コード例 #1
0
ファイル: flexicategories.php プロジェクト: bizanto/Hooked
 function fetchElement($name, $value, &$node, $control_name)
 {
     $filename = 'components/com_flexicontent/index.html';
     if (file_exists($filename)) {
         $doc =& JFactory::getDocument();
         $fieldName = $control_name . '[' . $name . ']';
         $values = explode(",", $value);
         require_once JPATH_ROOT . DS . "components" . DS . "com_flexicontent" . DS . "classes" . DS . "flexicontent.categories.php";
         $tree = flexicontent_cats::getCategoriesTree();
         $js = "\n\t\t\t\tfunction FLEXIClickCategory(obj) {\n\t\t\t\t\tvalues=new Array();\n\t\t\t\t\tfor(i=0,j=0;i<obj.options.length;i++) {\n\t\t\t\t\t\tif(obj.options[i].selected==true)\n\t\t\t\t\t\t\tvalues[j++] = obj.options[i].value;\n\t\t\t\t\t}\n\t\t\t\t\tvalues = values.concat();\n\t\t\t\t\tdocument.getElementById('a_id').value = values;\n\t\t\t\t}";
         $doc->addScriptDeclaration($js);
         $html = flexicontent_cats::buildcatselect($tree, $fieldName, $values, false, ' onClick="javascript:FLEXIClickCategory(this);" class="inputbox required validate-cid" multiple="multiple" size="8"', true);
         $html .= "\n<input type=\"hidden\" id=\"a_id\" name=\"{$fieldName}\" value=\"{$value}\" />";
         return $html;
     } else {
         echo "";
     }
 }
コード例 #2
0
 public static function decideCats(&$params)
 {
     global $globalcats;
     $display_cat_list = $params->get('display_cat_list', 0);
     $catids = $params->get('catids', array());
     $usesubcats = $params->get('usesubcats', 0);
     // FIND categories to display
     $allowed_cats = $disallowed_cats = false;
     if ($usesubcats) {
         // Find descendants of the categories
         $subcats = array();
         foreach ($catids as $catid) {
             $subcats = array_merge($subcats, array_map('trim', explode(",", $globalcats[$catid]->descendants)));
         }
         $catids = array_unique($subcats);
     }
     if ($display_cat_list == 1) {
         // include method
         $allowed_cats = $catids;
     } else {
         if ($display_cat_list == 2) {
             // exclude method
             $disallowed_cats = $catids;
         }
     }
     $tree = flexicontent_cats::getCategoriesTree();
     if ($allowed_cats) {
         foreach ($allowed_cats as $catid) {
             $allowedtree[$catid] = $tree[$catid];
         }
     }
     if ($disallowed_cats) {
         foreach ($disallowed_cats as $catid) {
             unset($tree[$catid]);
         }
         $allowedtree =& $tree;
     }
     if (!$allowed_cats && !$disallowed_cats) {
         $allowedtree =& $tree;
     }
     return $allowedtree;
 }
コード例 #3
0
 /**
  * Sorts and pads (indents) given categories according to their parent, thus creating a category tree by using recursion.
  * The sorting of categories is done by:
  * a. looping through all categories  v  in given children array padding all of category v with same padding
  * b. but for every category v that has a children array, it calling itself (recursion) in order to inject the children categories just bellow category v
  *
  * This function is based on the joomla 1.0 treerecurse 
  *
  * @access public
  * @return array
  */
 public static function treerecurse($parent_id, $indent, $list, &$children, $title, $maxlevel = 9999, $level = 0, $type = 1, $ancestors = null, $childs = null)
 {
     if (!$ancestors) {
         $ancestors = array();
     }
     $ROOT_CATEGORY_ID = !FLEXI_J16GE ? 0 : 1;
     if (@$children[$parent_id] && $level <= $maxlevel) {
         foreach ($children[$parent_id] as $v) {
             $id = $v->id;
             if (!in_array($v->parent_id, $ancestors) && $v->parent_id != 0) {
                 $ancestors[] = $v->parent_id;
             }
             if ($type) {
                 $pre = '<sup>|_</sup>&nbsp;';
                 $spacer = '.&nbsp;&nbsp;&nbsp;';
             } else {
                 $pre = '- ';
                 $spacer = '&nbsp;&nbsp;';
             }
             if ($title) {
                 if ($v->parent_id == $ROOT_CATEGORY_ID) {
                     $txt = '' . $v->title;
                 } else {
                     $txt = $pre . $v->title;
                 }
             } else {
                 if ($v->parent_id == $ROOT_CATEGORY_ID) {
                     $txt = '';
                 } else {
                     $txt = $pre;
                 }
             }
             $pt = $v->parent_id;
             $list[$id] = $v;
             $list[$id]->treename = "{$indent}{$txt}";
             $list[$id]->ancestors = $ancestors;
             $list[$id]->childrenarray = @$children[$id];
             $list[$id]->children = count(@$children[$id]);
             $list = flexicontent_cats::treerecurse($id, $indent . $spacer, $list, $children, $title, $maxlevel, $level + 1, $type, $ancestors, $childs);
         }
     }
     return $list;
 }
コード例 #4
0
                 }
             }
         }
         // ALSO consider categories filter if it is active in current view
     } else {
         $_fld_classes .= ' fc_autosubmit_exclude';
         // exclude from autosubmit because we need to get single category SEF url before submitting, and then submit ...
         $_fld_size = "";
         $_fld_onchange = ' onchange="update_' . $form_name . '();" ';
         $_fld_name = $catid_fieldname;
     }
     $_fld_attributes = ' class="' . $_fld_classes . '" ' . $_fld_size . $_fld_onchange . $_fld_multiple;
     $allowedtree = modFlexifilterHelper::decideCats($params);
     $selected_cats = $mcats_selection ? $cids : ($catid ? $catid : "");
     $top = false;
     $cats_select_field = flexicontent_cats::buildcatselect($allowedtree, $_fld_name, $selected_cats, $top, $_fld_attributes, $check_published = true, $check_perms = false, array(), $require_all = false);
 } else {
     if ($catid) {
         $cat_hidden_field = '<input type="hidden" name="cid" value="' . $catid . '"/>';
     }
 }
 $limit_selector = flexicontent_html::limit_selector($params, $form_name, $autosubmit);
 $orderby_selector = flexicontent_html::ordery_selector($params, $form_name, $autosubmit);
 // 2. Get category, this is needed so that we get only the allowed filters of the category
 // allowed filters are set in the category options (configuration)
 $saved_cid = JRequest::getVar('cid', '');
 // save cid ...
 $saved_layout = JRequest::getVar('layout');
 // save layout ...
 $saved_option = JRequest::getVar('option');
 // save option ...
コード例 #5
0
    function display($tpl = null)
    {
        // ********************
        // Initialise variables
        // ********************
        $app = JFactory::getApplication();
        $jinput = $app->input;
        $option = $jinput->get('option', '', 'cmd');
        $view = $jinput->get('view', '', 'cmd');
        $task = $jinput->get('task', '', 'cmd');
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        // Get model
        $model = $this->getModel();
        // Some flags
        $has_zlib = function_exists("zlib_encode");
        //version_compare(PHP_VERSION, '5.4.0', '>=');
        // Get session information
        $conf = $session->get('csvimport_config', "", 'flexicontent');
        $conf = unserialize($conf ? $has_zlib ? zlib_decode(base64_decode($conf)) : base64_decode($conf) : "");
        $lineno = $session->get('csvimport_lineno', 999999, 'flexicontent');
        $session->set('csvimport_parse_log', null, 'flexicontent');
        // This is the flag if CSV file has been parsed (import form already submitted), thus to display the imported data
        // **************************
        // Add css and js to document
        // **************************
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VHASH);
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VHASH);
        // Add JS frameworks
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        flexicontent_html::loadFramework('flexi-lib');
        // Add js function to overload the joomla submitform validation
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/admin.js', FLEXI_VHASH);
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/validate.js', FLEXI_VHASH);
        // *****************************
        // Get user's global permissions
        // *****************************
        $perms = FlexicontentHelperPerm::getPerm();
        // ************************
        // Create Submenu & Toolbar
        // ************************
        // Create Submenu (and also check access to current view)
        FLEXISubmenu('CanImport');
        // Create document/toolbar titles
        $doc_title = JText::_('FLEXI_IMPORT');
        $site_title = $document->getTitle();
        JToolBarHelper::title($doc_title, 'import');
        $document->setTitle($doc_title . ' - ' . $site_title);
        // Create the toolbar
        $toolbar = JToolBar::getInstance('toolbar');
        if (!empty($conf)) {
            if ($task != 'processcsv') {
                $ctrl_task = 'import.processcsv';
                $import_btn_title = empty($lineno) ? 'FLEXI_IMPORT_START_TASK' : 'FLEXI_IMPORT_CONTINUE_TASK';
                JToolBarHelper::custom($ctrl_task, 'save.png', 'save.png', $import_btn_title, $list_check = false);
            }
            $ctrl_task = 'import.clearcsv';
            JToolBarHelper::custom($ctrl_task, 'cancel.png', 'cancel.png', 'FLEXI_IMPORT_CLEAR_TASK', $list_check = false);
        } else {
            $ctrl_task = 'import.initcsv';
            JToolBarHelper::custom($ctrl_task, 'import.png', 'import.png', 'FLEXI_IMPORT_PREPARE_TASK', $list_check = false);
            $ctrl_task = 'import.testcsv';
            JToolBarHelper::custom($ctrl_task, 'test.png', 'test.png', 'FLEXI_IMPORT_TEST_FILE_FORMAT', $list_check = false);
        }
        //JToolBarHelper::Back();
        if ($perms->CanConfig) {
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
            $session = JFactory::getSession();
            $fc_screen_width = (int) $session->get('fc_screen_width', 0, 'flexicontent');
            $_width = $fc_screen_width && $fc_screen_width - 84 > 940 ? $fc_screen_width - 84 > 1400 ? 1400 : $fc_screen_width - 84 : 940;
            $fc_screen_height = (int) $session->get('fc_screen_height', 0, 'flexicontent');
            $_height = $fc_screen_height && $fc_screen_height - 128 > 550 ? $fc_screen_height - 128 > 1000 ? 1000 : $fc_screen_height - 128 : 550;
            JToolBarHelper::preferences('com_flexicontent', $_height, $_width, 'Configuration');
        }
        // Get types
        $types = flexicontent_html::getTypesList($_type_ids = false, $_check_perms = false, $_published = true);
        // Get Languages
        $languages = FLEXIUtilities::getLanguages('code');
        // Get categories
        global $globalcats;
        $categories = $globalcats;
        // ************************************
        // Decide layout to load: 'import*.php'
        // ************************************
        $this->setLayout('import');
        $this->sidebar = FLEXI_J30GE ? JHtmlSidebar::render() : null;
        // Execute the import task, load the log-like AJAX-based layout (import_process.php), to display results including any warnings
        if (!empty($conf) && $task == 'processcsv') {
            $this->assignRef('conf', $conf);
            parent::display('process');
            return;
        } else {
            if (!empty($conf)) {
                $this->assignRef('conf', $conf);
                $this->assignRef('cparams', $cparams);
                $this->assignRef('types', $types);
                $this->assignRef('languages', $languages);
                $this->assignRef('categories', $globalcats);
                parent::display('list');
                return;
            }
        }
        // Session config is empty, means import form has not been submited, display the form
        // We will display import form which is not 'default.php', it is 'import.php'
        // else ...
        // Check is session table DATA column is not mediumtext (16MBs, it can be 64 KBs ('text') in some sites that were not properly upgraded)
        $tblname = 'session';
        $dbprefix = $app->getCfg('dbprefix');
        $dbname = $app->getCfg('db');
        $db->setQuery("SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . $dbname . "' AND TABLE_NAME = '" . $dbprefix . $tblname . "'");
        $jession_coltypes = $db->loadAssocList('COLUMN_NAME');
        $_dataColType = strtolower($jession_coltypes['data']['DATA_TYPE']);
        $_dataCol_wrongSize = $_dataColType != 'mediumtext' && $_dataColType != 'longtext';
        // If data type is "text" it is safe to assume that it can be converted to "mediumtext",
        // since "text" means that session table is not memory storage,
        // plus it is already stored externally aka operation will be quick ?
        /*if ($_dataCol_wrongSize && $_dataColType == 'text')
        		{
        			$db->setQuery("ALTER TABLE `#__session` MODIFY `data` MEDIUMTEXT");
        			$db->execute();
        			$_dataCol_wrongSize = false;
        		}*/
        if ($_dataCol_wrongSize) {
            $app->enqueueMessage("Joomla DB table: <b>'session'</b> has a <b>'data'</b> column with type: <b>'" . $_dataColType . "'</b>, instead of expected type <b>'mediumtext'</b>. Trying to import large data files may fail", "notice");
        }
        $formvals = array();
        // Retrieve Basic configuration
        $formvals['type_id'] = $model->getState('type_id');
        $formvals['language'] = $model->getState('language');
        $formvals['state'] = $model->getState('state');
        $formvals['access'] = $model->getState('access');
        // Main and secondary categories, tags
        $formvals['maincat'] = $model->getState('maincat');
        $formvals['maincat_col'] = $model->getState('maincat_col');
        $formvals['seccats'] = $model->getState('seccats');
        $formvals['seccats_col'] = $model->getState('seccats_col');
        $formvals['tags_col'] = $model->getState('tags_col');
        // Publication: Author/modifier
        $formvals['created_by_col'] = $model->getState('created_by_col');
        $formvals['modified_by_col'] = $model->getState('modified_by_col');
        // Publication: META data
        $formvals['metadesc_col'] = $model->getState('metadesc_col');
        $formvals['metakey_col'] = $model->getState('metakey_col');
        // Publication: dates
        $formvals['modified_col'] = $model->getState('modified_col');
        $formvals['created_col'] = $model->getState('modified_col');
        $formvals['publish_up_col'] = $model->getState('publish_up_col');
        $formvals['publish_down_col'] = $model->getState('publish_down_col');
        // Advanced configuration
        $formvals['ignore_unused_cols'] = $model->getState('ignore_unused_cols');
        $formvals['id_col'] = $model->getState('id_col');
        $formvals['items_per_step'] = $model->getState('items_per_step');
        // CSV file format
        $formvals['mval_separator'] = $model->getState('mval_separator');
        $formvals['mprop_separator'] = $model->getState('mprop_separator');
        $formvals['field_separator'] = $model->getState('field_separator');
        $formvals['enclosure_char'] = $model->getState('enclosure_char');
        $formvals['record_separator'] = $model->getState('record_separator');
        $formvals['debug_records'] = $model->getState('debug_records');
        // ******************
        // Create form fields
        // ******************
        $lists['type_id'] = flexicontent_html::buildtypesselect($types, 'type_id', $formvals['type_id'], true, 'class="required use_select2_lib"', 'type_id');
        $actions_allowed = array('core.create');
        // Creating categorories tree for item assignment, we use the 'create' privelege
        // build the main category select list
        $attribs = 'class="use_select2_lib required"';
        $fieldname = 'maincat';
        $lists['maincat'] = flexicontent_cats::buildcatselect($categories, $fieldname, $formvals['maincat'], 2, $attribs, false, true, $actions_allowed);
        // build the secondary categories select list
        $class = "use_select2_lib";
        $attribs = 'multiple="multiple" size="10" class="' . $class . '"';
        $fieldname = 'seccats[]';
        $lists['seccats'] = flexicontent_cats::buildcatselect($categories, $fieldname, $formvals['seccats'], false, $attribs, false, true, $actions_allowed, $require_all = true);
        // build languages list
        // Retrieve author configuration
        $authorparams = flexicontent_db::getUserConfig($user->id);
        $allowed_langs = $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $lists['languages'] = flexicontent_html::buildlanguageslist('language', ' style="vertical-align:top;" onchange="var m=jQuery(\'#fc_import_about_langcol\'); this.value ? m.hide(600) : m.show(600);"', $formvals['language'], 6, $allowed_langs, $published_only = true, $disable_langs = null, $add_all = true, $conf = array('required' => true)) . '
			<span class="fc-mssg-inline fc-note fc-nobgimage" id="fc_import_about_langcol" style="display:none;">
				' . JText::_('FLEXI_USE_LANGUAGE_COLUMN_TIP') . '
			</span>';
        $lists['states'] = flexicontent_html::buildstateslist('state', ' style="vertical-align:top;" onchange="var m=jQuery(\'#fc_import_about_statecol\'); this.value ? m.hide(600) : m.show(600);"', $formvals['state'], 2) . '<span class="fc-mssg-inline fc-note fc-nobgimage" id="fc_import_about_statecol" style="display:none;">
				' . JText::_('FLEXI_USE_STATE_COLUMN_TIP') . '
			</span>';
        // build access level filter
        $access_levels = JHtml::_('access.assetgroups');
        array_unshift($access_levels, JHtml::_('select.option', '0', "Use 'access' column"));
        array_unshift($access_levels, JHtml::_('select.option', '', 'FLEXI_SELECT_ACCESS_LEVEL'));
        $fieldname = 'access';
        // make multivalue
        $elementid = 'access';
        $attribs = 'class="required use_select2_lib"';
        $lists['access'] = JHTML::_('select.genericlist', $access_levels, $fieldname, $attribs, 'value', 'text', $formvals['access'], $elementid, $translate = true);
        // Ignore warnings because component may not be installed
        $warnHandlers = JERROR::getErrorHandling(E_WARNING);
        JERROR::setErrorHandling(E_WARNING, 'ignore');
        // Reset the warning handler(s)
        foreach ($warnHandlers as $mode) {
            JERROR::setErrorHandling(E_WARNING, $mode);
        }
        // ********************************************************************************
        // Get field names (from the header line (row 0), and remove it form the data array
        // ********************************************************************************
        $file_field_types_list = '"image","file"';
        $q = 'SELECT id, name, label, field_type FROM #__flexicontent_fields AS fi' . ' WHERE fi.field_type IN (' . $file_field_types_list . ')';
        $db->setQuery($q);
        $file_fields = $db->loadObjectList('name');
        //assign data to template
        $this->assignRef('model', $model);
        $this->assignRef('lists', $lists);
        $this->assignRef('user', $user);
        $this->assignRef('cparams', $cparams);
        $this->assignRef('file_fields', $file_fields);
        $this->assignRef('formvals', $formvals);
        parent::display($tpl);
    }
コード例 #6
0
    /**
     * Creates the item page
     *
     * @since 1.0
     */
    function display($tpl = null)
    {
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        global $globalcats;
        $categories = $globalcats;
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $config = JFactory::getConfig();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $option = JRequest::getVar('option');
        $nullDate = $db->getNullDate();
        // Get the COMPONENT only parameters
        // Get component parameters
        $params = new JRegistry();
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $params->merge($cparams);
        $params = clone JComponentHelper::getParams('com_flexicontent');
        // Some flags
        $enable_translation_groups = flexicontent_db::useAssociations();
        //$params->get("enable_translation_groups");
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        // Add css to document
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VERSION);
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VERSION);
        // Fields common CSS
        $document->addStyleSheetVersion(JURI::root(true) . '/components/com_flexicontent/assets/css/flexi_form_fields.css', FLEXI_VERSION);
        // Add JS frameworks
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        flexicontent_html::loadFramework('flexi-lib');
        // Add js function to overload the joomla submitform validation
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/admin.js', FLEXI_VERSION);
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/validate.js', FLEXI_VERSION);
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/itemscreen.js', FLEXI_VERSION);
        // ***********************
        // Get data from the model
        // ***********************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        $item = $model->getItem();
        $form = $this->get('Form');
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // ***************************
        // Get Associated Translations
        // ***************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        $langs = FLEXIUtilities::getLanguages('code');
        // Get item id and new flag
        $cid = $model->getId();
        $isnew = !$cid;
        // Create and set a unique item id for plugins that needed it
        if ($cid) {
            $unique_tmp_itemid = $cid;
        } else {
            $unique_tmp_itemid = $app->getUserState('com_flexicontent.edit.item.unique_tmp_itemid');
            $unique_tmp_itemid = $unique_tmp_itemid ? $unique_tmp_itemid : date('_Y_m_d_h_i_s_', time()) . uniqid(true);
        }
        //print_r($unique_tmp_itemid);
        JRequest::setVar('unique_tmp_itemid', $unique_tmp_itemid);
        // Get number of subscribers
        $subscribers = $model->getSubscribersCount();
        // ******************
        // Version Panel data
        // ******************
        // Get / calculate some version related variables
        $versioncount = $model->getVersionCount();
        $versionsperpage = $params->get('versionsperpage', 10);
        $pagecount = (int) ceil($versioncount / $versionsperpage);
        // Data need by version panel: (a) current version page, (b) currently active version
        $current_page = 1;
        $k = 1;
        $allversions = $model->getVersionList();
        foreach ($allversions as $v) {
            if ($k > 1 && ($k - 1) % $versionsperpage == 0) {
                $current_page++;
            }
            if ($v->nr == $item->version) {
                break;
            }
            $k++;
        }
        // Finally fetch the version data for versions in current page
        $versions = $model->getVersionList(($current_page - 1) * $versionsperpage, $versionsperpage);
        // Create display of average rating
        $ratings = $model->getRatingDisplay();
        // *****************
        // Type related data
        // *****************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get and merge type parameters
        $tparams = $this->get('Typeparams');
        $tparams = new JRegistry($tparams);
        $params->merge($tparams);
        // Apply type configuration if it type is set
        // Get user allowed permissions on the item ... to be used by the form rendering
        // Also hide parameters panel if user can not edit parameters
        $perms = $this->_getItemPerms($item);
        if (!$perms['canparams']) {
            $document->addStyleDeclaration('#details-options {display:none;}');
        }
        // ******************
        // Create the toolbar
        // ******************
        $toolbar = JToolBar::getInstance('toolbar');
        $tip_class = FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
        // SET toolbar title
        if ($cid) {
            JToolBarHelper::title(JText::_('FLEXI_EDIT_ITEM'), 'itemedit');
            // Editing existing item
        } else {
            JToolBarHelper::title(JText::_('FLEXI_NEW_ITEM'), 'itemadd');
            // Creating new item
        }
        // **************
        // Common Buttons
        // **************
        // Applying new item type is a special case that has not loaded custom fieds yet
        JToolBarHelper::apply($item->type_id ? 'items.apply' : 'items.apply_type', !$isnew ? 'FLEXI_APPLY' : ($typesselected->id ? 'FLEXI_ADD' : 'FLEXI_APPLY_TYPE'), false);
        /*if (!$isnew || $item->version) flexicontent_html::addToolBarButton(
        		'FLEXI_FAST_APPLY', $btn_name='apply_ajax', $full_js="Joomla.submitbutton('items.apply_ajax')", $msg_alert='', $msg_confirm='',
        		$btn_task='items.apply_ajax', $extra_js='', $btn_list=false, $btn_menu=true, $btn_confirm=false, $btn_class="".$tip_class, $btn_icon="icon-loop",
        		'data-placement="bottom" title="Fast saving, without reloading the form. <br/><br/>Note: new files will not be uploaded, <br/>- in such a case please use \'Apply\'"');*/
        if (!$isnew || $item->version) {
            JToolBarHelper::save('items.save');
        }
        if (!$isnew || $item->version) {
            JToolBarHelper::custom('items.saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
        }
        JToolBarHelper::cancel('items.cancel');
        // ***********************
        // Add a preview button(s)
        // ***********************
        //$_sh404sef = JPluginHelper::isEnabled('system', 'sh404sef') && $config->get('sef');
        $_sh404sef = defined('SH404SEF_IS_RUNNING') && $config->get('sef');
        if ($cid) {
            // Domain URL and autologin vars
            $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
            $autologin = '';
            //$params->get('autoflogin', 1) ? '&fcu='.$user->username . '&fcp='.$user->password : '';
            // Check if we are in the backend, in the back end we need to set the application to the site app instead
            // we do not remove 'isAdmin' check so that we can copy later without change, e.g. to a plugin
            $isAdmin = JFactory::getApplication()->isAdmin();
            if ($isAdmin && !$_sh404sef) {
                JFactory::$application = JApplication::getInstance('site');
            }
            // Create the URL
            $item_url = FlexicontentHelperRoute::getItemRoute($item->id . ':' . $item->alias, $categories[$item->catid]->slug) . ($item->language != '*' ? '&lang=' . substr($item->language, 0, 2) : '');
            $item_url = $_sh404sef ? Sh404sefHelperGeneral::getSefFromNonSef($item_url, $fullyQualified = true, $xhtml = false, $ssl = null) : JRoute::_($item_url);
            // Check if we are in the backend again
            // In backend we need to remove administrator from URL as it is added even though we've set the application to the site app
            if ($isAdmin && !$_sh404sef) {
                $admin_folder = str_replace(JURI::root(true), '', JURI::base(true));
                $item_url = str_replace($admin_folder . '/', '/', $item_url);
                // Restore application
                JFactory::$application = JApplication::getInstance('administrator');
            }
            $previewlink = $item_url . (strstr($item_url, '?') ? '&amp;' : '?') . 'preview=1' . $autologin;
            //$previewlink     = str_replace('&amp;', '&', $previewlink);
            //$previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $categories[$item->catid]->slug)) .$autologin;
            // PREVIEW for latest version
            if (!$params->get('use_versioning', 1) || $item->version == $item->current_version && $item->version == $item->last_version) {
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small btn-info spaced-btn" onClick="window.open(\'' . $previewlink . '\');"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('Preview') . '</button>', 'preview');
            } else {
                // Add a preview button for (currently) LOADED version of the item
                $previewlink_loaded_ver = $previewlink . '&version=' . $item->version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_loaded_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FORM_LOADED_VERSION') . ' [' . $item->version . ']</button>', 'preview');
                // Add a preview button for currently ACTIVE version of the item
                $previewlink_active_ver = $previewlink . '&version=' . $item->current_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_active_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FRONTEND_ACTIVE_VERSION') . ' [' . $item->current_version . ']</button>', 'preview');
                // Add a preview button for currently LATEST version of the item
                $previewlink_last_ver = $previewlink;
                //'&version='.$item->last_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_last_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_LATEST_SAVED_VERSION') . ' [' . $item->last_version . ']</button>', 'preview');
            }
            JToolBarHelper::spacer();
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
        }
        // ************************
        // Add modal layout editing
        // ************************
        if ($perms['cantemplates']) {
            JToolBarHelper::divider();
            if (!$isnew || $item->version) {
                flexicontent_html::addToolBarButton('FLEXI_EDIT_LAYOUT', $btn_name = 'apply_ajax', $full_js = "var url = jQuery(this).attr('data-href'); fc_showDialog(url, 'fc_modal_popup_container'); return false;", $msg_alert = '', $msg_confirm = '', $btn_task = 'items.apply_ajax', $extra_js = '', $btn_list = false, $btn_menu = true, $btn_confirm = false, $btn_class = "btn-info" . $tip_class, $btn_icon = "icon-pencil", 'data-placement="bottom" data-href="index.php?option=com_flexicontent&amp;view=template&amp;type=items&amp;tmpl=component&amp;ismodal=1&amp;folder=' . $item->itemparams->get('ilayout', $tparams->get('ilayout', 'default')) . '" title="Edit the display layout of this item. <br/><br/>Note: this layout maybe assigned to content types or other items, thus changing it will effect them too"');
            }
        }
        // Check if saving an item that translates an original content in site's default language
        $site_default = substr(flexicontent_html::getSiteDefaultLang(), 0, 2);
        $is_content_default_lang = $site_default == substr($item->language, 0, 2);
        // *****************************************************************************
        // Get (CORE & CUSTOM) fields and their VERSIONED values and then
        // (a) Apply Content Type Customization to CORE fields (label, description, etc)
        // (b) Create the edit html of the CUSTOM fields by triggering 'onDisplayField'
        // *****************************************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $fields = $this->get('Extrafields');
        $item->fields =& $fields;
        if ($print_logging_info) {
            $fc_run_times['get_field_vals'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $jcustom = $app->getUserState('com_flexicontent.edit.item.custom');
        //print_r($jcustom);
        foreach ($fields as $field) {
            // a. Apply CONTENT TYPE customizations to CORE FIELDS, e.g a type specific label & description
            // NOTE: the field parameters are already created so there is not need to call this for CUSTOM fields, which do not have CONTENT TYPE customizations
            if ($field->iscore) {
                FlexicontentFields::loadFieldConfig($field, $item);
            }
            // b. Create field 's editing HTML (the form field)
            // NOTE: this is DONE only for CUSTOM fields, since form field html is created by the form for all CORE fields, EXCEPTION is the 'text' field (see bellow)
            if (!$field->iscore) {
                if (isset($jcustom[$field->name])) {
                    $field->value = array();
                    foreach ($jcustom[$field->name] as $i => $_val) {
                        $field->value[$i] = $_val;
                    }
                }
                $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                if ($is_editable) {
                    FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    if ($field->untranslatable) {
                        $field->html = (!isset($field->html) ? '<div class="fc-mssg-inline fc-warning" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_PLEASE_PUBLISH_THIS_PLUGIN') . '</div><div class="clear"></div>' : '') . '<div class="alert alert-info fc-small fc-iblock" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_FIELD_VALUE_IS_NON_TRANSLATABLE') . '</div>' . "\n" . (isset($field->html) ? '<div class="clear"></div>' . $field->html : '');
                    }
                } else {
                    if ($field->valueseditable == 1) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                    } else {
                        if ($field->valueseditable == 2) {
                            FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                            $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>' . "\n" . $field->display;
                        } else {
                            if ($field->valueseditable == 3) {
                                FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                                $field->html = $field->display;
                            } else {
                                if ($field->valueseditable == 4) {
                                    $field->html = '';
                                    $field->formhidden = 4;
                                }
                            }
                        }
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // *************************
        // Get tags used by the item
        // *************************
        $usedtagsIds = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtags = $model->getUsedtagsData($usedtagsIds);
        // *******************************
        // Get categories used by the item
        // *******************************
        if ($isnew) {
            // Case for preselected main category for new items
            $maincat = $item->catid ? $item->catid : JRequest::getInt('maincat', 0);
            if (!$maincat) {
                $maincat = $app->getUserStateFromRequest($option . '.items.filter_cats', 'filter_cats', '', 'int');
            }
            if ($maincat) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($tparams->get('cid_default')) {
                $selectedcats = $tparams->get('cid_default');
            }
            if ($tparams->get('catid_default')) {
                $item->catid = $tparams->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        //$selectedcats 	= $isnew ? array() : $fields['categories']->value;
        //echo "<br/>row->tags: "; print_r($item->tags);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsIds);
        //echo "<br/>usedtags (data): "; print_r($usedtags);
        //echo "<br/>row->categories: "; print_r($item->categories);
        //echo "<br/>selectedcats: "; print_r($selectedcats);
        // *********************************************************************************************
        // Build select lists for the form field. Only few of them are used in J1.6+, since we will use:
        // (a) form XML file to declare them and then (b) getInput() method form field to create them
        // *********************************************************************************************
        // First clean form data, we do this after creating the description field which may contain HTML
        JFilterOutput::objectHTMLSafe($item, ENT_QUOTES);
        $lists = array();
        // build state list
        $non_publishers_stategrp = $perms['isSuperAdmin'] || $item->state == -3 || $item->state == -4;
        $special_privelege_stategrp = $item->state == 2 || $perms['canarchive'] || ($item->state == -2 || $perms['candelete']);
        $state = array();
        // Using <select> groups
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_PUBLISHERS_WORKFLOW_STATES'));
        }
        $state[] = JHTML::_('select.option', 1, JText::_('FLEXI_PUBLISHED'));
        $state[] = JHTML::_('select.option', 0, JText::_('FLEXI_UNPUBLISHED'));
        $state[] = JHTML::_('select.option', -5, JText::_('FLEXI_IN_PROGRESS'));
        // States reserved for workflow
        if ($non_publishers_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_NON_PUBLISHERS_WORKFLOW_STATES'));
        }
        if ($item->state == -3 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -3, JText::_('FLEXI_PENDING'));
        }
        if ($item->state == -4 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -4, JText::_('FLEXI_TO_WRITE'));
        }
        // Special access states
        if ($special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_SPECIAL_ACTION_STATES'));
        }
        if ($item->state == 2 || $perms['canarchive']) {
            $state[] = JHTML::_('select.option', 2, JText::_('FLEXI_ARCHIVED'));
        }
        if ($item->state == -2 || $perms['candelete']) {
            $state[] = JHTML::_('select.option', -2, JText::_('FLEXI_TRASHED'));
        }
        // Close last <select> group
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
        }
        $fieldname = 'jform[state]';
        $elementid = 'jform_state';
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, $fieldname, $attribs, 'value', 'text', $item->state, $elementid);
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
            // build featured flag
            $fieldname = 'jform[featured]';
            $elementid = 'jform_featured';
            /*
            $options = array();
            $options[] = JHTML::_('select.option',  0, JText::_( 'FLEXI_NO' ) );
            $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_YES' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
            $lists['featured'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $item->featured, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array(0 => JText::_('FLEXI_NO'), 1 => JText::_('FLEXI_YES'));
            $lists['featured'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id == $item->featured ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['featured'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // *** EOF: J1.5 SPECIFIC SELECT LISTS
        // build version approval list
        $fieldname = 'jform[vstate]';
        $elementid = 'jform_vstate';
        /*
        $options = array();
        $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_NO' ) );
        $options[] = JHTML::_('select.option',  2, JText::_( 'FLEXI_YES' ) );
        $attribs = FLEXI_J16GE ? ' style ="float:left!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
        $lists['vstate'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', 2, $elementid);
        */
        $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
        $attribs = ' class="' . $classes . '" ';
        $i = 1;
        $options = array(1 => JText::_('FLEXI_NO'), 2 => JText::_('FLEXI_YES'));
        $lists['vstate'] = '';
        foreach ($options as $option_id => $option_label) {
            $checked = $option_id == 2 ? ' checked="checked"' : '';
            $elementid_no = $elementid . '_' . $i;
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
            }
            $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
            $lists['vstate'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '&nbsp;' . JText::_($option_label) . '</label>';
            }
            $i++;
        }
        // build field for notifying subscribers
        if (!$subscribers) {
            $lists['notify'] = !$isnew ? JText::_('FLEXI_NO_SUBSCRIBERS_EXIST') : '';
        } else {
            // b. Check if notification emails to subscribers , were already sent during current session
            $subscribers_notified = $session->get('subscribers_notified', array(), 'flexicontent');
            if (!empty($subscribers_notified[$item->id])) {
                $lists['notify'] = JText::_('FLEXI_SUBSCRIBERS_ALREADY_NOTIFIED');
            } else {
                // build favs notify field
                $fieldname = 'jform[notify]';
                $elementid = 'jform_notify';
                /*
                $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
                $lists['notify'] = '<input type="checkbox" name="jform[notify]" id="jform_notify" '.$attribs.' /> '. $lbltxt;
                */
                $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
                $attribs = ' class="' . $classes . '" ';
                $lbltxt = $subscribers . ' ' . JText::_($subscribers > 1 ? 'FLEXI_SUBSCRIBERS' : 'FLEXI_SUBSCRIBER');
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '<label class="fccheckradio_lbl" for="' . $elementid . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . $lbltxt . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['notify'] = ' <input type="checkbox" id="' . $elementid . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="1" ' . $extra_params . ' checked="checked" />';
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '&nbsp;' . $lbltxt . '</label>';
                }
            }
        }
        // Retrieve author configuration
        $authorparams = flexicontent_db::getUserConfig($user->id);
        // Get author's maximum allowed categories per item and set js limitation
        $max_cat_assign = intval($authorparams->get('max_cat_assign', 0));
        $document->addScriptDeclaration('
			max_cat_assign_fc = ' . $max_cat_assign . ';
			existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
		');
        JText::script('FLEXI_TOO_MANY_ITEM_CATEGORIES', true);
        // Creating categorories tree for item assignment, we use the 'create' privelege
        $actions_allowed = array('core.create');
        // Featured categories form field
        $featured_cats_parent = $params->get('featured_cats_parent', 0);
        $featured_cats = array();
        $enable_featured_cid_selector = $perms['multicat'] && $perms['canchange_featcat'];
        if ($featured_cats_parent) {
            $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
            $disabled_cats = $params->get('featured_cats_parent_disable', 1) ? array($featured_cats_parent) : array();
            $featured_sel = array();
            foreach ($selectedcats as $item_cat) {
                if (isset($featured_tree[$item_cat])) {
                    $featured_sel[] = $item_cat;
                }
            }
            $class = "use_select2_lib select2_list_selected";
            $attribs = 'class="' . $class . '" multiple="multiple" size="8"';
            $attribs .= $enable_featured_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[featured_cid][]';
            $lists['featured_cid'] = ($enable_featured_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($featured_tree, $fieldname, $featured_sel, 3, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            // Do not display, if not configured or not allowed to the user
            $lists['featured_cid'] = false;
        }
        // Multi-category form field, for user allowed to use multiple categories
        $lists['cid'] = '';
        $enable_cid_selector = $perms['multicat'] && $perms['canchange_seccat'];
        if (1) {
            if ($tparams->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('cid_allowed_parent'), $depth_limit = 0);
                $disabled_cats = $tparams->get('cid_allowed_parent_disable', 1) ? array($tparams->get('cid_allowed_parent')) : array();
            } else {
                $cid_tree =& $categories;
                $disabled_cats = array();
            }
            // Get author's maximum allowed categories per item and set js limitation
            $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
            $document->addScriptDeclaration('
				max_cat_assign_fc = ' . $max_cat_assign . ';
				existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
			');
            $class = "mcat use_select2_lib select2_list_selected";
            $class .= $max_cat_assign ? " validate-fccats" : " validate";
            $attribs = 'class="' . $class . '" multiple="multiple" size="20"';
            $attribs .= $enable_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[cid][]';
            $skip_subtrees = $featured_cats_parent ? array($featured_cats_parent) : array();
            $lists['cid'] = ($enable_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($cid_tree, $fieldname, $selectedcats, false, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees, $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (count($selectedcats) > 1) {
                foreach ($selectedcats as $catid) {
                    $cat_titles[$catid] = $globalcats[$catid]->title;
                }
                $lists['cid'] .= implode(', ', $cat_titles);
            } else {
                $lists['cid'] = false;
            }
        }
        // Main category form field
        $class = 'scat use_select2_lib';
        if ($perms['multicat']) {
            $class .= ' validate-catid';
        } else {
            $class .= ' required';
        }
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[catid]';
        $enable_catid_selector = $isnew && !$tparams->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($tparams->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('catid_allowed_parent'), $depth_limit = 0);
            $disabled_cats = $tparams->get('catid_allowed_parent_disable', 1) ? array($tparams->get('catid_allowed_parent')) : array();
        } else {
            $catid_tree =& $categories;
            $disabled_cats = array();
        }
        $lists['catid'] = false;
        if (!empty($catid_tree)) {
            $disabled = $enable_catid_selector ? '' : ' disabled="disabled"';
            $attribs .= $disabled;
            $lists['catid'] = ($enable_catid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($catid_tree, $fieldname, $item->catid, 2, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (!$isnew && $item->catid) {
                $lists['catid'] = $globalcats[$item->catid]->title;
            }
        }
        //buid types selectlist
        $class = 'required use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[type_id]';
        $elementid = 'jform_type_id';
        $lists['type'] = flexicontent_html::buildtypesselect($types, $fieldname, $typesselected->id, 1, $attribs, $elementid, $check_perms = true);
        //build languages list
        $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        if (!$isnew && $allowed_langs) {
            $allowed_langs[] = $item->language;
        }
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $lists['languages'] = flexicontent_html::buildlanguageslist('jform[language]', 'class="use_select2_lib"', $item->language, 2, $allowed_langs);
        // Label for current item state: published, unpublished, archived etc
        switch ($item->state) {
            case 0:
                $published = JText::_('FLEXI_UNPUBLISHED');
                break;
            case 1:
                $published = JText::_('FLEXI_PUBLISHED');
                break;
            case -1:
                $published = JText::_('FLEXI_ARCHIVED');
                break;
            case -3:
                $published = JText::_('FLEXI_PENDING');
                break;
            case -5:
                $published = JText::_('FLEXI_IN_PROGRESS');
                break;
            case -4:
            default:
                $published = JText::_('FLEXI_TO_WRITE');
                break;
        }
        // **************************************************************
        // Handle Item Parameters Creation and Load their values for J1.5
        // In J1.6+ we declare them in the item form XML file
        // **************************************************************
        if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
            $form->setValue('publish_down', null, '');
            // Setting to text will break form date element
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        } else {
            if (!is_array($allowed_tmpls)) {
                $allowed_tmpls = explode("|", $allowed_tmpls);
            }
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
            $jform->load($tmpl->params);
            $tmpl->params = $jform;
            foreach ($tmpl->params->getGroup('attribs') as $field) {
                $fieldname = $field->__get('fieldname');
                $value = $item->itemparams->get($fieldname);
                if (strlen($value)) {
                    $tmpl->params->setValue($fieldname, 'attribs', $value);
                }
            }
        }
        // ******************************
        // Assign data to VIEW's template
        // ******************************
        $this->assignRef('document', $document);
        $this->assignRef('lists', $lists);
        $this->assignRef('row', $item);
        if (FLEXI_J16GE) {
            $this->assignRef('form', $form);
        } else {
            $this->assignRef('editor', $editor);
            $this->assignRef('pane', $pane);
            $this->assignRef('formparams', $formparams);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('typesselected', $typesselected);
        $this->assignRef('published', $published);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('fields', $fields);
        $this->assignRef('versions', $versions);
        $this->assignRef('ratings', $ratings);
        $this->assignRef('pagecount', $pagecount);
        $this->assignRef('params', $params);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('tmpls', $tmpls);
        $this->assignRef('usedtags', $usedtags);
        $this->assignRef('perms', $perms);
        $this->assignRef('current_page', $current_page);
        // Clear custom form data from session
        $app->setUserState($form->option . '.edit.' . $form->context . '.custom', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', false);
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        parent::display($tpl);
        if ($print_logging_info) {
            $fc_run_times['form_rendering'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
    }
コード例 #7
0
 public static function getItems(&$params, $ordering)
 {
     global $dump, $globalcats;
     global $modfc_jprof, $mod_fc_run_times;
     $app = JFactory::getApplication();
     // For specific cache issues
     if (empty($globalcats)) {
         if (FLEXI_SECTION || FLEXI_CAT_EXTENSION) {
             JPluginHelper::importPlugin('system', 'flexisystem');
             if (FLEXI_CACHE) {
                 // add the category tree to categories cache
                 $catscache = JFactory::getCache('com_flexicontent_cats');
                 $catscache->setCaching(1);
                 //force cache
                 $catscache->setLifeTime(84600);
                 //set expiry to one day
                 $globalcats = $catscache->call(array('plgSystemFlexisystem', 'getCategoriesTree'));
             } else {
                 $globalcats = plgSystemFlexisystem::getCategoriesTree();
             }
         }
     }
     // Initialize variables
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $view = JRequest::getVar('view');
     $option = JRequest::getVar('option');
     $fparams = $app->getParams('com_flexicontent');
     $show_noauth = $fparams->get('show_noauth', 0);
     // Date-Times are stored as UTC, we should use current UTC time to compare and not user time (requestTime),
     //  thus the items are published globally at the time the author specified in his/her local clock
     //$now		= $app->get('requestTime');
     $now = JFactory::getDate()->toSql();
     $nullDate = $db->getNullDate();
     // $display_category_data
     $apply_config_per_category = (int) $params->get('apply_config_per_category', 0);
     // *** METHODS that their 'ALL' value is 0, (these do not use current item information)
     // current item scope parameters
     $method_curitem = (int) $params->get('method_curitem', 0);
     // current language scope parameters
     $method_curlang = (int) $params->get('method_curlang', 0);
     // current item scope parameters
     $method_curuserfavs = (int) $params->get('method_curuserfavs', 0);
     // featured items scope parameters
     $method_featured = (int) $params->get('method_featured', 0);
     // featured items scope parameters
     $method_states = (int) $params->get('method_states', 0);
     $item_states = $params->get('item_states');
     $show_nocontent_msg = (int) $params->get('show_nocontent_msg', 1);
     // *** METHODS that their 'ALL' value is 1, that also have behaviour variable (most of them)
     // categories scope parameters
     $method_cat = (int) $params->get('method_cat', 1);
     $catids = $params->get('catids', array());
     $behaviour_cat = $params->get('behaviour_cat', 0);
     $treeinclude = $params->get('treeinclude');
     // types scope parameters
     $method_types = (int) $params->get('method_types', 1);
     $types = $params->get('types');
     $behaviour_types = $params->get('behaviour_types', 0);
     // authors scope parameters
     $method_auth = (int) $params->get('method_auth', 1);
     $authors = trim($params->get('authors'));
     $behaviour_auth = $params->get('behaviour_auth');
     // items scope parameters
     $method_items = (int) $params->get('method_items', 1);
     $items = trim($params->get('items'));
     $behaviour_items = $params->get('behaviour_items', 0);
     $excluded_tags = $params->get('excluded_tags', array());
     $excluded_tags = !is_array($excluded_tags) ? array($excluded_tags) : $excluded_tags;
     $relitems_fields = $params->get('relitems_fields', array());
     $relitems_fields = !is_array($relitems_fields) ? array($relitems_fields) : $relitems_fields;
     // tags scope parameters
     $method_tags = (int) $params->get('method_tags', 1);
     $tag_ids = $params->get('tag_ids', array());
     $tag_combine = $params->get('tag_combine', 0);
     // date scope parameters
     $method_dates = (int) $params->get('method_dates', 1);
     // parameter added later, maybe not to break compatibility this should be INCLUDE=3 by default ?
     $date_type = (int) $params->get('date_type', 0);
     $nulldates = (int) $params->get('nulldates', 0);
     $bdate = $params->get('bdate', '');
     $edate = $params->get('edate', '');
     $raw_bdate = $params->get('raw_bdate', 0);
     $raw_edate = $params->get('raw_edate', 0);
     $behaviour_dates = $params->get('behaviour_dates', 0);
     $date_compare = $params->get('date_compare', 0);
     $datecomp_field = (int) $params->get('datecomp_field', 0);
     // Server date
     $sdate = explode(' ', $now);
     $cdate = $sdate[0] . ' 00:00:00';
     // Set date comparators
     if ($date_type == 0) {
         // created
         $comp = 'i.created';
     } else {
         if ($date_type == 1) {
             // modified
             $comp = 'i.modified';
         } else {
             if ($date_type == 2) {
                 // publish up
                 $comp = 'i.publish_up';
             } else {
                 if ($date_type == 4) {
                     // publish down
                     $comp = 'i.publish_down';
                 } else {
                     // $date_type == 3
                     $comp = 'dfrel.value';
                 }
             }
         }
     }
     // custom field scope
     $method_filt = (int) $params->get('method_filt', 1);
     // parameter added later, maybe not to break compatibility this should be INCLUDE=3 by default ?
     $behaviour_filt = (int) $params->get('behaviour_filt', 0);
     $static_filters = $params->get('static_filters', '');
     $dynamic_filters = $params->get('dynamic_filters', '');
     // get module fetching parameters
     if ($params->get('skip_items', 0)) {
         $count = (int) $params->get('maxskipcount', 50);
     } else {
         $count = (int) $params->get('count', 5);
     }
     // get module display parameters
     $mod_image = $params->get('mod_image');
     // ************************************************************************************
     // filter by publication state, (except for item state which is a special scope, below)
     // ************************************************************************************
     $where = ' WHERE c.published = 1';
     $where .= FLEXI_J16GE ? '' : ' AND i.sectionid = ' . FLEXI_SECTION;
     $ignore_up_down_dates = $params->get('ignore_up_down_dates', 0);
     // 1: ignore publish_up, 2: ignore publish_donw, 3: ignore both
     $ignoreState = $params->get('use_list_items_in_any_state_acl', 0) && $user->authorise('flexicontent.ignoreviewstate', 'com_flexicontent');
     if (!$ignoreState && $ignore_up_down_dates != 3 && $ignore_up_down_dates != 1) {
         $where .= ' AND ( i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $db->Quote($now) . ' )';
     }
     if (!$ignoreState && $ignore_up_down_dates != 3 && $ignore_up_down_dates != 2) {
         $where .= ' AND ( i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $db->Quote($now) . ' )';
     }
     // *********************
     // filter by permissions
     // *********************
     $joinaccess = '';
     if (!$show_noauth) {
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $where .= ' AND ty.access IN (0,' . $aid_list . ')';
         $where .= ' AND mc.access IN (0,' . $aid_list . ')';
         $where .= ' AND  i.access IN (0,' . $aid_list . ')';
     }
     // *******************************************************
     // NON-STATIC behaviors that need current item information
     // *******************************************************
     $isflexi_itemview = $option == 'com_flexicontent' && $view == FLEXI_ITEMVIEW && JRequest::getInt('id');
     $isflexi_catview = $option == 'com_flexicontent' && $view == 'category' && (JRequest::getInt('cid') || JRequest::getVar('cids'));
     $curritem_date_field_needed = $behaviour_dates && $date_compare && $date_type == 3 && $datecomp_field;
     // Date field selected
     if (($behaviour_cat || $behaviour_types || $behaviour_auth || $behaviour_items || $curritem_date_field_needed || $behaviour_filt) && $isflexi_itemview) {
         // initialize variables
         $cid = JRequest::getInt('cid');
         $id = JRequest::getInt('id');
         $Itemid = JRequest::getInt('Itemid');
         // Check for new item nothing to retrieve,
         // NOTE: aborting execution if current view is not item view, but item view is required
         // and also proper usage of current item, both of these will be handled by SCOPEs
         $sel_date = '';
         $join_date = '';
         if ($curritem_date_field_needed) {
             $sel_date = ', dfrel.value as custom_date';
             $join_date = '	LEFT JOIN #__flexicontent_fields_item_relations AS dfrel' . '   ON ( i.id = dfrel.item_id AND dfrel.valueorder = 1 AND dfrel.field_id = ' . $datecomp_field . ' )';
         }
         if ($id) {
             $query = 'SELECT i.*, ie.*, GROUP_CONCAT(ci.catid SEPARATOR ",") as itemcats' . $sel_date . ' FROM #__content as i' . ' LEFT JOIN #__flexicontent_items_ext AS ie on ie.item_id = i.id' . ' LEFT JOIN #__flexicontent_cats_item_relations AS ci on ci.itemid = i.id' . $join_date . ' WHERE i.id = ' . $id . ' GROUP BY ci.itemid';
             $db->setQuery($query);
             $curitem = $db->loadObject();
             // Get item dates
             $idate = null;
             if ($date_type == 0) {
                 // created
                 $idate = $curitem->created;
             } else {
                 if ($date_type == 1) {
                     // modified
                     $idate = $curitem->modified;
                 } else {
                     if ($date_type == 2) {
                         // publish up
                         $idate = $curitem->publish_up;
                     } else {
                         if (isset($curitem->custom_date)) {
                             // $date_type == 3
                             $idate = $curitem->custom_date;
                         }
                     }
                 }
             }
             if ($idate) {
                 $idate = explode(' ', $idate);
                 $cdate = $idate[0] . ' 00:00:00';
             }
             $curritemcats = explode(',', $curitem->itemcats);
         }
     }
     // ******************
     // current item scope
     // ******************
     $currid = JRequest::getInt('id');
     if ($method_curitem == 1) {
         // exclude method  ---  exclude current item
         $where .= ' AND i.id <> ' . $currid;
     } else {
         if ($method_curitem == 2) {
             // include method  ---  include current item ONLY
             $where .= ' AND i.id = ' . $currid;
         } else {
             // All Items including current
         }
     }
     // **********************
     // current language scope
     // **********************
     $lang = flexicontent_html::getUserCurrentLang();
     if ($method_curlang == 1) {
         // exclude method  ---  exclude items of current language
         $where .= ' AND ie.language NOT LIKE ' . $db->Quote($lang . '%');
     } else {
         if ($method_curlang == 2) {
             // include method  ---  include items of current language ONLY
             $where .= ' AND ( ie.language LIKE ' . $db->Quote($lang . '%') . (FLEXI_J16GE ? ' OR ie.language="*" ' : '') . ' ) ';
         } else {
             // Items of any language
         }
     }
     // *****************************
     // current user favourites scope
     // *****************************
     $curruserid = (int) $user->get('id');
     if ($method_curuserfavs == 1) {
         // exclude method  ---  exclude currently logged user favourites
         $join_favs = ' LEFT OUTER JOIN #__flexicontent_favourites AS fav ON fav.itemid = i.id AND fav.userid = ' . $curruserid;
         $where .= ' AND fav.itemid IS NULL';
     } else {
         if ($method_curuserfavs == 2) {
             // include method  ---  include currently logged user favourites
             $join_favs = ' LEFT JOIN #__flexicontent_favourites AS fav ON fav.itemid = i.id';
             $where .= ' AND fav.userid = ' . $curruserid;
         } else {
             // All Items regardless of being favoured by current user
             $join_favs = '';
         }
     }
     // ******************************
     // joomla featured property scope
     // ******************************
     if ($method_featured == 1) {
         // exclude method  ---  exclude currently logged user favourites
         $where .= ' AND i.featured=0';
     } else {
         if ($method_featured == 2) {
             // include method  ---  include currently logged user favourites
             $where .= ' AND i.featured=1';
         } else {
             // All Items regardless of being featured or not
         }
     }
     // *****************
     // item states scope
     // *****************
     $item_states = is_array($item_states) ? implode(',', $item_states) : $item_states;
     if ($method_states == 0) {
         if (!$ignoreState) {
             // method normal: Published item states
             $where .= ' AND i.state IN ( 1, -5 )';
         }
     } else {
         // exclude trashed
         $where .= ' AND i.state <> -2';
         if ($item_states) {
             if ($method_states == 1) {
                 // exclude method  ---  exclude specified item states
                 $where .= ' AND i.state NOT IN (' . $item_states . ')';
             } else {
                 if ($method_states == 2) {
                     // include method  ---  include specified item states
                     $where .= ' AND i.state IN (' . $item_states . ')';
                 }
             }
         } else {
             if ($method_states == 2) {
                 // misconfiguration, when using include method with no state selected ...
                 echo "<b>WARNING:</b> Misconfigured item states scope, select at least one state or set states scope to Normal <small>(Published)</small><br/>";
                 return;
             }
         }
     }
     // ****************
     // categories scope
     // ****************
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_cat && $method_cat == 1) {
         if ($apply_config_per_category) {
             echo "<b>WARNING:</b> Misconfiguration warning, APPLY CONFIGURATION PER CATEGORY is possible only if CATEGORY SCOPE is set to either (a) INCLUDE(static selection of categories) or (b) items in same category as current item / or current category of category view<br/>";
             return;
         }
     } else {
         if (!$behaviour_cat) {
             // Check for empty statically selected records, and abort with error message
             if (empty($catids)) {
                 echo "<b>WARNING:</b> Misconfigured category scope, select at least one category or set category scope to ALL<br/>";
                 return;
             }
             // Make sure categories is an array
             $catids = is_array($catids) ? $catids : array($catids);
             // Retrieve extra categories, such children or parent categories
             $catids_arr = flexicontent_cats::getExtraCats($catids, $treeinclude, array());
             if (empty($catids_arr)) {
                 if ($show_nocontent_msg) {
                     echo JText::_("No viewable content in Current View for your Access Level");
                 }
                 return;
             }
             if ($method_cat == 2) {
                 // exclude method
                 if ($apply_config_per_category) {
                     echo "<b>WARNING:</b> Misconfiguration warning, APPLY CONFIGURATION PER CATEGORY is possible only if CATEGORY SCOPE is set to either (a) INCLUDE(static selection of categories) or (b) items in same category as current item / or current category of category view<br/>";
                     return;
                 }
                 $where .= ' AND c.id NOT IN (' . implode(',', $catids_arr) . ')';
             } else {
                 if ($method_cat == 3) {
                     // include method
                     if (!$apply_config_per_category) {
                         $where .= ' AND c.id IN (' . implode(',', $catids_arr) . ')';
                     } else {
                         // *** Applying configuration per category ***
                         foreach ($catids_arr as $catid) {
                             // The items retrieval query will be executed ... once per EVERY category
                             $multiquery_cats[$catid] = ' AND c.id = ' . $catid;
                         }
                         $params->set('dynamic_catids', serialize($catids_arr));
                         // Set dynamic catids to be used by the getCategoryData
                     }
                 }
             }
         } else {
             if (($behaviour_cat == 2 || $behaviour_cat == 4) && $apply_config_per_category) {
                 echo "<b>WARNING:</b> Misconfiguration warning, APPLY CONFIGURATION PER CATEGORY is possible only if CATEGORY SCOPE is set to either (a) INCLUDE(static selection of categories) or (b) items in same category as current item / or current category of category view<br/>";
                 return;
             }
             $currcat_valid_case = $behaviour_cat == 1 && $isflexi_itemview || $behaviour_cat == 3 && $isflexi_catview;
             if (!$currcat_valid_case) {
                 return;
                 // current view is not item OR category view ... , nothing to display
             }
             // IF $cid is not set then use the main category id of the (current) item
             if ($isflexi_itemview) {
                 $cid = $cid ? $cid : $curitem->catid;
                 // Retrieve extra categories, such children or parent categories
                 $catids_arr = flexicontent_cats::getExtraCats(array($cid), $treeinclude, $curritemcats);
             } else {
                 if ($isflexi_catview) {
                     $cid = JRequest::getInt('cid', 0);
                     if (!$cid) {
                         $_cids = JRequest::getVar('cids', '');
                         if (!is_array($_cids)) {
                             $_cids = preg_replace('/[^0-9,]/i', '', (string) $_cids);
                             $_cids = explode(',', $_cids);
                         }
                         // make sure given data are integers ... !!
                         $cids = array();
                         foreach ($_cids as $i => $_id) {
                             if ((int) $_id) {
                                 $cids[] = (int) $_id;
                             }
                         }
                         // Retrieve extra categories, such children or parent categories
                         $catids_arr = flexicontent_cats::getExtraCats(array($cid), $treeinclude, array());
                     }
                 } else {
                     return;
                     // nothing to display
                 }
             }
             // Retrieve extra categories, such children or parent categories
             $catids_arr = flexicontent_cats::getExtraCats(array($cid), $treeinclude, $isflexi_itemview ? $curritemcats : array());
             if (empty($catids_arr)) {
                 if ($show_nocontent_msg) {
                     echo JText::_("No viewable content in Current View for your Access Level");
                 }
                 return;
             }
             if ($behaviour_cat == 1 || $behaviour_cat == 3) {
                 if (!$apply_config_per_category) {
                     $where .= ' AND c.id IN (' . implode(',', $catids_arr) . ')';
                 } else {
                     // *** Applying configuration per category ***
                     foreach ($catids_arr as $catid) {
                         // The items retrieval query will be executed ... once per EVERY category
                         $multiquery_cats[$catid] = ' AND c.id = ' . $catid;
                     }
                     $params->set('dynamic_catids', serialize($catids_arr));
                     // Set dynamic catids to be used by the getCategoryData
                 }
             } else {
                 $where .= ' AND c.id NOT IN (' . implode(',', $catids_arr) . ')';
             }
         }
     }
     // Now check if no items need to be retrieved
     if ($count == 0) {
         return;
     }
     // ***********
     // types scope
     // ***********
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_types && $method_types == 1) {
     } else {
         if (!$behaviour_types) {
             // Check for empty statically selected records, and abort with error message
             if (empty($types)) {
                 echo "<b>WARNING:</b> Misconfigured types scope, select at least one item type or set types scope to ALL<br/>";
                 return;
             }
             // Make types a comma separated string of ids
             $types = is_array($types) ? implode(',', $types) : $types;
             if ($method_types == 2) {
                 // exclude method
                 $where .= ' AND ie.type_id NOT IN (' . $types . ')';
             } else {
                 if ($method_types == 3) {
                     // include method
                     $where .= ' AND ie.type_id IN (' . $types . ')';
                 }
             }
         } else {
             if (!$isflexi_itemview) {
                 return;
                 // current view is not item view ... , nothing to display
             }
             if ($behaviour_types == 1) {
                 $where .= ' AND ie.type_id = ' . (int) $curitem->type_id;
             } else {
                 $where .= ' AND ie.type_id <> ' . (int) $curitem->type_id;
             }
         }
     }
     // ************
     // author scope
     // ************
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_auth && $method_auth == 1) {
     } else {
         if (!$behaviour_auth) {
             // Check for empty statically selected records, and abort with error message
             if (empty($authors)) {
                 echo "<b>WARNING:</b> Misconfigured author scope, select at least one author or set author scope to ALL<br/>";
                 return;
             }
             if ($method_auth == 2) {
                 // exclude method
                 $where .= ' AND i.created_by NOT IN (' . $authors . ')';
             } else {
                 if ($method_auth == 3) {
                     // include method
                     $where .= ' AND i.created_by IN (' . $authors . ')';
                 }
             }
         } else {
             if (!$isflexi_itemview && $behaviour_auth < 3) {
                 // Behaviour 3 is current user thus not related to current item
                 return;
                 // current view is not item view ... , nothing to display
             }
             if ($behaviour_auth == 1) {
                 $where .= ' AND i.created_by = ' . (int) $curitem->created_by;
             } else {
                 if ($behaviour_auth == 2) {
                     $where .= ' AND i.created_by <> ' . (int) $curitem->created_by;
                 } else {
                     // $behaviour_auth == 3
                     $where .= ' AND i.created_by = ' . (int) $user->id;
                 }
             }
         }
     }
     // ***********
     // items scope
     // ***********
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_items && $method_items == 1) {
     } else {
         if (!$behaviour_items) {
             // Check for empty statically selected records, and abort with error message
             if (empty($items)) {
                 echo "<b>WARNING:</b> Misconfigured items scope, select at least one item or set items scope to ALL<br/>";
                 return;
             }
             if ($method_items == 2) {
                 // exclude method
                 $where .= ' AND i.id NOT IN (' . $items . ')';
             } else {
                 if ($method_items == 3) {
                     // include method
                     $where .= ' AND i.id IN (' . $items . ')';
                 }
             }
         } else {
             if ($behaviour_items == 2 || $behaviour_items == 3) {
                 if (!$isflexi_itemview) {
                     return;
                     // current view is not item view ... , nothing to display
                 }
                 unset($related);
                 // make sure this is no set ...
                 if (count($relitems_fields)) {
                     $where2 = count($relitems_fields) > 1 ? ' AND field_id IN (' . implode(',', $relitems_fields) . ')' : ' AND field_id = ' . $relitems_fields[0];
                     // select the item ids related to current item via the relation fields
                     $query2 = 'SELECT DISTINCT ' . ($behaviour_items == 2 ? 'value' : 'item_id') . ' FROM #__flexicontent_fields_item_relations' . ' WHERE ' . ($behaviour_items == 2 ? 'item_id' : 'value') . ' = ' . (int) $id . $where2;
                     $db->setQuery($query2);
                     $related = $db->loadColumn();
                     $related = is_array($related) ? array_map('intval', $related) : $related;
                 }
                 if (isset($related) && count($related)) {
                     $where .= count($related) > 1 ? ' AND i.id IN (' . implode(',', $related) . ')' : ' AND i.id = ' . $related[0];
                 } else {
                     // No related items were found
                     return;
                 }
             } else {
                 if ($behaviour_items == 1) {
                     if (!$isflexi_itemview) {
                         return;
                         // current view is not item view ... , nothing to display
                     }
                     // select the tags associated to the item
                     $query2 = 'SELECT tid' . ' FROM #__flexicontent_tags_item_relations' . ' WHERE itemid = ' . (int) $id;
                     $db->setQuery($query2);
                     $tags = $db->loadColumn();
                     $tags = array_diff($tags, $excluded_tags);
                     unset($related);
                     if ($tags) {
                         $where2 = count($tags) > 1 ? ' AND tid IN (' . implode(',', $tags) . ')' : ' AND tid = ' . $tags[0];
                         // select the item ids related to current item via common tags
                         $query2 = 'SELECT DISTINCT itemid' . ' FROM #__flexicontent_tags_item_relations' . ' WHERE itemid <> ' . (int) $id . $where2;
                         $db->setQuery($query2);
                         $related = $db->loadColumn();
                     }
                     if (isset($related) && count($related)) {
                         $where .= count($related) > 1 ? ' AND i.id IN (' . implode(',', $related) . ')' : ' AND i.id = ' . $related[0];
                     } else {
                         // No related items were found
                         return;
                     }
                 }
             }
         }
     }
     // **********
     // tags scope
     // **********
     if ($method_tags > 1) {
         // Check for empty statically selected records, and abort with error message
         if (empty($tag_ids)) {
             echo "<b>WARNING:</b> Misconfigured tags scope, select at least one tag or set tags scope to ALL<br/>";
             return;
         }
         // Make sure tag_ids is an array
         $tag_ids = !is_array($tag_ids) ? array($tag_ids) : $tag_ids;
         // Create query to match item ids using the selected tags
         $query2 = 'SELECT ' . ($tag_combine ? 'itemid' : 'DISTINCT itemid') . ' FROM #__flexicontent_tags_item_relations' . ' WHERE tid IN (' . implode(',', $tag_ids) . ')' . ($tag_combine ? ' GROUP by itemid HAVING COUNT(*) >= ' . count($tag_ids) : '');
         if ($method_tags == 2) {
             // exclude method
             $where .= ' AND i.id NOT IN (' . $query2 . ')';
         } else {
             if ($method_tags == 3) {
                 // include method
                 $where .= ' AND i.id IN (' . $query2 . ')';
             }
         }
     }
     // **********
     // date scope
     // **********
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     // NOTE: currently we only have ALL, INCLUDE methods
     if (!$behaviour_dates && $method_dates == 1) {
     } else {
         if (!$behaviour_dates) {
             $negate_op = $method_dates == 2 ? 'NOT' : '';
             if (!$raw_edate && $edate && !FLEXIUtilities::isSqlValidDate($edate)) {
                 echo "<b>WARNING:</b> Misconfigured date scope, you have entered invalid -END- date:<br>(a) Enter a valid date via callendar OR <br>(b) leave blank OR <br>(c) choose (non-static behavior 'custom offset') and enter custom offset e.g. five days ago (be careful with space character): -5 d<br/>";
                 return;
             } else {
                 if ($edate) {
                     $where .= ' AND ( ' . $negate_op . ' ( ' . $comp . ' <= ' . (!$raw_edate ? $db->Quote($edate) : $edate) . ' )' . ($nulldates ? ' OR ' . $comp . ' IS NULL OR ' . $comp . '="" ' : '') . ' )';
                 }
             }
             if (!$raw_bdate && $bdate && !FLEXIUtilities::isSqlValidDate($bdate)) {
                 echo "<b>WARNING:</b> Misconfigured date scope, you have entered invalid -BEGIN- date:<br>(a) Enter a valid date via callendar OR <br>(b) leave blank OR <br>(c) choose (non-static behavior 'custom offset') and enter custom offset e.g. five days ago (be careful with space character): -5 d<br/>";
                 return;
             } else {
                 if ($bdate) {
                     $where .= ' AND ( ' . $negate_op . ' ( ' . $comp . ' >= ' . (!$raw_bdate ? $db->Quote($bdate) : $bdate) . ' )' . ($nulldates ? ' OR ' . $comp . ' IS NULL OR ' . $comp . '="" ' : '') . ' )';
                 }
             }
         } else {
             if (!$isflexi_itemview && $date_compare == 1) {
                 return;
                 // date_compare == 1 means compare to current item, but current view is not an item view so we terminate
             }
             // FOR date_compare==0, $cdate is SERVER DATE
             // FOR date_compare==1, $cdate is CURRENT ITEM DATE of type created or modified or publish_up or CUSTOM date field
             switch ($behaviour_dates) {
                 case '1':
                     // custom offset
                     if ($edate) {
                         $edate = array(0 => preg_replace("/[^-+0-9\\s]/", "", $edate), 1 => preg_replace("/[0-9-+\\s]/", "", $edate));
                         if (empty($edate[1])) {
                             echo "<b>WARNING:</b> Misconfigured date scope, you have entered invalid -END- date:Custom offset is invalid e.g. in order to enter five days ago (be careful with space character) use: -5 d (DO NOT FORGET the space between e.g. '-5 d')<br/>";
                             return;
                         } else {
                             $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, $edate[0], $edate[1])) . ($nulldates ? ' OR ' . $comp . ' IS NULL OR ' . $comp . '="" ' : '') . ' )';
                         }
                     }
                     if ($bdate) {
                         $bdate = array(0 => preg_replace("/[^-+0-9]/", "", $bdate), 1 => preg_replace("/[0-9-+]/", "", $bdate));
                         if (empty($bdate[1])) {
                             echo "<b>WARNING:</b> Misconfigured date scope, you have entered invalid -BEGIN- date: Custom offset is invalid e.g. in order to enter five days ago (be careful with space character) use: -5 d (DO NOT FORGET the space between e.g. '-5 d')<br/>";
                             return;
                         } else {
                             $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, $bdate[0], $bdate[1])) . ($nulldates ? ' OR ' . $comp . ' IS NULL OR ' . $comp . '="" ' : '') . ' )';
                         }
                     }
                     break;
                 case '8':
                     // same day
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-' . $cdate[2] . ' 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 1, 'd')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote($cdate) . ' )';
                     break;
                 case '2':
                     // same month
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 1, 'm')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote($cdate) . ' )';
                     break;
                 case '3':
                     // same year
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-01-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 1, 'Y')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote($cdate) . ' )';
                     break;
                 case '9':
                     // previous day
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-' . $cdate[2] . ' 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote($cdate) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, -1, 'd')) . ' )';
                     break;
                 case '4':
                     // previous month
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote($cdate) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, -1, 'm')) . ' )';
                     break;
                 case '5':
                     // previous year
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-01-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote($cdate) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, -1, 'Y')) . ' )';
                     break;
                 case '10':
                     // next day
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-' . $cdate[2] . ' 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 2, 'd')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, 1, 'd')) . ' )';
                     break;
                 case '6':
                     // next month
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-' . $cdate[1] . '-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 2, 'm')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, 1, 'm')) . ' )';
                     break;
                 case '7':
                     // next year
                     $cdate = explode(' ', $cdate);
                     $cdate = explode('-', $cdate[0]);
                     $cdate = $cdate[0] . '-01-01 00:00:00';
                     $where .= ' AND ( ' . $comp . ' < ' . $db->Quote(date_time::shift_dates($cdate, 2, 'Y')) . ' )';
                     $where .= ' AND ( ' . $comp . ' >= ' . $db->Quote(date_time::shift_dates($cdate, 1, 'Y')) . ' )';
                     break;
                 case '11':
                     // same day of month, ignore year
                     $where .= ' AND ( DAYOFMONTH(' . $comp . ') = ' . 'DAYOFMONTH(' . $db->Quote($cdate) . ') AND MONTH(' . $comp . ') = ' . 'MONTH(' . $db->Quote($cdate) . ') )';
                     break;
                 case '12':
                     // [-3d,+3d] days of month, IGNORE YEAR
                     $where .= ' AND ((DAYOFMONTH(' . $db->Quote($cdate) . ')-3) <= DAYOFMONTH(' . $comp . ') AND DAYOFMONTH(' . $comp . ') <= (DAYOFMONTH(' . $db->Quote($cdate) . ')+4) AND MONTH(' . $comp . ') = ' . 'MONTH(' . $db->Quote($cdate) . ') )';
                     break;
                 case '13':
                     // same week of month, IGNORE YEAR
                     $week_start = (int) $params->get('week_start', 0);
                     // 0 is sunday, 5 is monday
                     $week_of_month = '(WEEK(%s,5) - WEEK(DATE_SUB(%s, INTERVAL DAYOFMONTH(%s)-1 DAY),5)+1)';
                     $where .= ' AND (' . str_replace('%s', $comp, $week_of_month) . ' = ' . str_replace('%s', $db->Quote($cdate), $week_of_month) . ' AND ( MONTH(' . $comp . ') = ' . 'MONTH(' . $db->Quote($cdate) . ') ) )';
                     break;
                 case '14':
                     // same week of year, IGNORE YEAR
                     $week_start = (int) $params->get('week_start', 0);
                     // 0 is sunday, 5 is monday
                     $where .= ' AND ( WEEK(' . $comp . ') = ' . 'WEEK(' . $db->Quote($cdate) . ',' . $week_start . ') )';
                     break;
                 case '15':
                     // same month of year, IGNORE YEAR
                     $where .= ' AND ( MONTH(' . $comp . ') = ' . 'MONTH(' . $db->Quote($cdate) . ') )';
                     break;
                 case '16':
                     // same day of month, IGNORE MONTH, YEAR
                     $where .= ' AND ( DAYOFMONTH(' . $comp . ') = ' . 'DAYOFMONTH(' . $db->Quote($cdate) . ') )';
                     break;
                 case '17':
                     // [-3d,+3d] days of month, IGNORE  MONTH, YEAR
                     $where .= ' AND ((DAYOFMONTH(' . $db->Quote($cdate) . ')-3) <= DAYOFMONTH(' . $comp . ') AND DAYOFMONTH(' . $comp . ') <= (DAYOFMONTH(' . $db->Quote($cdate) . ')+4) )';
                     break;
                 case '18':
                     // same week of month, IGNORE MONTH, YEAR
                     $week_start = (int) $params->get('week_start', 0);
                     // 0 is sunday, 5 is monday
                     $week_of_month = '(WEEK(%s,5) - WEEK(DATE_SUB(%s, INTERVAL DAYOFMONTH(%s)-1 DAY),5)+1)';
                     $where .= ' AND (' . str_replace('%s', $comp, $week_of_month) . ' = ' . str_replace('%s', $db->Quote($cdate), $week_of_month) . ' )';
                     break;
             }
         }
     }
     // *****************************
     // EXTRA joins for special cases
     // *****************************
     // EXTRA joins when comparing to custom date field
     $join_date = '';
     if ($behaviour_dates || $method_dates != 1) {
         // using date SCOPE: dynamic behaviour, or static behavior with (static) method != ALL(=1)
         if (($bdate || $edate || $behaviour_dates) && $date_type == 3) {
             if ($datecomp_field) {
                 $join_date = '	LEFT JOIN #__flexicontent_fields_item_relations AS dfrel' . '   ON ( i.id = dfrel.item_id AND dfrel.field_id = ' . $datecomp_field . ' )';
             } else {
                 echo "<b>WARNING:</b> Misconfigured date scope, you have set DATE TYPE as CUSTOM DATE Field, but have not select any specific DATE Field to be used<br/>";
                 //$join_date = '';
                 return;
             }
         }
     }
     // *****************************************************************************************************************************
     // Get orderby SQL CLAUSE ('ordering' is passed by reference but no frontend user override is used (we give empty 'request_var')
     // *****************************************************************************************************************************
     $orderby = flexicontent_db::buildItemOrderBy($params, $ordering, $request_var = '', $config_param = 'ordering', $item_tbl_alias = 'i', $relcat_tbl_alias = 'rel', $default_order = '', $default_order_dir = '', $sfx = '', $support_2nd_lvl = true);
     //echo "<br/>" . print_r($ordering, true) ."<br/>";
     // EXTRA join of field used in custom ordering
     // NOTE: if (1st/2nd level) custom field id is not set, THEN 'field' ordering was changed to level's default, by the ORDER CLAUSE creating function
     $orderby_join = '';
     // Create JOIN for ordering items by a custom field (Level 1)
     if ('field' == $ordering[1]) {
         $orderbycustomfieldid = (int) $params->get('orderbycustomfieldid', 0);
         $orderby_join .= ' LEFT JOIN #__flexicontent_fields_item_relations AS f ON f.item_id = i.id AND f.field_id=' . $orderbycustomfieldid;
     }
     // Create JOIN for ordering items by a custom field (Level 2)
     if ('field' == $ordering[2]) {
         $orderbycustomfieldid_2nd = (int) $params->get('orderbycustomfieldid' . '_2nd', 0);
         $orderby_join .= ' LEFT JOIN #__flexicontent_fields_item_relations AS f2 ON f2.item_id = i.id AND f2.field_id=' . $orderbycustomfieldid_2nd;
     }
     // Create JOIN for ordering items by author's name
     if (in_array('author', $ordering) || in_array('rauthor', $ordering)) {
         $orderby_join .= ' LEFT JOIN #__users AS u ON u.id = i.created_by';
     }
     // *****************************************************
     // Decide Select Sub-Clause and Join-Clause for comments
     // *****************************************************
     $display_comments = $params->get('display_comments');
     $display_comments_feat = $params->get('display_comments_feat');
     // Check (when needed) if jcomments are installed, and also clear 'commented' ordering if they jcomments is missing
     if ($display_comments_feat || $display_comments || in_array('commented', $ordering)) {
         // Handle jcomments integratio. No need to reset 'commented' ordering if jcomments not installed,
         // and neither print message, the ORDER CLAUSE creating function should have done this already
         if (!file_exists(JPATH_SITE . DS . 'components' . DS . 'com_jcomments' . DS . 'jcomments.php')) {
             //echo "jcomments not installed, you need jcomments to use 'Most commented' ordering OR display comments information.<br>\n";
             $jcomments_exist = false;
         } else {
             $jcomments_exist = true;
         }
     }
     // Decide to JOIN (or not) with comments TABLE, needed when displaying comments and/or when ordering by comments
     $add_comments = ($display_comments_feat || $display_comments || in_array('commented', $ordering)) && $jcomments_exist;
     // Additional select and joins for comments
     $select_comments = $add_comments ? ', COUNT(DISTINCT com.id) AS comments_total' : '';
     $join_comments_type = $ordering[1] == 'commented' ? ' INNER JOIN' : ' LEFT JOIN';
     // Do not require most commented for 2nd level ordering
     $join_comments = $add_comments ? $join_comments_type . ' #__jcomments AS com ON com.object_id = i.id AND com.object_group="com_flexicontent" AND com.published="1"' : '';
     // **********************************************************
     // Decide Select Sub-Clause and Join-Clause for voting/rating
     // **********************************************************
     $display_voting = $params->get('display_voting');
     $display_voting_feat = $params->get('display_voting_feat');
     // Decide to JOIN (or not) with rating TABLE, needed when displaying ratings and/or when ordering by ratings
     $add_rated = $display_voting_feat || $display_voting || in_array('rated', $ordering);
     // Additional select and joins for ratings
     $select_rated = in_array('rated', $ordering) ? ', (cr.rating_sum / cr.rating_count) * 20 AS votes' : '';
     $select_rated .= $add_rated ? ', cr.rating_sum as rating_sum, cr.rating_count as rating_count' : '';
     $join_rated_type = in_array('rated', $ordering) ? ' INNER JOIN' : ' LEFT JOIN';
     $join_rated = $add_rated ? $join_rated_type . ' #__content_rating AS cr ON cr.content_id = i.id' : '';
     // ***********************************************************
     // Finally put together the query to retrieve the listed items
     // ***********************************************************
     // ******************
     // Custom FIELD scope
     // ******************
     $where_field_filters = '';
     $join_field_filters = '';
     // ZERO 'behaviour' means statically selected records, but METHOD 1 is ALL records ... so NOTHING to do
     if (!$behaviour_filt && $method_filt == 1) {
     } else {
         if ($behaviour_filt == 0 || $behaviour_filt == 2) {
             $negate_op = $method_filt == 2 ? 'NOT' : '';
             // These field filters apply a STATIC filtering, regardless of current item being displayed.
             // Static Field Filters (These are a string that MAPs filter ID TO filter VALUES)
             $static_filters_data = FlexicontentFields::setFilterValues($params, 'static_filters', $is_persistent = 1, $set_method = "array");
             // Dynamic Field Filters (THIS is filter IDs list)
             // These field filters apply a DYNAMIC filtering, that depend on current item being displayed. The items that have same value as currently displayed item will be included in the list.
             //$dynamic_filters = FlexicontentFields::setFilterValues( $params, 'dynamic_filters', $is_persistent=0);
             foreach ($static_filters_data as $filter_id => $filter_values) {
                 // Handle single-valued filter as multi-valued
                 if (!is_array($filter_values)) {
                     $filter_values = array(0 => $filter_values);
                 }
                 // Single or Multi valued filter
                 if (isset($filter_values[0])) {
                     $in_values = array();
                     foreach ($filter_values as $val) {
                         $in_values[] = $db->Quote($val);
                     }
                     // Quote in case they are strings !!
                     $where_field_filters .= ' AND ' . $negate_op . ' (rel' . $filter_id . '.value IN (' . implode(',', $in_values) . ') ) ';
                 } else {
                     // Special case only one part of range provided ... must MATCH/INCLUDE empty values or NULL values ...
                     $value_empty = !strlen(@$filter_values[1]) && strlen(@$filter_values[2]) ? ' OR rel' . $filter_id . '.value="" OR rel' . $filter_id . '.value IS NULL ' : '';
                     if (strlen(@$filter_values[1]) || strlen(@$filter_values[2])) {
                         $where_field_filters .= ' AND ' . $negate_op . ' ( 1 ';
                         if (strlen(@$filter_values[1])) {
                             $where_field_filters .= ' AND (rel' . $filter_id . '.value >=' . $filter_values[1] . ') ';
                         }
                         if (strlen(@$filter_values[2])) {
                             $where_field_filters .= ' AND (rel' . $filter_id . '.value <=' . $filter_values[2] . $value_empty . ') ';
                         }
                         $where_field_filters .= ' )';
                     }
                 }
                 $join_field_filters .= ' JOIN #__flexicontent_fields_item_relations AS rel' . $filter_id . ' ON rel' . $filter_id . '.item_id=i.id AND rel' . $filter_id . '.field_id = ' . $filter_id;
             }
         }
     }
     if ($behaviour_filt == 1 || $behaviour_filt == 2) {
         if (!$isflexi_itemview) {
             return;
             // current view is not item view ... , nothing to display
         }
         // 1. Get ids of dynamic filters
         //$dynamic_filter_ids = preg_split("/[\s]*,[\s]*/", $dynamic_filters);
         $dynamic_filter_ids = FLEXIUtilities::paramToArray($dynamic_filters, "/[\\s]*,[\\s]*/", "intval");
         if (empty($dynamic_filter_ids)) {
             echo "Please enter at least 1 field in Custom field filtering SCOPE, or set behaviour to static";
         } else {
             // 2. Get values of dynamic filters
             $where2 = count($dynamic_filter_ids) > 1 ? ' AND field_id IN (' . implode(',', $dynamic_filter_ids) . ')' : ' AND field_id = ' . $dynamic_filter_ids[0];
             // select the item ids related to current item via the relation fields
             $query2 = 'SELECT DISTINCT value, field_id' . ' FROM #__flexicontent_fields_item_relations' . ' WHERE item_id = ' . (int) $id . $where2;
             $db->setQuery($query2);
             $curritem_vals = $db->loadObjectList();
             //echo "<pre>"; print_r($curritem_vals); echo "</pre>";
             // 3. Group values by field
             $_vals = array();
             foreach ($curritem_vals as $v) {
                 $_vals[$v->field_id][] = $v->value;
             }
             foreach ($dynamic_filter_ids as $filter_id) {
                 // Handle non-existent value by requiring that matching item do not have a value for this field either
                 if (!isset($_vals[$filter_id])) {
                     $where_field_filters .= ' AND reldyn' . $filter_id . '.value IS NULL';
                 } else {
                     $in_values = array();
                     foreach ($_vals[$filter_id] as $v) {
                         $in_values[] = $db->Quote($v);
                     }
                     $where_field_filters .= ' AND reldyn' . $filter_id . '.value IN (' . implode(',', $in_values) . ') ' . "\n";
                 }
                 $join_field_filters .= ' JOIN #__flexicontent_fields_item_relations AS reldyn' . $filter_id . ' ON reldyn' . $filter_id . '.item_id=i.id AND reldyn' . $filter_id . '.field_id = ' . $filter_id . "\n";
             }
             //echo "<pre>"."\n\n".$join_field_filters ."\n\n".$where_field_filters."</pre>";
         }
     }
     if (empty($items_query)) {
         // If a custom query has not been set above then use the default one ...
         $items_query = 'SELECT ' . ' i.id ' . (in_array('commented', $ordering) ? $select_comments : '') . (in_array('rated', $ordering) ? $select_rated : '') . ' FROM #__flexicontent_items_tmp AS i' . ' JOIN #__flexicontent_items_ext AS ie on ie.item_id = i.id' . ' JOIN #__flexicontent_types AS ty on ie.type_id = ty.id' . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id' . ' JOIN #__categories AS  c ON  c.id = rel.catid' . ' JOIN #__categories AS mc ON mc.id = i.catid' . $joinaccess . $join_favs . $join_date . (in_array('commented', $ordering) ? $join_comments : '') . (in_array('rated', $ordering) ? $join_rated : '') . $orderby_join . $join_field_filters . $where . ' ' . ($apply_config_per_category ? '__CID_WHERE__' : '') . $where_field_filters . ' GROUP BY i.id' . $orderby;
         // if using CATEGORY SCOPE INCLUDE ... then link though them ... otherwise via main category
         $_cl = !$behaviour_cat && $method_cat == 3 ? 'c' : 'mc';
         $items_query_data = 'SELECT ' . ' i.*, ie.*, ty.name AS typename' . $select_comments . $select_rated . ', mc.title AS maincat_title, mc.alias AS maincat_alias' . ', CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as slug' . ', CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', ' . $_cl . '.id, ' . $_cl . '.alias) ELSE ' . $_cl . '.id END as categoryslug' . ', GROUP_CONCAT(rel.catid SEPARATOR ",") as itemcats' . ' FROM #__content AS i' . ' JOIN #__flexicontent_items_ext AS ie on ie.item_id = i.id' . ' JOIN #__flexicontent_types AS ty on ie.type_id = ty.id' . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id' . ' JOIN #__categories AS  c ON  c.id = rel.catid' . ' JOIN #__categories AS mc ON mc.id = i.catid' . $joinaccess . $join_favs . $join_date . $join_comments . $join_rated . $orderby_join . ' WHERE i.id IN (__content__)' . ' GROUP BY i.id';
     }
     // **********************************
     // Execute query once OR per category
     // **********************************
     if (!isset($multiquery_cats)) {
         $multiquery_cats = array(0 => "");
     }
     foreach ($multiquery_cats as $catid => $cat_where) {
         $_microtime = $modfc_jprof->getmicrotime();
         // Get content list per given category
         $per_cat_query = str_replace('__CID_WHERE__', $cat_where, $items_query);
         $db->setQuery($per_cat_query, 0, $count);
         $content = $db->loadColumn(0);
         if ($db->getErrorNum()) {
             JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
         }
         @($mod_fc_run_times['query_items'] += $modfc_jprof->getmicrotime() - $_microtime);
         // Check for no content found for given category
         if (empty($content)) {
             $cat_items_arr[$catid] = array();
             continue;
         }
         $_microtime = $modfc_jprof->getmicrotime();
         // Get content list data per given category
         $per_cat_query = str_replace('__content__', implode(',', $content), $items_query_data);
         $db->setQuery($per_cat_query, 0, $count);
         $_rows = $db->loadObjectList('item_id');
         if ($db->getErrorNum()) {
             JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
         }
         @($mod_fc_run_times['query_items_sec'] += $modfc_jprof->getmicrotime() - $_microtime);
         // Secondary content list ordering and assign content list per category
         $rows = array();
         foreach ($content as $_id) {
             $rows[] = $_rows[$_id];
         }
         $cat_items_arr[$catid] = $rows;
         // Get Original content ids for creating some untranslatable fields that have share data (like shared folders)
         flexicontent_db::getOriginalContentItemids($cat_items_arr[$catid]);
     }
     // ************************************************************************************************
     // Return items indexed per category id OR via empty string if not apply configuration per category
     // ************************************************************************************************
     return $cat_items_arr;
 }
コード例 #8
0
 /**
  * Method to get categories data
  *
  * @access public
  * @return array
  * @since	1.0
  */
 function getData()
 {
     $app = JFactory::getApplication();
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $option = JRequest::getVar('option');
     $view = JRequest::getVar('view');
     global $globalcats;
     $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_cats = $app->getUserStateFromRequest($option . '.' . $view . '.filter_cats', 'filter_cats', '', 'int');
     $filter_state = $app->getUserStateFromRequest($option . '.' . $view . '.filter_state', 'filter_state', '', 'string');
     $filter_access = $app->getUserStateFromRequest($option . '.' . $view . '.filter_access', 'filter_access', '', 'string');
     $filter_level = $app->getUserStateFromRequest($option . '.' . $view . '.filter_level', 'filter_level', '', 'string');
     if (FLEXI_J16GE) {
         $filter_language = $app->getUserStateFromRequest($option . '.' . $view . '.filter_language', 'filter_language', '', 'string');
     }
     $search = $app->getUserStateFromRequest($option . '.' . $view . '.search', 'search', '', 'string');
     $search = trim(JString::strtolower($search));
     $limit = $app->getUserStateFromRequest($option . '.' . $view . '.limit', 'limit', $app->getCfg('list_limit'), 'int');
     $limitstart = $app->getUserStateFromRequest($option . '.' . $view . '.limitstart', 'limitstart', 0, 'int');
     $orderby = ' ORDER BY ' . $filter_order . ' ' . $filter_order_Dir . ', ' . $order_property;
     $where = array();
     // Filter by publication state, ... breaks tree construction, commented out and done below
     /*if ( $filter_state ) {
     			if ( $filter_state == 'P' ) {
     				$where[] = 'c.published = 1';
     			} else if ($filter_state == 'U' ) {
     				$where[] = 'c.published = 0';
     			}
     		}*/
     // Filter by access level, ... breaks tree construction, commented out and done below
     /*if ( $filter_access ) {
     			$where[] = 'c.access = '.(int) $filter_access;
     		}*/
     if ($filter_cats && isset($globalcats[$filter_cats])) {
         // Limit category list to those contain in the subtree of the choosen category
         $where[] = 'c.id IN (' . $globalcats[$filter_cats]->descendants . ')';
     }
     // Filter on the level.
     if ($filter_level) {
         $cats = array();
         $filter_level = (int) $filter_level;
         foreach ($globalcats as $cat) {
             if (@$cat->level <= $filter_level) {
                 $cats[] = $cat->id;
             }
         }
         if (!empty($cats)) {
             $where[] = 'c.id IN (' . implode(",", $cats) . ')';
         }
     }
     $where = count($where) ? ' AND ' . implode(' AND ', $where) : '';
     // Note, since this is a tree we have to do the WORD SEARCH separately.
     if ($search) {
         $query = 'SELECT c.id' . ' FROM #__categories AS c' . ' WHERE LOWER(c.title) LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false) . ' AND c.section = ' . FLEXI_SECTION . $where;
         $db->setQuery($query);
         $search_rows = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray();
     }
     $query = 'SELECT c.*' . ', u.name AS editor, c.params as config' . (FLEXI_J16GE ? ', level.title AS access_level' : ', g.name AS groupname') . ', (SELECT COUNT(*) FROM #__flexicontent_cats_item_relations AS rel WHERE rel.catid = c.id) AS nrassigned ' . ' FROM #__categories AS c' . (FLEXI_J16GE ? ' LEFT JOIN #__viewlevels AS level ON level.id=c.access' : ' LEFT JOIN #__groups AS g ON g.id = c.access') . ' LEFT JOIN #__users AS u ON u.id = c.checked_out' . (FLEXI_J16GE ? '' : ' LEFT JOIN #__sections AS sec ON sec.id = c.section') . (FLEXI_J16GE ? ' WHERE c.extension = ' . $db->Quote(FLEXI_CAT_EXTENSION) . ' AND c.lft >= ' . $db->Quote(FLEXI_LFT_CATEGORY) . ' AND c.rgt<=' . $db->Quote(FLEXI_RGT_CATEGORY) : ' WHERE c.section = ' . FLEXI_SECTION) . (FLEXI_J16GE ? '' : ' AND sec.scope = ' . $db->Quote('content')) . $where . ' GROUP BY c.id' . $orderby;
     $db->setQuery($query);
     $rows = $db->loadObjectList();
     //establish the hierarchy of the categories
     $children = array();
     // Set depth limit
     $levellimit = 30;
     foreach ($rows as $child) {
         $parent = $child->parent_id;
         $list = @$children[$parent] ? $children[$parent] : array();
         array_push($list, $child);
         $children[$parent] = $list;
     }
     // Put found items into a tree, in the case of displaying the subree of top level category use the parent id of the category
     $ROOT_CATEGORY_ID = FLEXI_J16GE ? 1 : 0;
     $root_cat = !$filter_cats ? $ROOT_CATEGORY_ID : $globalcats[$filter_cats]->parent_id;
     $list = flexicontent_cats::treerecurse($root_cat, '', array(), $children, false, max(0, $levellimit - 1));
     // Eventually only pick out the searched items.
     if ($search) {
         $srows = array();
         foreach ($search_rows as $sid) {
             $srows[$sid] = 1;
         }
         $list_search = array();
         foreach ($list as $item) {
             if (@$srows[$item->id]) {
                 $list_search[] = $item;
             }
         }
         $list = $list_search;
     }
     // Filter by access level
     if ($filter_access) {
         $_access = (int) $filter_access;
         $list_search = array();
         foreach ($list as $item) {
             if ($item->access == $_access) {
                 $list_search[] = $item;
             }
         }
         $list = $list_search;
     }
     // Filter by publication state
     if ($filter_state == 'P' || $filter_state == 'U') {
         $_state = $filter_state == 'P' ? 1 : 0;
         $list_search = array();
         foreach ($list as $item) {
             if ($item->published == $_state) {
                 $list_search[] = $item;
             }
         }
         $list = $list_search;
     }
     // Create pagination object
     $total = count($list);
     jimport('joomla.html.pagination');
     $this->_pagination = new JPagination($total, $limitstart, $limit);
     // Slice out elements based on limits
     $list = array_slice($list, $this->_pagination->limitstart, $this->_pagination->limit);
     return $list;
 }
コード例 #9
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);
 }
コード例 #10
0
	/**
	 * Logic to save an item
	 *
	 * @access public
	 * @return void
	 * @since 1.0
	 */
	function save()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		
		// Initialize variables
		$app     = JFactory::getApplication();
		$db      = JFactory::getDBO();
		$user    = JFactory::getUser();
		$menu    = $app->getMenu()->getActive();
		$config  = JFactory::getConfig();
		$session = JFactory::getSession();
		$task	   = JRequest::getVar('task');
		$model   = $this->getModel(FLEXI_ITEMVIEW);
		$isnew   = !$model->getId();
		$ctrl_task = FLEXI_J16GE ? 'task=items.' : 'controller=items&task=';
		
		$fc_params  = JComponentHelper::getParams( 'com_flexicontent' );
		$dolog      = $fc_params->get('print_logging_info');
		
		// Get the COMPONENT only parameters
		$comp_params = JComponentHelper::getComponent('com_flexicontent')->params;
		$params = FLEXI_J16GE ? clone ($comp_params) : new JParameter( $comp_params ); // clone( JComponentHelper::getParams('com_flexicontent') );
		
		// Merge the type parameters
		$tparams = $model->getTypeparams();
		$tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
		$params->merge($tparams);
		
		// Merge the menu parameters
		if ($menu) {
			$menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);
			$params->merge($menu_params);
		}
		
		// Get needed parameters
		$submit_redirect_url_fe = $params->get('submit_redirect_url_fe', '');
		$allowunauthorize       = $params->get('allowunauthorize', 0);
		
		
		
		// *********************
		// Get data from request
		// *********************
		
		if (FLEXI_J16GE) {
			// Retrieve form data these are subject to basic filtering
			$data   = JRequest::getVar('jform', array(), 'post', 'array');   // Core Fields and and item Parameters
			$custom = JRequest::getVar('custom', array(), 'post', 'array');  // Custom Fields
			$jfdata = JRequest::getVar('jfdata', array(), 'post', 'array');  // Joomfish Data
			if ( ! @ $data['rules'] ) $data['rules'] = array();
		}
		
		else {
			// Retrieve form data these are subject to basic filtering
			$data = JRequest::get( 'post' );  // Core & Custom Fields and item Parameters
		}
		
		// Set data id into model in case not already set ?
		$model->setId((int) $data['id']);
		
		
		
		// *************************************
		// ENFORCE can change category ACL perms
		// *************************************
		
		$perms = FlexicontentHelperPerm::getPerm();
		// Per content type change category permissions
		if (FLEXI_J16GE) {
			$current_type_id  = ($isnew || !$model->get('type_id')) ? $data['type_id'] : $model->get('type_id');  // GET current (existing/old) item TYPE ID
			$CanChangeFeatCat = $user->authorise('flexicontent.change.cat.feat', 'com_flexicontent.type.' . $current_type_id);
			$CanChangeSecCat  = $user->authorise('flexicontent.change.cat.sec', 'com_flexicontent.type.' . $current_type_id);
			$CanChangeCat     = $user->authorise('flexicontent.change.cat', 'com_flexicontent.type.' . $current_type_id);
		} else {
			$CanChangeFeatCat = 1;
			$CanChangeSecCat  = 1;
			$CanChangeCat     = 1;
		}
		
		$featured_cats_parent = $params->get('featured_cats_parent', 0);
		$featured_cats = array();
		
		$enable_featured_cid_selector = $perms->MultiCat && $CanChangeFeatCat;
		$enable_cid_selector   = $perms->MultiCat && $CanChangeSecCat;
		$enable_catid_selector = ($isnew && !$tparams->get('catid_default')) || (!$isnew && !$model->get('catid')) || $CanChangeCat;
		
		// Enforce maintaining featured categories
		$featured_cats_parent = $params->get('featured_cats_parent', 0);
		$featured_cats = array();
		if ( $featured_cats_parent && !$enable_featured_cid_selector )
		{
			$featured_tree = flexicontent_cats::getCategoriesTree($published_only=1, $parent_id=$featured_cats_parent, $depth_limit=0);
			$featured_cid = array();
			if (!$isnew) {
				foreach($model->get('categories') as $item_cat) if (isset($featured_tree[$item_cat])) $featured_cid[] = $item_cat;
			}
			$data['featured_cid'] = $featured_cid;
		}
		
		// Enforce maintaining secondary categories
		if (!$enable_cid_selector) {
			if ($isnew) {
				$data['cid'] = $tparams->get('cid_default');
			} else if ( isset($featured_cid) ) {
				$featured_cid_arr = array_flip($featured_cid);
				$sec_cid = array();
				foreach($model->get('cats') as $item_cat) if (!isset($featured_cid_arr[$item_cat])) $sec_cid[] = $item_cat;
				$data['cid'] = $sec_cid;
			} else {
				$data['cid'] = $model->get('cats');
			}
		}
		
		if (!$enable_catid_selector) {
			if ($isnew && $tparams->get('catid_default'))
				$data['catid'] = $tparams->get('catid_default');
			else if ($model->get('catid'))
				$data['catid'] = $model->get('catid');
		}
		
		
		
		// **************************
		// Basic Form data validation
		// **************************
		
		if (FLEXI_J16GE)
		{
			// *** MANUALLY CHECK CAPTCHA ***
			$use_captcha    = $params->get('use_captcha', 1);     // 1 for guests, 2 for any user
			$captcha_formop = $params->get('captcha_formop', 0);  // 0 for submit, 1 for submit/edit (aka always)
			$is_submitop = ((int) $data['id']) == 0;
			$display_captcha = $use_captcha >= 2 || ( $use_captcha == 1 &&  $user->guest );
			$display_captcha = $display_captcha && ( $is_submitop || $captcha_formop);  // for submit operation we do not need to check 'captcha_formop' ...
			if ($display_captcha)
			{
				// Try to force the use of recaptcha plugin
				JFactory::getConfig()->set('captcha', 'recaptcha');
				
				if ( $app->getCfg('captcha') == 'recaptcha' && JPluginHelper::isEnabled('captcha', 'recaptcha') ) {
					JPluginHelper::importPlugin('captcha');
					$dispatcher = JDispatcher::getInstance();
					$result = $dispatcher->trigger('onCheckAnswer', JRequest::getString('recaptcha_response_field'));
					if (!$result[0]) {
						$errmsg  = JText::_('FLEXI_CAPTCHA_FAILED');
						$errmsg .= ' '.JText::_('FLEXI_MUST_REFILL_SOME_FIELDS');
						echo "<script>alert('".$errmsg."');";
						echo "window.history.back();";
						echo "</script>";
						jexit();
					}
				}
			}
			
			// Validate Form data for core fields and for parameters
			$form = $model->getForm();          // Do not pass any data we only want the form object in order to validate the data and not create a filled-in form
			$post = $model->validate($form, $data);
			
			// Check for validation error
			if (!$post) {
				// Get the validation messages.
				$errors	= $form->getErrors();
	
				// Push up to three validation messages out to the user.
				for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
					if ($errors[$i] instanceof Exception)
						$app->enqueueMessage($errors[$i]->getMessage(), 'notice');
					else
						$app->enqueueMessage($errors[$i], 'notice');
				}
	
				// Save the jform data in the session.
				$app->setUserState($form->option.'.edit.'.$form->context.'.data', $data);
				// Save the custom fields data in the session.
				$app->setUserState($form->option.'.edit.'.$form->context.'.custom', $custom);
				
				// Redirect back to the registration form.
				$this->setRedirect( $_SERVER['HTTP_REFERER'] );
				return false;
				//die('error');
			}
			
			/*if (!$post) {
				//JError::raiseWarning( 500, "Error while validating data: " . $model->getError() );
				echo "Error while validating data: " . $model->getError();
				echo '<span class="fc_return_msg">'.JText::sprintf('FLEXI_CLICK_HERE_TO_RETURN', '"JavaScript:window.history.back();"').'</span>';
				jexit();
			}*/
			
			// Some values need to be assigned after validation
			$post['attribs'] = @$data['attribs'];  // Workaround for item's template parameters being clear by validation since they are not present in item.xml
			$post['custom']  = & $custom;          // Assign array of custom field values, they are in the 'custom' form array instead of jform
			$post['jfdata']  = & $jfdata;          // Assign array of Joomfish field values, they are in the 'jfdata' form array instead of jform
			
			// Assign template parameters of the select ilayout as an sub-array (the DB model will handle the merging of parameters)
			$ilayout = @ $data['attribs']['ilayout'];  // normal not be set if frontend template editing is not shown
			if( $ilayout && !empty($data['layouts'][$ilayout]) )   $post['attribs']['layouts'] = $data['layouts'];
			//echo "<pre>"; print_r($post['attribs']); exit;
		}
		
		else {
			$post = $data;
			
			// Some values need to be assigned after validation
			$post['text'] = JRequest::getVar( 'text', '', 'post', 'string', JREQUEST_ALLOWRAW ); // Workaround for allowing raw text field
			
			// Assign template parameters of the select ilayout as an sub-array (the DB model will handle the merging of parameters)
			$ilayout = @ $post['params']['ilayout'];  // normal not be set if frontend template editing is not shown
			if( $ilayout && !empty($post['layouts'][$ilayout]) )  $post['params']['layouts'] = $post['layouts'];
			//echo "<pre>"; print_r($post['params']); exit;
			
		}
		
		// USEFULL FOR DEBUGING for J2.5 (do not remove commented code)
		//$diff_arr = array_diff_assoc ( $data, $post);
		//echo "<pre>"; print_r($diff_arr); jexit();
		
		
		// ********************************************************************************
		// PERFORM ACCESS CHECKS, NOTE: we need to check access again, despite having
		// checked them on edit form load, because user may have tampered with the form ... 
		// ********************************************************************************
		
		$type_id = (int) @ $post['type_id'];  // Typecast to int, (already done for J2.5 via validating)
		if ( !$isnew && $model->get('type_id') == $type_id ) {
			// Existing item with Type not being ALTERED, content type can be maintained regardless of privilege
			$canCreateType = true;
		} else {
			// New item or existing item with Type is being ALTERED, check privilege to create items of this type
			$canCreateType = $model->canCreateType( array($type_id), true, $types );
		}
		
		
		// ****************************************************************
		// Calculate user's privileges on current content item
		// ... canPublish IS RECALCULATED after saving, maybe comment out ?
		// ****************************************************************
		
		if (!$isnew) {
			
			if (FLEXI_J16GE) {
				$asset = 'com_content.article.' . $model->get('id');
				$canPublish = $user->authorise('core.edit.state', $asset) || ($user->authorise('core.edit.state.own', $asset) && $model->get('created_by') == $user->get('id'));
				$canEdit = $user->authorise('core.edit', $asset) || ($user->authorise('core.edit.own', $asset) && $model->get('created_by') == $user->get('id'));
				// ALTERNATIVE 1
				//$canEdit = $model->getItemAccess()->get('access-edit'); // includes privileges edit and edit-own
				// ALTERNATIVE 2
				//$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $model->get('id'));
				//$canEdit = in_array('edit', $rights) || (in_array('edit.own', $rights) && $model->get('created_by') == $user->get('id')) ;
			} else if ($user->gid >= 25) {
				$canPublish = true;
				$canEdit = true;
			} else if (FLEXI_ACCESS) {
				$rights 	= FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, $model->get('id'), $model->get('catid'));
				$canPublish = in_array('publish', $rights) || (in_array('publishown', $rights) && $model->get('created_by') == $user->get('id')) ;
				$canEdit = in_array('edit', $rights) || (in_array('editown', $rights) && $model->get('created_by') == $user->get('id')) ;
			} else {
				$canPublish = $user->authorize('com_content', 'publish', 'content', 'all');
				$canEdit = $user->authorize('com_content', 'edit', 'content', 'all') || ($user->authorize('com_content', 'edit', 'content', 'own') && $model->get('created_by') == $user->get('id'));
				//$canPublish = ($user->gid >= 21);  // At least J1.5 Publisher
				//$canEdit = ($user->gid >= 20);  // At least J1.5 Editor
			}
			
			if ( !$canEdit ) {
				// No edit privilege, check if item is editable till logoff
				if ($session->has('rendered_uneditable', 'flexicontent')) {
					$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
					$canEdit = isset($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')];
				}
			}

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

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

				$n_state_ok = in_array($item->state, $states_notify_new);
				$e_state_ok = in_array($item->state, $states_notify_existing);
				
				if ($needs_publication_approval)   $notify_emails = $nConf->emails->notify_new_pending;
				else if ($isnew && $n_state_ok)    $notify_emails = $nConf->emails->notify_new;
				else if ($isnew)                   $notify_emails = array();
				else if ($needs_version_reviewal)  $notify_emails = $nConf->emails->notify_existing_reviewal;
				else if (!$isnew && $e_state_ok)   $notify_emails = $nConf->emails->notify_existing;
				else if (!$isnew)                  $notify_emails = array();
				
				if ($needs_publication_approval)   $notify_text = $params->get('text_notify_new_pending');
				else if ($isnew)                   $notify_text = $params->get('text_notify_new');
				else if ($needs_version_reviewal)  $notify_text = $params->get('text_notify_existing_reviewal');
				else if (!$isnew)                  $notify_text = $params->get('text_notify_existing');
				//print_r($notify_emails); jexit();
			}
		}
		
		
		// *********************************************************************************************************************
		// If there are emails to notify for current saving case, then send the notifications emails, but 
		// *********************************************************************************************************************
		if ( !empty($notify_emails) && count($notify_emails) ) {
			$notify_vars = new stdClass();
			$notify_vars->needs_version_reviewal     = $needs_version_reviewal;
			$notify_vars->needs_publication_approval = $needs_publication_approval;
			$notify_vars->isnew         = $isnew;
			$notify_vars->notify_emails = $notify_emails;
			$notify_vars->notify_text   = $notify_text;
			$notify_vars->before_cats   = $before_cats;
			$notify_vars->after_cats    = $after_cats;
			$notify_vars->original_item = @ $original_item;
			
			$model->sendNotificationEmails($notify_vars, $params, $manual_approval_request=0);
		}
		
		
		// ***************************************************
		// CLEAN THE CACHE so that our changes appear realtime
		// ***************************************************
		if (FLEXI_J16GE) {
			$cache = FLEXIUtilities::getCache($group='', 0);
			$cache->clean('com_flexicontent_items');
			$cache->clean('com_flexicontent_filters');
			$cache = FLEXIUtilities::getCache($group='', 1);
			$cache->clean('com_flexicontent_items');
			$cache->clean('com_flexicontent_filters');
		} else {
			$itemcache = JFactory::getCache('com_flexicontent_items');
			$itemcache->clean();
			$filtercache = JFactory::getCache('com_flexicontent_filters');
			$filtercache->clean();
		}
		
		
		// ****************************************************************************************************************************
		// Recalculate EDIT PRIVILEGE of new item. Reason for needing to do this is because we can have create permission in a category
		// and thus being able to set this category as item's main category, but then have no edit/editown permission for this category
		// ****************************************************************************************************************************
		if (FLEXI_J16GE) {
			$asset = 'com_content.article.' . $model->get('id');
			$canEdit = $user->authorise('core.edit', $asset) || ($user->authorise('core.edit.own', $asset) && $model->get('created_by') == $user->get('id'));
			// ALTERNATIVE 1
			//$canEdit = $model->getItemAccess()->get('access-edit'); // includes privileges edit and edit-own
			// ALTERNATIVE 2
			//$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $model->get('id'));
			//$canEdit = in_array('edit', $rights) || (in_array('edit.own', $rights) && $model->get('created_by') == $user->get('id')) ;
		} else if (FLEXI_ACCESS && $user->gid < 25) {
			$rights 	= FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, $model->get('id'), $model->get('catid'));
			$canEdit = in_array('edit', $rights) || (in_array('editown', $rights) && $model->get('created_by') == $user->get('id')) ;
		} else {
			// This is meaningful when executed in frontend, since all backend users (managers and above) can edit items
			$canEdit = $user->authorize('com_content', 'edit', 'content', 'all') || ($user->authorize('com_content', 'edit', 'content', 'own') && $model->get('created_by') == $user->get('id'));
		}
		
		
		// *******************************************************************************************************
		// Check if user can not edit item further (due to changed main category, without edit/editown permission)
		// *******************************************************************************************************
		if (!$canEdit)
		{
			if ($task=='apply') {
				// APPLY TASK: Temporarily set item to be editable till closing it
				$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
				$rendered_uneditable[$model->get('id')]  = 1;
				$session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
				$canEdit = 1;
			}
			
			else if ( $newly_submitted_item ) {
				// NEW ITEM: Do not use editable till logoff behaviour
				// ALSO: Clear editable FLAG set in the case that 'apply' button was used during new item creation
				if ( !$params->get('items_session_editable', 0) ) {
					$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
					if ( isset($rendered_uneditable[$model->get('id')]) ) {
						unset( $rendered_uneditable[$model->get('id')] );
						$session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
					}
				}
			}
			
			else {
				// EXISTING ITEM: (if enabled) Use the editable till logoff behaviour
				if ( $params->get('items_session_editable', 0) ) {
					
					// Set notice for existing item being editable till logoff 
					JError::raiseNotice( 403, JText::_( 'FLEXI_CANNOT_EDIT_AFTER_LOGOFF' ) );
					
					// Allow item to be editable till logoff
					$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
					$rendered_uneditable[$model->get('id')]  = 1;
					$session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
					$canEdit = 1;
				}
			}
			
			// Set notice about saving an item that cannot be changed further
			if ( !$canEdit ) {
				$app->enqueueMessage(JText::_( 'FLEXI_CANNOT_MAKE_FURTHER_CHANGES_TO_CONTENT' ), 'message' );
			}
		}
		
		
		// ****************************************************************
		// Check for new Content Item is being closed, and clear some flags
		// ****************************************************************
		
		if ($task!='apply' && $newly_submitted_item )
		{
			// Clear item from being marked as newly submitted
			unset($newly_submitted[$model->get('id')]);
			$session->set('newly_submitted', $newly_submitted, 'flexicontent');
			
			// The 'apply' task may set 'editable till logoff' FLAG ...
			// CLEAR IT, since NEW content this is meant to be used temporarily
			if ( !$params->get('items_session_editable', 0) ) {
				$rendered_uneditable = $session->get('rendered_uneditable', array(),'flexicontent');
				if ( isset($rendered_uneditable[$model->get('id')]) ) {
					unset( $rendered_uneditable[$model->get('id')] );
					$session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
				}
			}
		}
		
		
		// ****************************************
		// Saving is done, decide where to redirect
		// ****************************************
		
		// REDIRECT CASE FOR APPLYING: Save and reload the item edit form
		if ($task=='apply') {
			$msg = JText::_( 'FLEXI_ITEM_SAVED' );
			
			// Create the URL
			global $globalcats;
			$Itemid = JRequest::getInt('Itemid', 0);  // maintain current menu item if this was given
			$item_url = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $globalcats[$item->catid]->slug, $Itemid));
			$link = $item_url
				.(strstr($item_url, '?') ? '&' : '?').'task=edit'
				;
			
			// Important pass referer back to avoid making the form itself the referer
			// but also check that referer URL is 'safe' (allowed) , e.g. not an offsite URL, otherwise set referer to HOME page
			$referer = JRequest::getString('referer', JURI::base(), 'post');
			if ( ! flexicontent_html::is_safe_url($referer) ) $referer = JURI::base();
			$return = '&return='.base64_encode( $referer );
			$link .= $return;
		}
		
		// REDIRECT CASES FOR SAVING
		else {
			
			// REDIRECT CASE: Return to a custom page after creating a new item (e.g. a thanks page)
			if ( $newly_submitted_item && $submit_redirect_url_fe ) {
				$link = $submit_redirect_url_fe;
				$msg = JText::_( 'FLEXI_ITEM_SAVED' );
			}
			// REDIRECT CASE: Save and preview the latest version
			else if ($task=='save_a_preview') {
				$msg = JText::_( 'FLEXI_ITEM_SAVED' );
				$link = JRoute::_(FlexicontentHelperRoute::getItemRoute($model->_item->id.':'.$model->_item->alias, $model->_item->catid, 0, $model->_item).'&preview=1', false);
			}
			// REDIRECT CASE: Return to the form 's referer (previous page) after item saving
			else {
				$msg = $newly_submitted_item ? JText::_( 'FLEXI_THANKS_SUBMISSION' ) : JText::_( 'FLEXI_ITEM_SAVED' );
				
				// Check that referer URL is 'safe' (allowed) , e.g. not an offsite URL, otherwise for returning to HOME page
				$link = JRequest::getString('referer', JURI::base(), 'post');
				if ( ! flexicontent_html::is_safe_url($link) ) {
					if ( $dolog ) JFactory::getApplication()->enqueueMessage( 'refused redirection to possible unsafe URL: '.$link, 'notice' );
					$link = JURI::base();
				}
			}
		}
		
		$this->setRedirect($link, $msg);
	}
コード例 #11
0
ファイル: view.html.php プロジェクト: kosmosby/medicine-prof
    /**
     * Creates the item page
     *
     * @since 1.0
     */
    function display($tpl = null)
    {
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        global $globalcats;
        $categories = $globalcats;
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $option = JRequest::getVar('option');
        $nullDate = $db->getNullDate();
        // Get the COMPONENT only parameters
        $params = clone JComponentHelper::getParams('com_flexicontent');
        if (!FLEXI_J16GE) {
            jimport('joomla.html.pane');
            $pane = JPane::getInstance('sliders');
            $editor = JFactory::getEditor();
        }
        // Some flags
        $enable_translation_groups = $params->get("enable_translation_groups") && (FLEXI_J16GE || FLEXI_FISH);
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
        flexicontent_html::loadFramework('jQuery');
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        // Load custom behaviours: form validation, popup tooltips
        //JHTML::_('behavior.formvalidation');
        JHTML::_('behavior.tooltip');
        // Add css to document
        $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/flexicontentbackend.css');
        if (FLEXI_J30GE) {
            $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j3x.css');
        } else {
            if (FLEXI_J16GE) {
                $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j25.css');
            } else {
                $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j15.css');
            }
        }
        // Add js function to overload the joomla submitform
        $document->addScript(JURI::root() . 'components/com_flexicontent/assets/js/admin.js');
        $document->addScript(JURI::root() . 'components/com_flexicontent/assets/js/validate.js');
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScript(JURI::root() . 'components/com_flexicontent/assets/js/itemscreen.js');
        // ***********************
        // Get data from the model
        // ***********************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        $item = $this->get('Item');
        if (FLEXI_J16GE) {
            $form = $this->get('Form');
        }
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // ***************************
        // Get Associated Translations
        // ***************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $langs = FLEXIUtilities::getLanguages('code');
        }
        // Get item id and new flag
        $cid = $model->getId();
        $isnew = !$cid;
        // Create and set a unique item id for plugins that needed it
        JRequest::setVar('unique_tmp_itemid', $cid ? $cid : date('_Y_m_d_h_i_s_', time()) . uniqid(true));
        // Get number of subscribers
        $subscribers = $model->getSubscribersCount();
        // ******************
        // Version Panel data
        // ******************
        // Get / calculate some version related variables
        $versioncount = $model->getVersionCount();
        $versionsperpage = $params->get('versionsperpage', 10);
        $pagecount = (int) ceil($versioncount / $versionsperpage);
        // Data need by version panel: (a) current version page, (b) currently active version
        $current_page = 1;
        $k = 1;
        $allversions = $model->getVersionList();
        foreach ($allversions as $v) {
            if ($k > 1 && ($k - 1) % $versionsperpage == 0) {
                $current_page++;
            }
            if ($v->nr == $item->version) {
                break;
            }
            $k++;
        }
        // Finally fetch the version data for versions in current page
        $versions = $model->getVersionList(($current_page - 1) * $versionsperpage, $versionsperpage);
        // *****************
        // Type related data
        // *****************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get and merge type parameters
        $tparams = $this->get('Typeparams');
        $tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
        $params->merge($tparams);
        // Apply type configuration if it type is set
        // Get user allowed permissions on the item ... to be used by the form rendering
        // Also hide parameters panel if user can not edit parameters
        $perms = $this->_getItemPerms($item, $typesselected);
        if (!$perms['canparams']) {
            $document->addStyleDeclaration((FLEXI_J16GE ? '#details-options' : '#det-pane') . '{display:none;}');
        }
        // ******************
        // Create the toolbar
        // ******************
        $toolbar = JToolBar::getInstance('toolbar');
        // SET toolbar title
        if ($cid) {
            JToolBarHelper::title(JText::_('FLEXI_EDIT_ITEM'), 'itemedit');
            // Editing existing item
        } else {
            JToolBarHelper::title(JText::_('FLEXI_NEW_ITEM'), 'itemadd');
            // Creating new item
        }
        // Add a preview button for LATEST version of the item
        if ($cid) {
            // Domain URL and autologin vars
            $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
            $autologin = '';
            //$params->get('autoflogin', 1) ? '&fcu='.$user->username . '&fcp='.$user->password : '';
            // Check if we are in the backend, in the back end we need to set the application to the site app instead
            $isAdmin = JFactory::getApplication()->isAdmin();
            if ($isAdmin && FLEXI_J16GE) {
                JFactory::$application = JApplication::getInstance('site');
            }
            // Create the URL
            $item_url = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->id . ':' . $item->alias, $categories[$item->catid]->slug) . $autologin);
            // Check if we are in the backend again
            // In backend we need to remove administrator from URL as it is added even though we've set the application to the site app
            if ($isAdmin) {
                if (FLEXI_J16GE) {
                    $admin_folder = str_replace(JURI::root(true), '', JURI::base(true));
                    $item_url = str_replace($admin_folder, '', $item_url);
                    // Restore application
                    JFactory::$application = JApplication::getInstance('administrator');
                } else {
                    $item_url = JURI::root(true) . '/' . $item_url;
                }
            }
            $previewlink = $item_url . (strstr($item_url, '?') ? '&' : '?') . 'preview=1';
            //$previewlink     = str_replace('&amp;', '&', $previewlink);
            //$previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $categories[$item->catid]->slug)) .$autologin;
            if (!$params->get('use_versioning', 1) || $item->version == $item->current_version && $item->version == $item->last_version) {
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('Preview') . '</a>', 'preview');
            } else {
                // Add a preview button for (currently) LOADED version of the item
                $previewlink_loaded_ver = $previewlink . '&version=' . $item->version;
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink_loaded_ver . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('FLEXI_PREVIEW_FORM_LOADED_VERSION') . ' [' . $item->version . ']</a>', 'preview');
                // Add a preview button for currently ACTIVE version of the item
                $previewlink_active_ver = $previewlink . '&version=' . $item->current_version;
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink_active_ver . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('FLEXI_PREVIEW_FRONTEND_ACTIVE_VERSION') . ' [' . $item->current_version . ']</a>', 'preview');
                // Add a preview button for currently LATEST version of the item
                $previewlink_last_ver = $previewlink;
                //'&version='.$item->last_version;
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink_last_ver . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('FLEXI_PREVIEW_LATEST_SAVED_VERSION') . ' [' . $item->last_version . ']</a>', 'preview');
            }
            JToolBarHelper::spacer();
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
        }
        // Common Buttons
        if (FLEXI_J16GE) {
            JToolBarHelper::apply('items.apply');
            if (!$isnew || $item->version) {
                JToolBarHelper::save('items.save');
            }
            if (!$isnew || $item->version) {
                JToolBarHelper::custom('items.saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
            }
            JToolBarHelper::cancel('items.cancel');
        } else {
            JToolBarHelper::apply();
            if (!$isnew || $item->version) {
                JToolBarHelper::save();
            }
            if (!$isnew || $item->version) {
                JToolBarHelper::custom('saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
            }
            JToolBarHelper::cancel();
        }
        // Check if saving an item that translates an original content in site's default language
        $is_content_default_lang = substr(flexicontent_html::getSiteDefaultLang(), 0, 2) == substr($item->language, 0, 2);
        $modify_untraslatable_values = $enable_translation_groups && !$is_content_default_lang && $item->lang_parent_id && $item->lang_parent_id != $item->id;
        // *****************************************************************************
        // Get (CORE & CUSTOM) fields and their VERSIONED values and then
        // (a) Apply Content Type Customization to CORE fields (label, description, etc)
        // (b) Create the edit html of the CUSTOM fields by triggering 'onDisplayField'
        // *****************************************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $fields = $this->get('Extrafields');
        if ($print_logging_info) {
            $fc_run_times['get_field_vals'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        foreach ($fields as $field) {
            // a. Apply CONTENT TYPE customizations to CORE FIELDS, e.g a type specific label & description
            // NOTE: the field parameters are already created so there is not need to call this for CUSTOM fields, which do not have CONTENT TYPE customizations
            if ($field->iscore) {
                FlexicontentFields::loadFieldConfig($field, $item);
            }
            // b. Create field 's editing HTML (the form field)
            // NOTE: this is DONE only for CUSTOM fields, since form field html is created by the form for all CORE fields, EXCEPTION is the 'text' field (see bellow)
            if (!$field->iscore) {
                if (FLEXI_J16GE) {
                    $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                } else {
                    if (FLEXI_ACCESS && $user->gid < 25) {
                        $is_editable = !$field->valueseditable || FAccess::checkAllContentAccess('com_content', 'submit', 'users', $user->gmid, 'field', $field->id);
                    } else {
                        $is_editable = 1;
                    }
                }
                if (!$is_editable) {
                    $field->html = '<div class="fc-mssg fc-warning">' . JText::_('FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                } else {
                    if ($modify_untraslatable_values && $field->untranslatable) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_('FLEXI_FIELD_VALUE_IS_UNTRANSLATABLE') . '</div>';
                    } else {
                        FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // *************************
        // Get tags used by the item
        // *************************
        $usedtagsIds = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtags = $model->getUsedtagsData($usedtagsIds);
        // *******************************
        // Get categories used by the item
        // *******************************
        if ($isnew) {
            // Case for preselected main category for new items
            $maincat = $item->catid ? $item->catid : JRequest::getInt('maincat', 0);
            if (!$maincat) {
                $maincat = $app->getUserStateFromRequest($option . '.items.filter_cats', 'filter_cats', '', 'int');
            }
            if ($maincat) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($tparams->get('cid_default')) {
                $selectedcats = $tparams->get('cid_default');
            }
            if ($tparams->get('catid_default')) {
                $item->catid = $tparams->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        //$selectedcats 	= $isnew ? array() : $fields['categories']->value;
        //echo "<br/>row->tags: "; print_r($item->tags);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsIds);
        //echo "<br/>usedtags (data): "; print_r($usedtags);
        //echo "<br/>row->categories: "; print_r($item->categories);
        //echo "<br/>selectedcats: "; print_r($selectedcats);
        // *********************************************************************************************
        // Build select lists for the form field. Only few of them are used in J1.6+, since we will use:
        // (a) form XML file to declare them and then (b) getInput() method form field to create them
        // *********************************************************************************************
        // First clean form data, we do this after creating the description field which may contain HTML
        JFilterOutput::objectHTMLSafe($item, ENT_QUOTES);
        $lists = array();
        // build granular access list
        if (!FLEXI_J16GE) {
            if (FLEXI_ACCESS) {
                if (isset($user->level)) {
                    $lists['access'] = FAccess::TabGmaccess($item, 'item', 1, 0, 0, 1, 0, 1, 0, 1, 1);
                } else {
                    $lists['access'] = JText::_('Your profile has been changed, please logout to access to the permissions');
                }
            } else {
                $lists['access'] = JHTML::_('list.accesslevel', $item);
                // created but not used in J1.5 backend form
            }
        }
        // build state list
        $_arc_ = FLEXI_J16GE ? 2 : -1;
        $non_publishers_stategrp = $perms['isSuperAdmin'] || $item->state == -3 || $item->state == -4;
        $special_privelege_stategrp = $item->state == $_arc_ || $perms['canarchive'] || ($item->state == -2 || $perms['candelete']);
        $state = array();
        // Using <select> groups
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_PUBLISHERS_WORKFLOW_STATES'));
        }
        $state[] = JHTML::_('select.option', 1, JText::_('FLEXI_PUBLISHED'));
        $state[] = JHTML::_('select.option', 0, JText::_('FLEXI_UNPUBLISHED'));
        $state[] = JHTML::_('select.option', -5, JText::_('FLEXI_IN_PROGRESS'));
        // States reserved for workflow
        if ($non_publishers_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_NON_PUBLISHERS_WORKFLOW_STATES'));
        }
        if ($item->state == -3 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -3, JText::_('FLEXI_PENDING'));
        }
        if ($item->state == -4 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -4, JText::_('FLEXI_TO_WRITE'));
        }
        // Special access states
        if ($special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_SPECIAL_ACTION_STATES'));
        }
        if ($item->state == $_arc_ || $perms['canarchive']) {
            $state[] = JHTML::_('select.option', $_arc_, JText::_('FLEXI_ARCHIVED'));
        }
        if ($item->state == -2 || $perms['candelete']) {
            $state[] = JHTML::_('select.option', -2, JText::_('FLEXI_TRASHED'));
        }
        // Close last <select> group
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
        }
        $fieldname = FLEXI_J16GE ? 'jform[state]' : 'state';
        $elementid = FLEXI_J16GE ? 'jform_state' : 'state';
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, $fieldname, $attribs, 'value', 'text', $item->state, $elementid);
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
            // build featured flag
            $fieldname = 'jform[featured]';
            $elementid = 'jform_featured';
            /*
            $options = array();
            $options[] = JHTML::_('select.option',  0, JText::_( 'FLEXI_NO' ) );
            $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_YES' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
            $lists['featured'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $item->featured, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array(0 => JText::_('FLEXI_NO'), 1 => JText::_('FLEXI_YES'));
            $lists['featured'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id == $item->featured ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-label="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['featured'] .= ' <input type="radio" id="' . $elementid_no . '" element_group_id="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // *** EOF: J1.5 SPECIFIC SELECT LISTS
        // build version approval list
        $fieldname = FLEXI_J16GE ? 'jform[vstate]' : 'vstate';
        $elementid = FLEXI_J16GE ? 'jform_vstate' : 'vstate';
        /*
        $options = array();
        $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_NO' ) );
        $options[] = JHTML::_('select.option',  2, JText::_( 'FLEXI_YES' ) );
        $attribs = FLEXI_J16GE ? ' style ="float:left!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
        $lists['vstate'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', 2, $elementid);
        */
        $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
        $attribs = ' class="' . $classes . '" ';
        $i = 1;
        $options = array(1 => JText::_('FLEXI_NO'), 2 => JText::_('FLEXI_YES'));
        $lists['vstate'] = '';
        foreach ($options as $option_id => $option_label) {
            $checked = $option_id == 2 ? ' checked="checked"' : '';
            $elementid_no = $elementid . '_' . $i;
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
            }
            $extra_params = !$prettycheckable_added ? '' : ' data-label="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
            $lists['vstate'] .= ' <input type="radio" id="' . $elementid_no . '" element_group_id="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '&nbsp;' . JText::_($option_label) . '</label>';
            }
            $i++;
        }
        // build field for notifying subscribers
        if (!$subscribers) {
            $lists['notify'] = !$isnew ? JText::_('FLEXI_NO_SUBSCRIBERS_EXIST') : '';
        } else {
            // b. Check if notification emails to subscribers , were already sent during current session
            $subscribers_notified = $session->get('subscribers_notified', array(), 'flexicontent');
            if (!empty($subscribers_notified[$item->id])) {
                $lists['notify'] = JText::_('FLEXI_SUBSCRIBERS_ALREADY_NOTIFIED');
            } else {
                // build favs notify field
                $fieldname = FLEXI_J16GE ? 'jform[notify]' : 'notify';
                $elementid = FLEXI_J16GE ? 'jform_notify' : 'notify';
                /*
                $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
                $lists['notify'] = '<input type="checkbox" name="jform[notify]" id="jform_notify" '.$attribs.' /> '. $lbltxt;
                */
                $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
                $attribs = ' class="' . $classes . '" ';
                $lbltxt = $subscribers . ' ' . JText::_($subscribers > 1 ? 'FLEXI_SUBSCRIBERS' : 'FLEXI_SUBSCRIBER');
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '<label class="fccheckradio_lbl" for="' . $elementid . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-label="' . $lbltxt . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['notify'] = ' <input type="checkbox" id="' . $elementid . '" element_group_id="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="1" ' . $extra_params . ' checked="checked" />';
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '&nbsp;' . $lbltxt . '</label>';
                }
            }
        }
        // Retrieve author configuration
        $db->setQuery('SELECT author_basicparams FROM #__flexicontent_authors_ext WHERE user_id = ' . $user->id);
        if ($authorparams = $db->loadResult()) {
            $authorparams = FLEXI_J16GE ? new JRegistry($authorparams) : new JParameter($authorparams);
        }
        // Get author's maximum allowed categories per item and set js limitation
        $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
        $document->addScriptDeclaration('
			max_cat_assign_fc = ' . $max_cat_assign . ';
			existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
			max_cat_overlimit_msg_fc = "' . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES', true) . '";
		');
        // Creating categorories tree for item assignment, we use the 'create' privelege
        $actions_allowed = array('core.create');
        // Featured categories form field
        $featured_cats_parent = $params->get('featured_cats_parent', 0);
        $featured_cats = array();
        $enable_featured_cid_selector = $perms['multicat'] && $perms['canchange_featcat'];
        if ($featured_cats_parent) {
            $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
            $featured_sel = array();
            foreach ($selectedcats as $item_cat) {
                if (isset($featured_tree[$item_cat])) {
                    $featured_sel[] = $item_cat;
                }
            }
            $class = "use_select2_lib select2_list_selected";
            $attribs = 'class="' . $class . '" multiple="multiple" size="8"';
            $attribs .= $enable_featured_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = FLEXI_J16GE ? 'jform[featured_cid][]' : 'featured_cid[]';
            $lists['featured_cid'] = ($enable_featured_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($featured_tree, $fieldname, $featured_sel, 3, $attribs, true, true, $actions_allowed);
        } else {
            // Do not display, if not configured or not allowed to the user
            $lists['featured_cid'] = false;
        }
        // Multi-category form field, for user allowed to use multiple categories
        $lists['cid'] = '';
        $enable_cid_selector = $perms['multicat'] && $perms['canchange_seccat'];
        if (1) {
            if ($tparams->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('cid_allowed_parent'), $depth_limit = 0);
            } else {
                $cid_tree =& $categories;
            }
            // Get author's maximum allowed categories per item and set js limitation
            $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
            $document->addScriptDeclaration('
				max_cat_assign_fc = ' . $max_cat_assign . ';
				existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
				max_cat_overlimit_msg_fc = "' . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES', true) . '";
			');
            $class = "mcat use_select2_lib select2_list_selected";
            $class .= $max_cat_assign ? " validate-fccats" : " validate";
            $attribs = 'class="' . $class . '" multiple="multiple" size="20"';
            $attribs .= $enable_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = FLEXI_J16GE ? 'jform[cid][]' : 'cid[]';
            $skip_subtrees = $featured_cats_parent ? array($featured_cats_parent) : array();
            $lists['cid'] = ($enable_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($cid_tree, $fieldname, $selectedcats, false, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees, $disable_subtrees = array());
        } else {
            if (count($selectedcats) > 1) {
                foreach ($selectedcats as $catid) {
                    $cat_titles[$catid] = $globalcats[$catid]->title;
                }
                $lists['cid'] .= implode(', ', $cat_titles);
            } else {
                $lists['cid'] = false;
            }
        }
        // Main category form field
        $class = 'scat use_select2_lib';
        if ($perms['multicat']) {
            $class .= ' validate-catid';
        } else {
            $class .= ' required';
        }
        $attribs = 'class="' . $class . '"';
        $fieldname = FLEXI_J16GE ? 'jform[catid]' : 'catid';
        $enable_catid_selector = $isnew && !$tparams->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($tparams->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('catid_allowed_parent'), $depth_limit = 0);
        } else {
            $catid_tree =& $categories;
        }
        $lists['catid'] = false;
        if (!empty($catid_tree)) {
            $disabled = $enable_catid_selector ? '' : ' disabled="disabled"';
            $attribs .= $disabled;
            $lists['catid'] = ($enable_catid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($catid_tree, $fieldname, $item->catid, 2, $attribs, true, true, $actions_allowed);
        } else {
            if (!$isnew && $item->catid) {
                $lists['catid'] = $globalcats[$item->catid]->title;
            }
        }
        //buid types selectlist
        $class = 'required use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $fieldname = FLEXI_J16GE ? 'jform[type_id]' : 'type_id';
        $elementid = FLEXI_J16GE ? 'jform_type_id' : 'type_id';
        $lists['type'] = flexicontent_html::buildtypesselect($types, $fieldname, $typesselected->id, 1, $attribs, $elementid, $check_perms = true);
        //build languages list
        $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        if (!$isnew && $allowed_langs) {
            $allowed_langs[] = $item->language;
        }
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $language_fieldname = FLEXI_J16GE ? 'jform[language]' : 'language';
        if (FLEXI_FISH || FLEXI_J16GE) {
            $lists['languages'] = flexicontent_html::buildlanguageslist($language_fieldname, '', $item->language, 3, $allowed_langs);
        }
        // Label for current item state: published, unpublished, archived etc
        switch ($item->state) {
            case 0:
                $published = JText::_('FLEXI_UNPUBLISHED');
                break;
            case 1:
                $published = JText::_('FLEXI_PUBLISHED');
                break;
            case -1:
                $published = JText::_('FLEXI_ARCHIVED');
                break;
            case -3:
                $published = JText::_('FLEXI_PENDING');
                break;
            case -5:
                $published = JText::_('FLEXI_IN_PROGRESS');
                break;
            case -4:
            default:
                $published = JText::_('FLEXI_TO_WRITE');
                break;
        }
        // **************************************************************
        // Handle Item Parameters Creation and Load their values for J1.5
        // In J1.6+ we declare them in the item form XML file
        // **************************************************************
        if (!FLEXI_J16GE) {
            // Create the form parameters object
            if (FLEXI_ACCESS) {
                $formparams = new JParameter('', JPATH_COMPONENT . DS . 'models' . DS . 'item2.xml');
            } else {
                $formparams = new JParameter('', JPATH_COMPONENT . DS . 'models' . DS . 'item.xml');
            }
            // Details Group
            $active = intval($item->created_by) ? intval($item->created_by) : $user->get('id');
            if (!FLEXI_ACCESS) {
                $formparams->set('access', $item->access);
            }
            $formparams->set('created_by', $active);
            $formparams->set('created_by_alias', $item->created_by_alias);
            $formparams->set('created', JHTML::_('date', $item->created, '%Y-%m-%d %H:%M:%S'));
            $formparams->set('publish_up', JHTML::_('date', $item->publish_up, '%Y-%m-%d %H:%M:%S'));
            if (JHTML::_('date', $item->publish_down, '%Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
                $formparams->set('publish_down', JText::_('FLEXI_NEVER'));
            } else {
                $formparams->set('publish_down', JHTML::_('date', $item->publish_down, '%Y-%m-%d %H:%M:%S'));
            }
            // Advanced Group
            $formparams->loadINI($item->attribs);
            //echo "<pre>"; print_r($formparams->_xml['themes']->_children[0]);  echo "<pre>"; print_r($formparams->_xml['themes']->param[0]); exit;
            foreach ($formparams->_xml['themes']->_children as $i => $child) {
                if (isset($child->_attributes['enableparam']) && !$params->get($child->_attributes['enableparam'])) {
                    unset($formparams->_xml['themes']->_children[$i]);
                    unset($formparams->_xml['themes']->param[$i]);
                }
            }
            // Metadata Group
            $formparams->set('description', $item->metadesc);
            $formparams->set('keywords', $item->metakey);
            $formparams->loadINI($item->metadata);
        } else {
            if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
                $form->setValue('publish_down', null, JText::_('FLEXI_NEVER'));
            }
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        } else {
            if (!is_array($allowed_tmpls)) {
                $allowed_tmpls = !FLEXI_J16GE ? array($allowed_tmpls) : explode("|", $allowed_tmpls);
            }
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            if (FLEXI_J16GE) {
                $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
                $jform->load($tmpl->params);
                $tmpl->params = $jform;
                foreach ($tmpl->params->getGroup('attribs') as $field) {
                    $fieldname = $field->__get('fieldname');
                    $value = $item->itemparams->get($fieldname);
                    if (strlen($value)) {
                        $tmpl->params->setValue($fieldname, 'attribs', $value);
                    }
                }
            } else {
                $tmpl->params->loadINI($item->attribs);
            }
        }
        // ******************************
        // Assign data to VIEW's template
        // ******************************
        $this->assignRef('document', $document);
        $this->assignRef('lists', $lists);
        $this->assignRef('row', $item);
        if (FLEXI_J16GE) {
            $this->assignRef('form', $form);
        } else {
            $this->assignRef('editor', $editor);
            $this->assignRef('pane', $pane);
            $this->assignRef('formparams', $formparams);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('typesselected', $typesselected);
        $this->assignRef('published', $published);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('fields', $fields);
        $this->assignRef('versions', $versions);
        $this->assignRef('pagecount', $pagecount);
        $this->assignRef('params', $params);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('tmpls', $tmpls);
        $this->assignRef('usedtags', $usedtags);
        $this->assignRef('perms', $perms);
        $this->assignRef('current_page', $current_page);
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        parent::display($tpl);
        if ($print_logging_info) {
            $fc_run_times['form_rendering'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
    }
コード例 #12
0
ファイル: view.html.php プロジェクト: kosmosby/medicine-prof
 function _displayCopyMove($tpl = null, $cid)
 {
     global $globalcats;
     $app = JFactory::getApplication();
     //initialise variables
     $user = JFactory::getUser();
     $document = JFactory::getDocument();
     $option = JRequest::getCmd('option');
     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 functions
     $document->addScript('components/com_flexicontent/assets/js/copymove.js');
     //get vars
     $filter_order = $app->getUserStateFromRequest($option . '.items.filter_order', 'filter_order', '', 'cmd');
     $filter_order_Dir = $app->getUserStateFromRequest($option . '.items.filter_order_Dir', 'filter_order_Dir', '', 'word');
     //$perms 	= FlexicontentHelperPerm::getPerm();
     // Create document/toolbar titles
     $copy_behaviour = JRequest::getVar('copy_behaviour', 'copy/move');
     if ($copy_behaviour == 'translate') {
         $doc_title = JText::_('FLEXI_TRANSLATE_ITEM');
     } else {
         $doc_title = JText::_('FLEXI_COPYMOVE_ITEM');
     }
     $site_title = $document->getTitle();
     JToolBarHelper::title($doc_title, 'itemadd');
     $document->setTitle($doc_title . ' - ' . $site_title);
     // Create the toolbar
     JToolBarHelper::save(FLEXI_J16GE ? 'items.copymove' : 'copymove');
     JToolBarHelper::cancel(FLEXI_J16GE ? 'items.cancel' : 'cancel');
     //Get data from the model
     $rows = $this->get('Data');
     $itemCats = $this->get('ItemCats');
     $categories = $globalcats;
     // build the main category select list
     $lists['maincat'] = flexicontent_cats::buildcatselect($categories, 'maincat', '', 0, 'class="inputbox" size="10"', false, false);
     // build the secondary categories select list
     $lists['seccats'] = flexicontent_cats::buildcatselect($categories, 'seccats[]', '', 0, 'class="inputbox" multiple="multiple" size="10"', false, false);
     //assign data to template
     $this->assignRef('lists', $lists);
     $this->assignRef('rows', $rows);
     $this->assignRef('itemCats', $itemCats);
     $this->assignRef('cid', $cid);
     $this->assignRef('user', $user);
     parent::display($tpl);
 }
コード例 #13
0
ファイル: controller.php プロジェクト: kosmosby/medicine-prof
        function save_import()
	{
		// Check for request forgeries
		//JRequest::checkToken() or jexit( 'Invalid Token' );
		
		
		
                //mara
                
                $arr_countries = array('AL' => 'Albania',
 'AM' => 'Armenia' ,
 'ARG' =>'Argentina' ,
 'AU' => 'Australia' ,
 'AUT' => 'Austria' ,
 'AZ' =>'Azerbaidjan' ,
 'BEL' => 'Belgium' ,
 'BGD' => 'Bangladesh' ,
 'BLG' => 'Bulgaria' ,
 'BLR' => 'Belarus' ,
 'BOS' => 'Bosnia-Herzegovina' ,
 'BRA' => 'Brazil' ,
 'CAN' => 'Canada' ,
 'CB' => 'Cuba' ,
 'CHE' => 'Switzerland' ,
 'CHI' => 'China' ,
 'CHL' => 'Chile' ,
 'CS' => 'Czech Republic' ,
 'DEU' => 'Germany' ,
 'DNK' => 'Denmark' ,
 'EGP' => 'Egypt' ,
 'EST' => 'Estonia' ,
 'FIN' => 'Finland' ,
 'FRA' => 'France' ,
 'GBR' => 'Great Britain' ,
 'GBRUSA' => 'Great Britain' ,
 'GEO' => 'Georgia' ,
 'GR' => 'Greece' ,
 'HK' => 'Hong Kong' ,
 'HOR' => 'Croatia' ,
 'HUN' => 'Hungary' ,
 'IDZ' => 'Indonesia' ,
 'IND' => 'India' ,
 'IOR' => 'Jordan' ,
 'IRA' => 'Iran' ,
 'IRL' => 'Ireland' ,
 'ISL' => 'Iceland' ,
 'ISR' => 'Israel' ,
 'ITA' => 'Italy' ,
 'JPN' => 'Japan' ,
 'KAZ' => 'Kazakhstan' ,
 'KGZ' => 'Kyrgyzstan' ,
 'KIP' => 'Cyprus' ,
 'LAT' => 'Latvia' ,
 'LIT' => 'Lithuania' ,
 'LUX' => 'Luxembourg' ,
 'MAK' => 'Macedonia' ,
 'ME' => 'Montenegro' ,
 'MEK' => 'Mexico' ,
 'MLT' => 'Malta' ,
 'MOL' => 'Moldavia' ,
 'MON' => 'Monaco' ,
 'NID' => 'Netherlands' ,
 'NOR' => 'Norway' ,
 'PAK' => 'Pakistan' ,
 'POL' => 'Poland' ,
 'PORT' => 'Portugal' ,
 'PR' => 'Puerto Rico' ,
 'PS' => 'Palestinian Territory' ,
 'RS' => 'Serbia' ,
 'RUM' => 'Romania' ,
 'RUS' => 'Russian Federation' ,
 'SA' => 'Saudi Arabia' ,
 'SCH' => 'Serbia' ,
 'SGP' => 'Singapore' ,
 'SHE' => 'Switzerland' ,
 'SKO' => 'South Korea' ,
 'SLO' => 'Slovenia' ,
 'SLR' => 'Slovak Republic' ,
 'SM' => 'San Marino' ,
 'SPN' => 'Spain' ,
 'SWE' => 'Sweden' ,
 'SYR' => 'Syria' ,
 'TA' => 'Thailand' ,
 'TUR' => 'Turkey' ,
 'UAR' => 'South Africa' ,
 'UGS' => 'Serbia' ,
 'UKR' => 'Ukraine' ,
 'unk' => 'Unknown' ,
 'USA' => 'United States' ,
 'USAFRA' => 'United States' ,
 'Uzb' => 'Uzbekistan' ,
 'VTN' => 'Vietnam');
                
                
		mysql_connect('localhost', 'root', 'staSPE8e');
                mysql_select_db('vidal');
                mysql_query("SET NAMES utf8");
                $query = "SELECT pa.ATCCode,m.LatName,n.NozologyCode,Document.DocumentID,"
                        ."Document.RusName,Document.EngName,Document.CompiledComposition,Document.PhInfluence,Document.PhKinetics,"
                        ."Document.Dosage,Document.OverDosage,Document.Interaction,Document.Lactation,Document.SideEffects,"
                        ."Document.StorageCondition,Document.Indication,Document.ContraIndication,Document.SpecialInstruction "
                        . "FROM Document"
                        ." LEFT JOIN Document_IndicNozology as n ON Document.DocumentID = n.DocumentID"
                        ." LEFT JOIN Molecule_Document as md ON md.DocumentID = Document.DocumentID"
                        ." LEFT JOIN Molecule as m ON m.MoleculeID = md.MoleculeID"
                        ." LEFT JOIN Product_Document as pd ON pd.DocumentID = Document.DocumentID"
                        ." LEFT JOIN Product_ATC as pa ON pd.ProductID = pa.ProductID"
                        ." GROUP BY Document.DocumentID";
                $result = mysql_query($query) or die(mysql_error());
		while($all = mysql_fetch_array($result)){
                    
                    
                    // Initialize variables
		$app     = JFactory::getApplication();
		$db      = JFactory::getDBO();
		$user    = JFactory::getUser();
		$menu    = $app->getMenu()->getActive();
		$config  = JFactory::getConfig();
		$session = JFactory::getSession();
		$task	   = JRequest::getVar('task');
		$model   = $this->getModel(FLEXI_ITEMVIEW);
		$isnew   = !$model->getId();
		$ctrl_task = FLEXI_J16GE ? 'task=items.' : 'controller=items&task=';
		
		$fc_params  = JComponentHelper::getParams( 'com_flexicontent' );
		$dolog      = $fc_params->get('print_logging_info');
		
		// Get the COMPONENT only parameters
		$comp_params = JComponentHelper::getComponent('com_flexicontent')->params;
		$params = FLEXI_J16GE ? clone ($comp_params) : new JParameter( $comp_params ); // clone( JComponentHelper::getParams('com_flexicontent') );
		
		// Merge the type parameters
		$tparams = $model->getTypeparams();
		$tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
		$params->merge($tparams);
		
		// Merge the menu parameters
		if ($menu) {
			$menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);
			$params->merge($menu_params);
		}
		
		// Get needed parameters
		$submit_redirect_url_fe = $params->get('submit_redirect_url_fe', '');
		$allowunauthorize       = $params->get('allowunauthorize', 0);
                    
                    $data = array();
                    
                    $data['title'] = $all['RusName'];
                    //content
                    $data['text'] = $all['CompiledComposition'].$all['PhInfluence'].$all['PhKinetics'].$all['Dosage'].$all['OverDosage'].$all['Interaction'].$all['Lactation'].$all['SideEffects'].$all['StorageCondition'].$all['Indication'].$all['ContraIndication'].$all['SpecialInstruction'];
                    $data['state'] = 1;
                    $data['catid'] = 45;
                    $data['type_id'] = 2;
                    $data['id'] = 0;
                    //insert into content

                    //flexicontent_fields_item_relations
                    //15 field RusName EngName

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

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

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

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



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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

                                else {
                                        $post = $data;

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

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

                                }

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


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

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


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

                                if (!$isnew) {

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

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

                                } else {

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

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

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

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

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

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

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

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


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

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

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


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

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


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


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


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

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


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

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

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

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

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

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

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

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

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

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


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

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


                                // ***************************************************
                                // CLEAN THE CACHE so that our changes appear realtime
                                // ***************************************************
                                if (FLEXI_J16GE) {
                                        $cache = FLEXIUtilities::getCache($group='', 0);
                                        $cache->clean('com_flexicontent_items');
                                        $cache->clean('com_flexicontent_filters');
                                        $cache = FLEXIUtilities::getCache($group='', 1);
                                        $cache->clean('com_flexicontent_items');
                                        $cache->clean('com_flexicontent_filters');
                                } else {
                                        $itemcache = JFactory::getCache('com_flexicontent_items');
                                        $itemcache->clean();
                                        $filtercache = JFactory::getCache('com_flexicontent_filters');
                                        $filtercache->clean();
                                }


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


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

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

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

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

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

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


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

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

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


                               
                }
		//$this->setRedirect($link, $msg);
	}
コード例 #14
0
 /**
  * Method to load the Category
  *
  * @access public
  * @return array
  */
 function getCategory($pk = null, $raiseErrors = true, $checkAccess = true)
 {
     //initialize some vars
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     $cparams = $this->_params;
     if ($pk) {
         $this->_id = $pk;
     }
     // Set a specific id
     $cat_required = $this->_layout == '';
     $cat_usable = !$this->_layout || $this->_layout != 'mcats';
     // Clear category id, if current layout cannot be limited to a specific category
     $this->_id = $cat_usable ? $this->_id : 0;
     if ($this->_id) {
         require_once JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'classes' . DS . 'flexicontent.categories.php';
         // If category model is loaded from 3rd party code
         $catshelper = new flexicontent_cats($this->_id);
         $parents = $catshelper->getParentlist($all_cols = false);
         $parents_published = true;
         foreach ($parents as $parent) {
             if (!$parent->published) {
                 $parents_published = false;
                 break;
             }
         }
         if ($parents_published) {
             // ************************************************************************************************************
             // Retrieve category data, but ONLY if current layout can use it, ('mcats' does not since it uses multiple ids)
             // ************************************************************************************************************
             $query = 'SELECT c.*,' . ' CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as slug' . ' FROM #__categories AS c' . ' WHERE c.id = ' . $this->_id . ' AND c.published = 1 AND c.extension=' . $this->_db->Quote(FLEXI_CAT_EXTENSION);
             $this->_db->setQuery($query);
             $_category = $this->_db->loadObject();
             // False if not found or unpublished
             if ($this->_db->getErrorNum()) {
                 JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($this->_db->getErrorMsg()), 'error');
             }
         } else {
             $_category = false;
             // A parent category is unpublished
         }
     } else {
         $_category = false;
         // No category id given, or category id is not applicable for current layout
     }
     // *******************************************************************************
     // Check category was found / is published, and throw an error. Note that an empty
     // layout means single category view, so raise an error if category id is missing
     // *******************************************************************************
     if (($this->_id || $cat_required) && !$_category) {
         $err_mssg = $err_type = false;
         if (!$_category) {
             $err_mssg = JText::sprintf('FLEXI_CONTENT_CATEGORY_NOT_FOUND_OR_NOT_PUBLISHED', $this->_id);
             $err_type = 404;
         }
         // Throw error -OR- return if errors suppresed
         if ($err_mssg) {
             if (!$raiseErrors) {
                 return false;
             }
             if (FLEXI_J16GE) {
                 throw new Exception($err_mssg, $err_type);
             } else {
                 JError::raiseError($err_type, $err_mssg);
             }
         }
     }
     // *********************************************************************
     // Some layouts optionally limit to a specific category, for these
     // create an empty category data object (if one was not created already)
     // *********************************************************************
     if ($this->_layout) {
         if ($this->_layout != 'mcats' && !empty($_category)) {
             $this->_category = $_category;
         } else {
             $this->_category = new stdClass();
             $this->_category->published = 1;
             $this->_category->id = $this->_id;
             // can be zero for layouts: author/myitems/favs/tags, etc
             $this->_category->title = '';
             $this->_category->description = '';
             $this->_category->slug = '';
             $this->_category->ids = $this->_ids;
             // mcats layout but it can be empty, to allow all categories
         }
     } else {
         $this->_category = $_category;
     }
     // *****************************************************
     // Check for proper layout configuration and throw error
     // *****************************************************
     if ($this->_layout) {
         $err_mssg = $err_type = false;
         if (!in_array($this->_layout, array('favs', 'tags', 'mcats', 'myitems', 'author'))) {
             $err_mssg = JText::sprintf('FLEXI_CONTENT_LIST_LAYOUT_IS_NOT_SUPPORTED', $this->_layout);
             $err_type = 404;
         } else {
             if ($this->_layout == 'author' && !$this->_authorid) {
                 $err_mssg = JText::_('FLEXI_CANNOT_LIST_CONTENT_AUTHORID_NOT_SET');
                 $err_type = 404;
             } else {
                 if ($this->_layout == 'tags' && !$this->_tagid) {
                     $err_mssg = JText::_('FLEXI_CANNOT_LIST_CONTENT_TAGID_NOT_SET');
                     $err_type = 404;
                 } else {
                     if ($this->_layout == 'myitems' && !$this->_authorid) {
                         $err_mssg = JText::_('FLEXI_LOGIN_TO_DISPLAY_YOUR_CONTENT');
                         $err_type = 403;
                         $login_redirect = true;
                     } else {
                         if ($this->_layout == 'favs' && !$this->_authorid) {
                             $err_mssg = JText::_('FLEXI_LOGIN_TO_DISPLAY_YOUR_CONTENT');
                             $err_type = 403;
                             $login_redirect = true;
                         }
                     }
                 }
             }
         }
         // Raise a notice and redirect
         if ($err_mssg) {
             if (!$raiseErrors) {
                 return false;
             }
             if (!empty($login_redirect)) {
                 // redirect unlogged user to login
                 $uri = JFactory::getURI();
                 $return = $uri->toString();
                 $com_users = FLEXI_J16GE ? 'com_users' : 'com_user';
                 $url = $cparams->get('login_page', 'index.php?option=' . $com_users . '&view=login');
                 $return = strtr(base64_encode($return), '+/=', '-_,');
                 $url .= '&return=' . $return;
                 // '&return='.base64_encode($return);
                 $url .= '&isfcurl=1';
                 JError::raiseWarning($err_type, $err_mssg);
                 $app->redirect($url);
             } else {
                 if (FLEXI_J16GE) {
                     throw new Exception($err_mssg, $err_type);
                 } else {
                     JError::raiseError($err_type, $err_mssg);
                 }
             }
         }
     }
     // *******************************************************
     // Set category parameters, these have already been loaded
     // *******************************************************
     $this->_category->parameters = $this->_params;
     // ******************************************************************
     // Check whether category access level allows access and throw errors
     // but skip checking Access if so requested via function parameter
     // ******************************************************************
     if (!$checkAccess) {
         return $this->_category;
     }
     // Check access level of category and of its parents
     $canread = true;
     if ($this->_id) {
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $allowed_levels = array_flip($aid_arr);
         $canread = isset($allowed_levels[$this->_category->access]);
         if ($canread) {
             foreach ($parents as $parent) {
                 if (!isset($allowed_levels[$parent->access])) {
                     $canread = false;
                     break;
                 }
             }
         }
     }
     // Handle unreadable category (issue 403 unauthorized error, redirecting unlogged users to login)
     if ($this->_id && !$canread) {
         if ($user->guest) {
             // Redirect to login
             $uri = JFactory::getURI();
             $return = $uri->toString();
             $com_users = FLEXI_J16GE ? 'com_users' : 'com_user';
             $url = $cparams->get('login_page', 'index.php?option=' . $com_users . '&view=login');
             $return = strtr(base64_encode($return), '+/=', '-_,');
             $url .= '&return=' . $return;
             // '&return='.base64_encode($return);
             $url .= '&isfcurl=1';
             JError::raiseWarning(403, JText::sprintf("FLEXI_LOGIN_TO_ACCESS", $url));
             $app->redirect($url);
         } else {
             if ($cparams->get('unauthorized_page', '')) {
                 $app->redirect($cparams->get('unauthorized_page'));
             } else {
                 JError::raiseWarning(403, JText::_("FLEXI_ALERTNOTAUTH_VIEW"));
                 $app->redirect('index.php');
             }
         }
     }
     return $this->_category;
 }
コード例 #15
0
ファイル: view.html.php プロジェクト: kosmosby/medicine-prof
 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();
     $template = $app->isSite() ? !FLEXI_J16GE ? 'khepri' : (FLEXI_J30GE ? 'hathor' : 'bluestork') : $app->getTemplate();
     JHTML::_('behavior.tooltip');
     JHTML::_('behavior.modal');
     //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->setTitle(JText::_('FLEXI_SELECTITEM'));
     $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/flexicontentbackend.css');
     if (FLEXI_J30GE) {
         $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j3x.css');
     } else {
         if (FLEXI_J16GE) {
             $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j25.css');
         } else {
             $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j15.css');
         }
     }
     $document->addStyleSheet(JURI::root() . 'administrator/templates/' . $template . (FLEXI_J16GE ? '/css/template.css' : '/css/general.css'));
     //Get data from the model
     if (FLEXI_J16GE) {
         $rows = $this->get('Items');
     } else {
         $rows = $this->get('Data');
     }
     // Parse configuration for every category
     foreach ($rows as $cat) {
         $cat->config = FLEXI_J16GE ? new JRegistry($cat->config) : new JParameter($cat->config);
     }
     $pagination = $this->get('Pagination');
     // *******************
     // 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 = ' 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 = ' 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 = ' 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', '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 = ' 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('ordering', $ordering);
     $this->assignRef('pagination', $pagination);
     parent::display($tpl);
 }
コード例 #16
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);
    }
コード例 #17
0
 function fetchElement($name, $value, &$node, $control_name)
 {
     static $function_added = false;
     if (FLEXI_J16GE) {
         $node =& $this->element;
         $attributes = get_object_vars($node->attributes());
         $attributes = $attributes['@attributes'];
     } else {
         $attributes =& $node->_attributes;
     }
     $values = FLEXI_J16GE ? $this->value : $value;
     if (!empty($attributes['joinwith'])) {
         $values = explode($attributes['joinwith'], $values);
     }
     if (empty($values)) {
         $values = array();
     } else {
         if (!is_array($values)) {
             $values = !FLEXI_J16GE ? array($values) : explode("|", $values);
         }
     }
     $fieldname = FLEXI_J16GE ? $this->name : $control_name . '[' . $name . ']';
     $element_id = FLEXI_J16GE ? $this->id : $control_name . $name;
     $ffname = @$attributes['name'];
     $published_only = (bool) @$attributes['published_only'];
     $parent_id = (int) @$attributes['parent_id'];
     $depth_limit = (int) @$attributes['depth_limit'];
     $tree = flexicontent_cats::getCategoriesTree($published_only, $parent_id, $depth_limit);
     $attribs = '';
     // Steps needed for multi-value select field element, e.g. code to maximize select field
     if (@$attributes['multiple'] == 'multiple' || @$attributes['multiple'] == 'true') {
         $attribs .= ' multiple="multiple" ';
         $attribs .= @$attributes['size'] ? ' size="' . $attributes['size'] . '" ' : ' size="8" ';
         $fieldname .= !FLEXI_J16GE ? "[]" : "";
         // NOTE: this added automatically in J2.5
         /*$onclick = ""
         			."${element_id} = document.getElementById(\"${element_id}\");"
         			."if (${element_id}.size<40) {"
         			."	${element_id}_oldsize = ${element_id}.size;"
         			."	${element_id}.size=40;"
         			."} else {"
         			."	${element_id}.size = ${element_id}_oldsize;"
         			."}"
         			."parent = ${element_id}.getParent(); upcnt=0;"
         			."while(upcnt<10 && !parent.hasClass(\"jpane-slider\")) {"
         			."	upcnt++; parent = parent.getParent();"
         			."}"
         			."if (parent.hasClass(\"jpane-slider\")) parent.setStyle(\"height\", \"auto\");"
         		;
         		$style = 'display:inline-block;'.(FLEXI_J16GE ? 'float:left; margin: 6px 0px 0px 18px;':'margin:0px 0px 6px 12px');
         		$maximize_link = "<a style='$style' href='javascript:;' onclick='$onclick' >Maximize/Minimize</a>";*/
     } else {
         //$maximize_link = '';
     }
     $maximize_link = '';
     $top = @$attributes['top'] ? $attributes['top'] : false;
     $classes = 'use_select2_lib ';
     $classes .= @$attributes['required'] && @$attributes['required'] != 'false' ? ' required' : '';
     $classes .= $node->attributes('validation_class') ? ' ' . $node->attributes('validation_class') : '';
     $classes = ' class="' . $classes . '"';
     $attribs .= $classes . ' style="float:left;" ';
     // Add onClick functions (e.g. joining values to a string)
     if (!empty($attributes['joinwith']) && !$function_added) {
         $function_added = true;
         $js = "\n\t\t\tfunction FLEXIClickCategory(obj, name) {\n\t\t\t\tvalues=new Array();\n\t\t\t\tfor(i=0,j=0;i<obj.options.length;i++) {\n\t\t\t\t\tif(obj.options[i].selected==true)\n\t\t\t\t\t\tvalues[j++] = obj.options[i].value;\n\t\t\t\t}\n\t\t\t\tvalue_list = values.join(',');\n\t\t\t\tdocument.getElementById('a_id_'+name).value = value_list;\n\t\t\t\t//alert(document.getElementById('a_id_'+name).value);\n\t\t\t}";
         $doc = JFactory::getDocument();
         $doc->addScriptDeclaration($js);
     }
     $html = '';
     if (!empty($attributes['joinwith'])) {
         $select_fieldname = '_' . $ffname . '_';
         $text_fieldname = str_replace('[]', '', $fieldname);
         $attribs .= ' onclick="FLEXIClickCategory(this,\'' . $ffname . '\');" ';
         $html .= "\n<input type=\"hidden\" id=\"a_id_{$ffname}\" name=\"{$text_fieldname}\" value=\"" . @$values[0] . "\" />";
     } else {
         $select_fieldname = $fieldname;
     }
     $html .= flexicontent_cats::buildcatselect($tree, $select_fieldname, $values, $top, $attribs, false, true, $actions_allowed = array('core.create'));
     return $html . $maximize_link;
 }
コード例 #18
0
 function _displayCopyMove($tpl = null, $cid = array(), $behaviour = 'copy/move')
 {
     global $globalcats;
     $app = JFactory::getApplication();
     // Initialise variables
     $user = JFactory::getUser();
     $document = JFactory::getDocument();
     // 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 to document
     JHTML::_('behavior.tooltip');
     flexicontent_html::loadFramework('select2');
     $document->addScriptVersion(JURI::base(true) . '/components/com_flexicontent/assets/js/copymove.js', FLEXI_VERSION);
     // 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);
     // Create document/toolbar titles
     if ($behaviour == 'translate') {
         $doc_title = JText::_('FLEXI_TRANSLATE_ITEM');
     } else {
         $doc_title = JText::_('FLEXI_BATCH');
     }
     $site_title = $document->getTitle();
     JToolBarHelper::title($doc_title, 'itemadd');
     $document->setTitle($doc_title . ' - ' . $site_title);
     // Create the toolbar
     JToolBarHelper::save('items.copymove');
     JToolBarHelper::cancel('items.cancel');
     //Get data from the model
     $rows = $this->get('Data');
     $itemCats = $this->get('ItemCats');
     $categories = $globalcats;
     // build the main category select list
     $lists['maincat'] = flexicontent_cats::buildcatselect($categories, 'maincat', '', JText::_('FLEXI_DO_NOT_CHANGE'), 'class="use_select2_lib" size="10"', false, false);
     // build the secondary categories select list
     $lists['seccats'] = flexicontent_cats::buildcatselect($categories, 'seccats[]', '', 0, 'class="use_select2_lib" multiple="multiple" size="10"', false, false);
     // build language selection
     $lists['language'] = flexicontent_html::buildlanguageslist('language', '', '', $type = $behaviour != 'translate' ? JText::_('FLEXI_NOCHANGE_LANGUAGE') : 7, $allowed_langs = null, $published_only = true, $disable_langs = null, $add_all = true, array('required' => 1));
     // build state selection
     $selected_state = 0;
     // use unpublished as default state of new items, (instead of '' which means do not change)
     $lists['state'] = flexicontent_html::buildstateslist('state', 'class="use_select2_lib"', $selected_state);
     // build types selection
     $types = flexicontent_html::getTypesList();
     $lists['type_id'] = flexicontent_html::buildtypesselect($types, 'type_id', '', JText::_('FLEXI_DO_NOT_CHANGE'), 'class="use_select2_lib" size="1" style="vertical-align:top;"', 'type_id');
     // build access level filter
     $levels = JHtml::_('access.assetgroups');
     array_unshift($levels, JHtml::_('select.option', '', 'FLEXI_DO_NOT_CHANGE'));
     $fieldname = $elementid = 'access';
     $attribs = 'class="use_select2_lib"';
     $lists['access'] = JHTML::_('select.genericlist', $levels, $fieldname, $attribs, 'value', 'text', $value = '', $elementid, $translate = true);
     //assign data to template
     $this->assignRef('lists', $lists);
     $this->assignRef('rows', $rows);
     $this->assignRef('itemCats', $itemCats);
     $this->assignRef('cid', $cid);
     $this->assignRef('user', $user);
     $this->assignRef('behaviour', $behaviour);
     parent::display($tpl);
 }
コード例 #19
0
ファイル: view.html.php プロジェクト: kosmosby/medicine-prof
 function display($tpl = null)
 {
     $mainframe = JFactory::getApplication();
     //initialise variables
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     $document = JFactory::getDocument();
     $option = JRequest::getCmd('option');
     $context = 'com_flexicontent';
     $task = JRequest::getVar('task', '');
     $cid = JRequest::getVar('cid', array());
     $cparams = JComponentHelper::getParams('com_flexicontent');
     $this->setLayout('import');
     //initialise variables
     $user = JFactory::getUser();
     $document = JFactory::getDocument();
     $context = 'com_flexicontent';
     $has_zlib = version_compare(PHP_VERSION, '5.4.0', '>=');
     FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
     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');
         }
     }
     // Get filter vars
     $filter_order = $mainframe->getUserStateFromRequest($context . '.import.filter_order', 'filter_order', '', 'cmd');
     $filter_order_Dir = $mainframe->getUserStateFromRequest($context . '.import.filter_order_Dir', 'filter_order_Dir', '', 'word');
     // Get session information
     $session = JFactory::getSession();
     $conf = $session->get('csvimport_config', "", 'flexicontent');
     $conf = unserialize($conf ? $has_zlib ? zlib_decode(base64_decode($conf)) : base64_decode($conf) : "");
     $lineno = $session->get('csvimport_lineno', 999999, 'flexicontent');
     $session->set('csvimport_parse_log', null, 'flexicontent');
     // Get User's Global Permissions
     $perms = FlexicontentHelperPerm::getPerm();
     // Create Submenu (and also check access to current view)
     FLEXISubmenu('CanImport');
     // Create document/toolbar titles
     $doc_title = JText::_('FLEXI_IMPORT');
     $site_title = $document->getTitle();
     JToolBarHelper::title($doc_title, 'import');
     $document->setTitle($doc_title . ' - ' . $site_title);
     // Create the toolbar
     $toolbar = JToolBar::getInstance('toolbar');
     if (!empty($conf)) {
         if ($task != 'processcsv') {
             $ctrl_task = FLEXI_J16GE ? 'import.processcsv' : 'processcsv';
             $import_btn_title = empty($lineno) ? 'FLEXI_IMPORT_START_TASK' : 'FLEXI_IMPORT_CONTINUE_TASK';
             JToolBarHelper::custom($ctrl_task, 'save.png', 'save.png', $import_btn_title, $list_check = false);
         }
         $ctrl_task = FLEXI_J16GE ? 'import.clearcsv' : 'clearcsv';
         JToolBarHelper::custom($ctrl_task, 'cancel.png', 'cancel.png', 'FLEXI_IMPORT_CLEAR_TASK', $list_check = false);
     } else {
         $ctrl_task = FLEXI_J16GE ? 'import.initcsv' : 'initcsv';
         JToolBarHelper::custom($ctrl_task, 'import.png', 'import.png', 'FLEXI_IMPORT_PREPARE_TASK', $list_check = false);
         $ctrl_task = FLEXI_J16GE ? 'import.testcsv' : 'testcsv';
         JToolBarHelper::custom($ctrl_task, 'test.png', 'test.png', 'FLEXI_IMPORT_TEST_FILE_FORMAT', $list_check = false);
     }
     //JToolBarHelper::Back();
     if ($perms->CanConfig) {
         JToolBarHelper::divider();
         JToolBarHelper::spacer();
         $session = JFactory::getSession();
         $fc_screen_width = (int) $session->get('fc_screen_width', 0, 'flexicontent');
         $_width = $fc_screen_width && $fc_screen_width - 84 > 940 ? $fc_screen_width - 84 > 1400 ? 1400 : $fc_screen_width - 84 : 940;
         $fc_screen_height = (int) $session->get('fc_screen_height', 0, 'flexicontent');
         $_height = $fc_screen_height && $fc_screen_height - 128 > 550 ? $fc_screen_height - 128 > 1000 ? 1000 : $fc_screen_height - 128 : 550;
         JToolBarHelper::preferences('com_flexicontent', $_height, $_width, 'Configuration');
     }
     if (!empty($conf) && $task == 'processcsv') {
         $this->assignRef('conf', $conf);
         parent::display('process');
         return;
     }
     // Get types
     $query = 'SELECT id, name' . ' FROM #__flexicontent_types' . ' WHERE published = 1' . ' ORDER BY name ASC';
     $db->setQuery($query);
     $types = $db->loadObjectList('id');
     // Get Languages
     $languages = FLEXI_FISH || FLEXI_J16GE ? FLEXIUtilities::getLanguages('code') : array();
     // Get categories
     global $globalcats;
     $categories = $globalcats;
     if (!empty($conf)) {
         $this->assignRef('conf', $conf);
         $this->assignRef('cparams', $cparams);
         $this->assignRef('types', $types);
         $this->assignRef('languages', $languages);
         $this->assignRef('categories', $globalcats);
         parent::display('list');
         return;
     }
     // ******************
     // Create form fields
     // ******************
     $lists['type_id'] = flexicontent_html::buildtypesselect($types, 'type_id', '', true, 'class="fcfield_selectval" size="1"', 'type_id');
     $actions_allowed = array('core.create');
     // Creating categorories tree for item assignment, we use the 'create' privelege
     // build the secondary categories select list
     $class = "fcfield_selectmulval";
     $attribs = 'multiple="multiple" size="10" class="' . $class . '"';
     $fieldname = FLEXI_J16GE ? 'seccats[]' : 'seccats[]';
     $lists['seccats'] = flexicontent_cats::buildcatselect($categories, $fieldname, '', false, $attribs, false, true, $actions_allowed, $require_all = true);
     // build the main category select list
     $attribs = 'class="fcfield_selectval"';
     $fieldname = FLEXI_J16GE ? 'maincat' : 'maincat';
     $lists['maincat'] = flexicontent_cats::buildcatselect($categories, $fieldname, '', 2, $attribs, false, true, $actions_allowed);
     /*
     	// build the main category select list
     	$lists['maincat'] = flexicontent_cats::buildcatselect($categories, 'maincat', '', 0, 'class="inputbox" size="10"', false, false);
     	// build the secondary categories select list
     	$lists['seccats'] = flexicontent_cats::buildcatselect($categories, 'seccats[]', '', 0, 'class="inputbox" multiple="multiple" size="10"', false, false);
     */
     //build languages list
     // 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);
     }
     $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
     $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
     // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
     // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
     if (FLEXI_FISH || FLEXI_J16GE) {
         $default_lang = $cparams->get('import_lang', '*');
         $lists['languages'] = flexicontent_html::buildlanguageslist('language', '', $default_lang, 6, $allowed_langs, $published_only = true);
     } else {
         $default_lang = flexicontent_html::getSiteDefaultLang();
         $_langs[] = JHTML::_('select.option', $default_lang, JText::_('Default') . ' (' . flexicontent_html::getSiteDefaultLang() . ')');
         $lists['languages'] = JHTML::_('select.radiolist', $_langs, 'language', $class = '', 'value', 'text', $default_lang);
     }
     $default_state = $cparams->get('import_state', 1);
     $lists['states'] = flexicontent_html::buildstateslist('state', '', $default_state, 2);
     // Ignore warnings because component may not be installed
     $warnHandlers = JERROR::getErrorHandling(E_WARNING);
     JERROR::setErrorHandling(E_WARNING, 'ignore');
     if (FLEXI_J30GE) {
         // J3.0+ adds an warning about component not installed, commented out ... till time ...
         $fleximport_comp_enabled = false;
         //JComponentHelper::isEnabled('com_fleximport');
     } else {
         $fleximport_comp = JComponentHelper::getComponent('com_fleximport', true);
         $fleximport_comp_enabled = $fleximport_comp && $fleximport_comp->enabled;
     }
     // Reset the warning handler(s)
     foreach ($warnHandlers as $mode) {
         JERROR::setErrorHandling(E_WARNING, $mode);
     }
     if ($fleximport_comp_enabled) {
         $fleximport = JText::sprintf('FLEXI_FLEXIMPORT_INSTALLED', JText::_('FLEXI_FLEXIMPORT_INFOS'));
     } else {
         $fleximport = JText::sprintf('FLEXI_FLEXIMPORT_NOT_INSTALLED', JText::_('FLEXI_FLEXIMPORT_INFOS'));
     }
     // ********************************************************************************
     // Get field names (from the header line (row 0), and remove it form the data array
     // ********************************************************************************
     $file_field_types_list = '"image","file"';
     $q = 'SELECT id, name, label, field_type FROM #__flexicontent_fields AS fi' . ' WHERE fi.field_type IN (' . $file_field_types_list . ')';
     $db->setQuery($q);
     $file_fields = $db->loadObjectList('name');
     //assign data to template
     $this->assignRef('lists', $lists);
     $this->assignRef('cid', $cid);
     $this->assignRef('user', $user);
     $this->assignRef('fleximport', $fleximport);
     $this->assignRef('cparams', $cparams);
     $this->assignRef('file_fields', $file_fields);
     parent::display($tpl);
 }
コード例 #20
0
 function onDisplayFilter(&$filter, $value = '', $formName = 'adminForm')
 {
     if (!in_array($filter->field_type, self::$field_types)) {
         return;
     }
     // ** some parameter shortcuts
     $label_filter = $filter->parameters->get('display_label_filter', 0);
     if ($label_filter == 2) {
         $text_select = $filter->label;
     } else {
         $text_select = JText::_('FLEXI_ALL');
     }
     $filter->html = '';
     if (!$filter->parameters->get('range', 0)) {
         // *** Retrieve values
         // *** Limit values, show only allowed values according to category configuration parameter 'limit_filter_values'
         $force = JRequest::getVar('view') == 'search' ? 'all' : 'default';
         $results = flexicontent_cats::getFilterValues($filter, $force);
         // *** Create the select form field used for filtering
         $options = array();
         $options[] = JHTML::_('select.option', '', '-' . $text_select . '-');
         foreach ($results as $result) {
             if (!strlen($result->value)) {
                 continue;
             }
             $options[] = JHTML::_('select.option', $result->value, JText::_($result->text));
         }
         if ($label_filter == 1) {
             $filter->html .= $filter->label . ': ';
         }
         $filter->html .= JHTML::_('select.genericlist', $options, 'filter_' . $filter->id, ' class="fc_field_filter" onchange="document.getElementById(\'' . $formName . '\').submit();"', 'value', 'text', $value);
     } else {
         //print_r($value);
         $size = (int) ($filter->parameters->get('size', 30) / 2);
         $filter->html .= '<input name="filter_' . $filter->id . '[1]" class="fc_field_filter" type="text" size="' . $size . '" value="' . @$value[1] . '" /> - ';
         $filter->html .= '<input name="filter_' . $filter->id . '[2]" class="fc_field_filter" type="text" size="' . $size . '" value="' . @$value[2] . '" />' . "\n";
     }
 }
コード例 #21
0
 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);
 }
コード例 #22
0
 /**
  * Creates the (menu-overridden) categories/main category form fields for NEW item submission form
  *
  * @since 1.0
  */
 function _getMenuCats(&$item, &$perms)
 {
     global $globalcats;
     $params =& $item->parameters;
     $isnew = !$item->id;
     // Get menu parameters related to category overriding
     $cid = $params->get("cid");
     // Overriden categories list
     $maincatid = $params->get("maincatid");
     // Default main category out of the overriden categories
     $postcats = $params->get("postcats", 0);
     // Behavior of override, submit to ONE Or MULTIPLE or to FIXED categories
     $override = $params->get("overridecatperms", 1);
     // Default to 1 for compatibilty with previous-version saved menu items
     // Check if item is new and overridden cats defined and cat overriding enabled
     if (!$isnew || empty($cid) || !$override) {
         return false;
     }
     // DO NOT override user's permission for submitting to multiple categories
     if (!$perms['multicat'] && $postcats == 2) {
         $postcats = 1;
     }
     // OVERRIDE item categories, using the ones specified specified by the MENU item, instead of categories that user has CREATE (=add) Permission
     $cids = !is_array($cid) ? explode(",", $cid) : $cid;
     // Add default main category to the overridden category list if not already there
     if ($maincatid && !in_array($maincatid, $cids)) {
         $cids[] = $maincatid;
     }
     // Create 2 arrays with category info used for creating the of select list of (a) multi-categories select field (b) main category select field
     $categories = array();
     $options = array();
     foreach ($cids as $catid) {
         $categories[] = $globalcats[$catid];
     }
     // Field names for (a) multi-categories field and (b) main category field
     $cid_form_fieldname = 'jform[cid][]';
     $catid_form_fieldname = 'jform[catid]';
     $catid_form_tagid = 'jform_catid';
     // Create form field HTML for the menu-overridden categories fields
     switch ($postcats) {
         case 0:
             // no categories selection, submit to a MENU SPECIFIED categories list
         // no categories selection, submit to a MENU SPECIFIED categories list
         default:
             // Do not create multi-category field if only one category was selected
             if (count($cids) > 1) {
                 foreach ($cids as $catid) {
                     $cat_titles[$catid] = $globalcats[$catid]->title;
                     $mo_cats .= '<input type="hidden" name="' . $cid_form_fieldname . '" value="' . $catid . '" />';
                 }
                 $mo_cats .= implode(', ', $cat_titles);
             } else {
                 $mo_cats = false;
             }
             $mo_maincat = $globalcats[$maincatid]->title;
             $mo_maincat .= '<input type="hidden" name="' . $catid_form_fieldname . '" value="' . $maincatid . '" />';
             $mo_cancid = false;
             break;
         case 1:
             // submit to a single category, selecting from a MENU SPECIFIED categories subset
             $mo_cats = false;
             $mo_maincat = flexicontent_cats::buildcatselect($categories, $catid_form_fieldname, $maincatid, 2, ' class="scat use_select2_lib required" ', $check_published = true, $check_perms = false);
             $mo_cancid = false;
             break;
         case 2:
             // submit to multiple categories, selecting from a MENU SPECIFIED categories subset
             $attribs = 'class="validate use_select2_lib select2_list_selected" multiple="multiple" size="8"';
             $mo_cats = flexicontent_cats::buildcatselect($categories, $cid_form_fieldname, array(), false, $attribs, $check_published = true, $check_perms = false);
             $mo_maincat = flexicontent_cats::buildcatselect($categories, $catid_form_fieldname, $maincatid, 2, ' class="scat use_select2_lib validate-catid" ', $check_published = true, $check_perms = false);
             $mo_cancid = true;
             break;
     }
     $menuCats = new stdClass();
     $menuCats->cid = $mo_cats;
     $menuCats->catid = $mo_maincat;
     $menuCats->cancid = $mo_cancid;
     return $menuCats;
 }
コード例 #23
0
 function display($tpl = null)
 {
     global $globalcats;
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     $option = JRequest::getVar('option');
     $view = JRequest::getVar('view');
     $document = JFactory::getDocument();
     // Get model
     $model = $this->getModel();
     //JHTML::_('behavior.tooltip');
     JHTML::_('behavior.modal');
     $assocs_id = JRequest::getInt('assocs_id', 0);
     $language = !$assocs_id ? JRequest::getCmd('language') : $app->getUserStateFromRequest($option . '.' . $view . '.language', 'language', '', 'string');
     $created_by = !$assocs_id ? JRequest::getCmd('created_by') : $app->getUserStateFromRequest($option . '.' . $view . '.created_by', 'created_by', 0, 'int');
     if ($assocs_id) {
         $assocanytrans = $user->authorise('flexicontent.assocanytrans', 'com_flexicontent');
         if (!$assocanytrans && !$created_by) {
             $created_by = $user->id;
         }
     }
     // get filter values
     $filter_order = $app->getUserStateFromRequest($option . '.' . $view . '.filter_order', 'filter_order', 'c.lft', 'cmd');
     $filter_order_Dir = $app->getUserStateFromRequest($option . '.' . $view . '.filter_order_Dir', 'filter_order_Dir', '', 'cmd');
     $filter_state = $app->getUserStateFromRequest($option . '.' . $view . '.filter_state', 'filter_state', '', 'cmd');
     $filter_cats = $app->getUserStateFromRequest($option . '.' . $view . '.filter_cats', 'filter_cats', 0, 'int');
     $filter_level = $app->getUserStateFromRequest($option . '.' . $view . '.filter_level', 'filter_level', 0, 'int');
     $filter_access = $app->getUserStateFromRequest($option . '.' . $view . '.filter_access', 'filter_access', '', 'string');
     $filter_lang = $app->getUserStateFromRequest($option . '.' . $view . '.filter_lang', 'filter_lang', '', 'cmd');
     $filter_author = $app->getUserStateFromRequest($option . '.' . $view . '.filter_author', 'filter_author', '', 'cmd');
     $search = $app->getUserStateFromRequest($option . '.' . $view . '.search', 'search', '', 'string');
     $search = $db->escape(trim(JString::strtolower($search)));
     // Prepare the document: set title, add css files, etc
     $document->setTitle(JText::_('FLEXI_SELECTITEM'));
     if ($app->isSite()) {
         $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontent.css', FLEXI_VHASH);
     } else {
         $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VHASH);
     }
     flexicontent_html::loadFramework('select2');
     $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VHASH);
     // Include backend CSS template CSS file , access to backend folder may not be allowed but ...
     //$template = $app->isSite() ? (!FLEXI_J16GE ? 'khepri' : (FLEXI_J30GE ? 'hathor' : 'bluestork')) : $app->getTemplate();
     //$document->addStyleSheet(JURI::base(true).'/templates/'.$template.(FLEXI_J16GE ? '/css/template.css': '/css/general.css'));
     //Get data from the model
     $rows = $this->get('Items');
     $authors = $this->get('Authorslist');
     $pagination = $this->get('Pagination');
     // Ordering active FLAG
     $ordering = $filter_order == 'c.lft';
     // Parse configuration for every category
     foreach ($rows as $cat) {
         $cat->config = new JRegistry($cat->config);
     }
     // *******************
     // Create Form Filters
     // *******************
     // filter search word
     $lists['search'] = $search;
     // table ordering
     $lists['order_Dir'] = $filter_order_Dir;
     $lists['order'] = $filter_order;
     // build the categories select list
     $categories = $globalcats;
     $lists['filter_cats'] = '<label class="label">' . JText::_('FLEXI_CATEGORY') . '</label>' . flexicontent_cats::buildcatselect($categories, 'filter_cats', $filter_cats, '-', 'class="use_select2_lib fcfilter_be" size="1" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', $check_published = true, $check_perms = false);
     // filter depth level
     $depths = array();
     $depths[] = JHtml::_('select.option', '', '-');
     for ($i = 1; $i <= 10; $i++) {
         $depths[] = JHtml::_('select.option', $i, $i);
     }
     $fieldname = $elementid = 'filter_level';
     $attribs = ' class="use_select2_lib fcfilter_be" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" ';
     $lists['filter_level'] = '<label class="label">' . JText::_('FLEXI_MAX_DEPTH') . '</label>' . JHTML::_('select.genericlist', $depths, $fieldname, $attribs, 'value', 'text', $filter_level, $elementid, $translate = true);
     // build author select list
     $lists['filter_author'] = '<label class="label">' . JText::_('FLEXI_AUTHOR') . '</label>' . ($assocs_id && $created_by ? '<span class="badge badge-info">' . JFactory::getUser($created_by)->name . '</span>' : flexicontent_html::buildauthorsselect($authors, 'filter_author', $filter_author, '-', 'class="use_select2_lib fcfilter_be" size="3" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"'));
     // build publication state filter
     $states = JHtml::_('jgrid.publishedOptions');
     array_unshift($states, JHtml::_('select.option', '', '-'));
     $fieldname = $elementid = 'filter_state';
     $attribs = ' class="use_select2_lib fcfilter_be" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" ';
     $lists['filter_state'] = '<label class="label">' . JText::_('FLEXI_STATE') . '</label>' . JHTML::_('select.genericlist', $states, $fieldname, $attribs, 'value', 'text', $filter_state, $elementid, $translate = true);
     // build access level filter
     $levels = JHtml::_('access.assetgroups');
     array_unshift($levels, JHtml::_('select.option', '', '-'));
     $fieldname = $elementid = 'filter_access';
     $attribs = ' class="use_select2_lib fcfilter_be" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()" ';
     $lists['filter_access'] = '<label class="label">' . JText::_('FLEXI_ACCESS') . '</label>' . JHTML::_('select.genericlist', $levels, $fieldname, $attribs, 'value', 'text', $filter_access, $elementid, $translate = true);
     // build language filter
     $lists['filter_lang'] = '<label class="label">' . JText::_('FLEXI_LANGUAGE') . '</label>' . ($assocs_id && $language ? '<span class="badge badge-info">' . $language . '</span>' : flexicontent_html::buildlanguageslist('filter_lang', 'class="use_select2_lib fcfilter_be" onchange="document.adminForm.limitstart.value=0; Joomla.submitform()"', $filter_lang, '-'));
     // assign data to template
     $this->assignRef('assocs_id', $assocs_id);
     $this->assignRef('lists', $lists);
     $this->assignRef('rows', $rows);
     $this->assignRef('ordering', $ordering);
     $this->assignRef('pagination', $pagination);
     parent::display($tpl);
 }
コード例 #24
0
ファイル: view.html.php プロジェクト: kosmosby/medicine-prof
 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);
 }
コード例 #25
0
 /**
  * Creates the page's display
  *
  * @since 1.0
  */
 function display($tpl = null)
 {
     // Get Non-routing Categories, and Category Tree
     global $globalnoroute, $globalcats;
     if (!is_array($globalnoroute)) {
         $globalnoroute = array();
     }
     //initialize variables
     $dispatcher = JDispatcher::getInstance();
     $app = JFactory::getApplication();
     $session = JFactory::getSession();
     $option = JRequest::getVar('option');
     $document = JFactory::getDocument();
     $menus = $app->getMenu();
     $menu = $menus->getActive();
     $uri = JFactory::getURI();
     $user = JFactory::getUser();
     $aid = JAccess::getAuthorisedViewLevels($user->id);
     // Get model
     $model = $this->getModel();
     // Get category and set category parameters as VIEW's parameters (category parameters are merged with component/page/author parameters already)
     $category = $this->get('Category');
     $params = $category->parameters;
     if ($category->id) {
         $meta_params = new JRegistry($category->metadata);
     }
     // Get various data from the model
     $categories = $this->get('Childs');
     // this will also count sub-category items is if  'show_itemcount'  is enabled
     $peercats = $this->get('Peers');
     // this will also count sub-category items is if  'show_subcatcount_peercat'  is enabled
     $items = $this->get('Data');
     $total = $this->get('Total');
     $filters = $this->get('Filters');
     if ($params->get('show_comments_count', 0)) {
         $comments = $this->get('CommentsInfo');
     } else {
         $comments = null;
     }
     $alpha = $params->get('show_alpha', 1) ? $this->get('Alphaindex') : array();
     // This is somwhat expensive so calculate it only if required
     // Request variables, WARNING, must be loaded after retrieving items, because limitstart may have been modified
     $limitstart = JRequest::getInt('limitstart');
     $format = JRequest::getCmd('format', null);
     // ********************************
     // Load needed JS libs & CSS styles
     // ********************************
     FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
     flexicontent_html::loadFramework('jQuery');
     flexicontent_html::loadFramework('flexi_tmpl_common');
     // ************************
     // CATEGORY LAYOUT handling
     // ************************
     // (a) Decide to use mobile or normal category template layout
     $useMobile = $params->get('use_mobile_layouts', 0);
     if ($useMobile) {
         $force_desktop_layout = $params->get('force_desktop_layout', 0);
         $mobileDetector = flexicontent_html::getMobileDetector();
         $isMobile = $mobileDetector->isMobile();
         $isTablet = $mobileDetector->isTablet();
         $useMobile = $force_desktop_layout ? $isMobile && !$isTablet : $isMobile;
     }
     $_clayout = $useMobile ? 'clayout_mobile' : 'clayout';
     // (b) Get from category parameters, allowing URL override
     $clayout = JRequest::getCmd($_clayout, false);
     if (!$clayout) {
         $desktop_clayout = $params->get('clayout', 'blog');
         $clayout = !$useMobile ? $desktop_clayout : $params->get('clayout_mobile', $desktop_clayout);
     }
     // (c) Get cached template data
     $themes = flexicontent_tmpl::getTemplates($lang_files = array($clayout));
     // (d) Verify the category layout exists
     if (!isset($themes->category->{$clayout})) {
         $fixed_clayout = 'blog';
         $app->enqueueMessage("<small>Current Category Layout Template is '{$clayout}' does not exist<br>- Please correct this in the URL or in Content Type configuration.<br>- Using Template Layout: '{$fixed_clayout}'</small>", 'notice');
         $clayout = $fixed_clayout;
         FLEXIUtilities::loadTemplateLanguageFile($clayout);
         // Manually load Template-Specific language file of back fall clayout
     }
     // (e) finally set the template name back into the category's parameters
     $params->set('clayout', $clayout);
     // Get URL variables
     $layout_vars = flexicontent_html::getCatViewLayoutVars($model);
     $layout = $layout_vars['layout'];
     $authorid = $layout_vars['authorid'];
     $tagid = $layout_vars['tagid'];
     $cids = $layout_vars['cids'];
     $cid = $layout_vars['cid'];
     // Get Tag data if current layout is 'tags'
     if ($tagid) {
         $tag = $this->get('Tag');
     }
     $authordescr_item = false;
     if ($authorid && $params->get('authordescr_itemid') && $format != 'feed') {
         $authordescr_itemid = $params->get('authordescr_itemid');
     }
     // Bind Fields
     if ($format != 'feed') {
         $items = FlexicontentFields::getFields($items, 'category', $params, $aid);
     }
     //Set layout
     $this->setLayout('category');
     $limit = $app->getUserStateFromRequest('com_flexicontent' . $category->id . '.category.limit', 'limit', $params->def('limit', 0), 'int');
     // Get category titles needed by pathway, this will allow Falang to translate them
     $catshelper = new flexicontent_cats($cid);
     $parents = $catshelper->getParentlist($all_cols = false);
     //echo "<pre>".print_r($parents,true)."</pre>";
     /*$parents = array();
     		if ( $cid && isset($globalcats[$cid]->ancestorsarray) ) {
     			$parent_ids = $globalcats[$cid]->ancestorsarray;
     			foreach ($parent_ids as $parent_id) $parents[] = $globalcats[$parent_id];
     		}*/
     $rootcat = (int) $params->get('rootcat');
     if ($rootcat) {
         $root_parents = $globalcats[$rootcat]->ancestorsarray;
     }
     // **********************************************************
     // Calculate a (browser window) page title and a page heading
     // **********************************************************
     // Verify menu item points to current FLEXIcontent object
     if ($menu) {
         $view_ok = 'category' == @$menu->query['view'];
         $cid_ok = $cid == (int) @$menu->query['cid'];
         $layout_ok = $layout == @$menu->query['layout'];
         // null is equal to empty string
         $authorid_ok = $authorid == (int) @$menu->query['authorid'];
         // null is equal to zero
         $tagid_ok = $tagid == (int) @$menu->query['tagid'];
         // null is equal to zero
         $menu_matches = $view_ok && $cid_ok && $layout_ok && $authorid_ok && $tagid_ok;
         //$menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);  // Get active menu item parameters
     } else {
         $menu_matches = false;
     }
     // MENU ITEM matched, use its page heading (but use menu title if the former is not set)
     if ($menu_matches) {
         $default_heading = FLEXI_J16GE ? $menu->title : $menu->name;
         // Cross set (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->def('page_heading', $params->get('page_title', $default_heading));
         $params->def('page_title', $params->get('page_heading', $default_heading));
         $params->def('show_page_heading', $params->get('show_page_title', 0));
         $params->def('show_page_title', $params->get('show_page_heading', 0));
     } else {
         // Clear some menu parameters
         //$params->set('pageclass_sfx',	'');  // CSS class SUFFIX is behavior, so do not clear it ?
         // Calculate default page heading (=called page title in J1.5), which in turn will be document title below !! ...
         switch ($layout) {
             case '':
                 $default_heading = $category->title;
                 break;
             case 'myitems':
                 $default_heading = JText::_('FLEXICONTENT_MYITEMS');
                 break;
             case 'author':
                 $default_heading = JText::_('FLEXICONTENT_AUTHOR') . ': ' . JFactory::getUser($authorid)->get('name');
                 break;
             case 'tags':
                 $default_heading = JText::_('FLEXI_ITEMS_WITH_TAG') . ': ' . $tag->name;
                 break;
             case 'favs':
                 $default_heading = JText::_('FLEXI_YOUR_FAVOURED_ITEMS');
                 break;
             default:
                 $default_heading = JText::_('FLEXICONTENT_CATEGORY');
         }
         if ($layout && $cid) {
             // Non-single category listings, limited to a specific category
             $default_heading .= ', ' . JText::_('FLEXI_IN_CATEGORY') . ': ' . $category->title;
         }
         // Decide to show page heading (=J1.5 page title) only if a custom layout is used (=not a single category layout)
         $show_default_heading = $layout ? 1 : 0;
         // Set both (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->set('page_title', $default_heading);
         $params->set('page_heading', $default_heading);
         $params->set('show_page_heading', $show_default_heading);
         $params->set('show_page_title', $show_default_heading);
     }
     // Prevent showing the page heading if (a) IT IS same as category title and (b) category title is already configured to be shown
     if ($params->get('show_cat_title', 1)) {
         if ($params->get('page_heading') == $category->title) {
             $params->set('show_page_heading', 0);
         }
         if ($params->get('page_title') == $category->title) {
             $params->set('show_page_title', 0);
         }
     }
     // ************************************************************
     // Create the document title, by from page title and other data
     // ************************************************************
     // Use the page heading as document title, (already calculated above via 'appropriate' logic ...)
     // or the overriden custom <title> ... set via parameter
     $doc_title = empty($meta_params) ? $params->get('page_title') : $meta_params->get('page_title', $params->get('page_title'));
     // Check and prepend or append site name to page title
     if ($doc_title != $app->getCfg('sitename')) {
         if ($app->getCfg('sitename_pagetitles', 0) == 1) {
             $doc_title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $doc_title);
         } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
             $doc_title = JText::sprintf('JPAGETITLE', $doc_title, $app->getCfg('sitename'));
         }
     }
     // Finally, set document title
     $document->setTitle($doc_title);
     // ************************
     // Set document's META tags
     // ************************
     // Workaround for Joomla not setting the default value for 'robots', so component must do it
     $app_params = $app->getParams();
     if ($_mp = $app_params->get('robots')) {
         $document->setMetadata('robots', $_mp);
     }
     if ($category->id) {
         // possibly not set for author items OR my items
         if ($category->metadesc) {
             $document->setDescription($category->metadesc);
         }
         if ($category->metakey) {
             $document->setMetadata('keywords', $category->metakey);
         }
         // meta_params are always set if J1.6+ and category id is set
         if ($meta_params->get('robots')) {
             $document->setMetadata('robots', $meta_params->get('robots'));
         }
         // ?? Deprecated <title> tag is used instead by search engines
         if ($app->getCfg('MetaTitle') == '1') {
             $meta_title = $meta_params->get('page_title') ? $meta_params->get('page_title') : $category->title;
             $document->setMetaData('title', $meta_title);
         }
         if ($app->getCfg('MetaAuthor') == '1') {
             if ($meta_params->get('author')) {
                 $meta_author = $meta_params->get('author');
             } else {
                 $table = JUser::getTable();
                 $meta_author = $table->load($category->created_user_id) ? $table->name : '';
             }
             $document->setMetaData('author', $meta_author);
         }
     }
     // Overwrite with menu META data if menu matched
     if ($menu_matches) {
         if ($_mp = $menu->params->get('menu-meta_description')) {
             $document->setDescription($_mp);
         }
         if ($_mp = $menu->params->get('menu-meta_keywords')) {
             $document->setMetadata('keywords', $_mp);
         }
         if ($_mp = $menu->params->get('robots')) {
             $document->setMetadata('robots', $_mp);
         }
         if ($_mp = $menu->params->get('secure')) {
             $document->setMetadata('secure', $_mp);
         }
     }
     // *********************************************************************
     // Create category link, but also consider current 'layout', and use the
     // layout specific variables so that filtering form will work properly
     // *********************************************************************
     $non_sef_link = null;
     $category_link = flexicontent_html::createCatLink($category->slug, $non_sef_link, $model);
     // ************************************
     // Add rel canonical html head link tag (TODO: improve multi-page handing)
     // ************************************
     $port = $uri->getPort();
     $base = $uri->getScheme() . '://' . $uri->getHost() . ($port ? ':' . $port : '');
     $start = JRequest::getInt('start', '');
     $start = $start ? "&start=" . $start : "";
     // ********************************************************************************************
     // Create pathway, if automatic pathways is enabled, then path will be cleared before populated
     // ********************************************************************************************
     $pathway = $app->getPathWay();
     // Clear pathway, if automatic pathways are enabled
     if ($params->get('automatic_pathways', 0)) {
         $pathway_arr = $pathway->getPathway();
         $pathway->setPathway(array());
         //$pathway->set('_count', 0);  // not needed ??
         $item_depth = 0;
         // menu item depth is now irrelevant ???, ignore it
     } else {
         $item_depth = $params->get('item_depth', 0);
     }
     // Respect menu item depth, defined in menu item
     $p = $item_depth;
     while ($p < count($parents)) {
         // Do not add the directory root category or its parents (this when coming from a directory view)
         if (!empty($root_parents) && in_array($parents[$p]->id, $root_parents)) {
             $p++;
             continue;
         }
         // Do not add to pathway unroutable categories
         if (in_array($parents[$p]->id, $globalnoroute)) {
             $p++;
             continue;
         }
         // Add current parent category
         $pathway->addItem($this->escape($parents[$p]->title), JRoute::_(FlexicontentHelperRoute::getCategoryRoute($parents[$p]->slug)));
         $p++;
     }
     $authordescr_item_html = false;
     if ($authordescr_item) {
         $flexi_html_helper = new flexicontent_html();
         $authordescr_item_html = $flexi_html_helper->renderItem($authordescr_itemid);
     }
     //echo $authordescr_item_html; exit();
     if ($clayout) {
         // Add the templates css files if availables
         if (isset($themes->category->{$clayout}->css)) {
             foreach ($themes->category->{$clayout}->css as $css) {
                 $document->addStyleSheet($this->baseurl . '/' . $css);
             }
         }
         // Add the templates js files if availables
         if (isset($themes->category->{$clayout}->js)) {
             foreach ($themes->category->{$clayout}->js as $js) {
                 $document->addScript($this->baseurl . '/' . $js);
             }
         }
         // Set the template var
         $tmpl = $themes->category->{$clayout}->tmplvar;
     } else {
         $tmpl = '.category.default';
     }
     // @TODO trigger the plugin selectively
     // and delete the plugins tags if not active
     if ($params->get('trigger_onprepare_content_cat')) {
         JPluginHelper::importPlugin('content');
         // Allow to trigger content plugins on category description
         // NOTE: for J2.5, we will trigger the plugins as if description text was an article text, using ... 'com_content.article'
         $category->text = $category->description;
         $results = $dispatcher->trigger('onContentPrepare', array('com_content.article', &$category, &$params, 0));
         JRequest::setVar('layout', $layout);
         // Restore LAYOUT variable should some plugin have modified it
         $category->description = $category->text;
     }
     // Maybe here not to import all plugins but just those for description field or add a parameter for this
     // Anyway these events are usually not very time consuming as is the the event onPrepareContent(J1.5)/onContentPrepare(J1.6+)
     JPluginHelper::importPlugin('content');
     foreach ($items as $item) {
         $item->event = new stdClass();
         $item->params = new JRegistry($item->attribs);
         // !!! The triggering of the event onPrepareContent(J1.5)/onContentPrepare(J1.6+) of content plugins
         // !!! for description field (maintext) along with all other flexicontent
         // !!! fields is handled by flexicontent.fields.php
         // !!! Had serious performance impact
         // CODE REMOVED
         // We must check if the current category is in the categories of the item ..
         $item_in_category = false;
         if ($item->catid == $category->id) {
             $item_in_category = true;
         } else {
             foreach ($item->cats as $cat) {
                 if ($cat->id == $category->id) {
                     $item_in_category = true;
                     break;
                 }
             }
         }
         // ADVANCED CATEGORY ROUTING (=set the most appropriate category for the item ...)
         // CHOOSE APPROPRIATE category-slug FOR THE ITEM !!! ( )
         if ($item_in_category && !in_array($category->id, $globalnoroute)) {
             // 1. CATEGORY SLUG: CURRENT category
             // Current category IS a category of the item and ALSO routing (creating links) to this category is allowed
             $item->categoryslug = $category->slug;
         } else {
             if (!in_array($item->catid, $globalnoroute)) {
                 // 2. CATEGORY SLUG: ITEM's MAIN category   (already SET, ... no assignment needed)
                 // Since we cannot use current category (above), we will use item's MAIN category
                 // ALSO routing (creating links) to this category is allowed
             } else {
                 // 3. CATEGORY SLUG: ANY ITEM's category
                 // We will use the first for which routing (creating links) to the category is allowed
                 $allcats = array();
                 $item->cats = $item->cats ? $item->cats : array();
                 foreach ($item->cats as $cat) {
                     if (!in_array($cat->id, $globalnoroute)) {
                         $item->categoryslug = $globalcats[$cat->id]->slug;
                         break;
                     }
                 }
             }
         }
         // Just put item's text (description field) inside property 'text' in case the events modify the given text,
         $item->text = isset($item->fields['text']->display) ? $item->fields['text']->display : '';
         // Set the view and option to 'category' and 'com_content'  (actually view is already called category)
         JRequest::setVar('option', 'com_content');
         JRequest::setVar("isflexicontent", "yes");
         // These events return text that could be displayed at appropriate positions by our templates
         $item->event = new stdClass();
         $results = $dispatcher->trigger('onContentAfterTitle', array('com_content.category', &$item, &$params, 0));
         $item->event->afterDisplayTitle = trim(implode("\n", $results));
         $results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.category', &$item, &$params, 0));
         $item->event->beforeDisplayContent = trim(implode("\n", $results));
         $results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.category', &$item, &$params, 0));
         $item->event->afterDisplayContent = trim(implode("\n", $results));
         // Set the option back to 'com_flexicontent'
         JRequest::setVar('option', 'com_flexicontent');
         // Put text back into the description field, THESE events SHOULD NOT modify the item text, but some plugins may do it anyway... , so we assign text back for compatibility
         $item->fields['text']->display =& $item->text;
     }
     // Calculate CSS classes needed to add special styling markups to the items
     flexicontent_html::calculateItemMarkups($items, $params);
     // *****************************************************
     // Remove unroutable categories from sub/peer categories
     // *****************************************************
     // sub-cats
     $_categories = array();
     foreach ($categories as $i => $cat) {
         if (in_array($cat->id, $globalnoroute)) {
             continue;
         }
         $_categories[] = $categories[$i];
     }
     $categories = $_categories;
     // peer-cats
     $_categories = array();
     foreach ($peercats as $i => $cat) {
         if (in_array($cat->id, $globalnoroute)) {
             continue;
         }
         $_categories[] = $peercats[$i];
     }
     $peercats = $_categories;
     // ************************************
     // Get some variables needed for images
     // ************************************
     $joomla_image_path = $app->getCfg('image_path', '');
     $joomla_image_url = str_replace(DS, '/', $joomla_image_path);
     $joomla_image_path = $joomla_image_path ? $joomla_image_path . DS : '';
     $joomla_image_url = $joomla_image_url ? $joomla_image_url . '/' : '';
     $phpThumbURL = JURI::base(true) . '/components/com_flexicontent/librairies/phpthumb/phpThumb.php?src=';
     // **************
     // CATEGORY IMAGE
     // **************
     // category image params
     $show_cat_image = $params->get('show_description_image', 0);
     // we use different name for variable
     $cat_image_source = $params->get('cat_image_source', 2);
     // 0: extract, 1: use param, 2: use both
     $cat_link_image = $params->get('cat_link_image', 1);
     $cat_image_method = $params->get('cat_image_method', 1);
     $cat_image_width = $params->get('cat_image_width', 80);
     $cat_image_height = $params->get('cat_image_height', 80);
     $cat_default_image = $params->get('cat_default_image', '');
     if ($show_cat_image) {
         $h = '&amp;h=' . $cat_image_height;
         $w = '&amp;w=' . $cat_image_width;
         $aoe = '&amp;aoe=1';
         $q = '&amp;q=95';
         $zc = $cat_image_method ? '&amp;zc=' . $cat_image_method : '';
     }
     if ($cat_default_image) {
         $src = JURI::base(true) . "/" . $joomla_image_url . $cat_default_image;
         $ext = pathinfo($src, PATHINFO_EXTENSION);
         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
         $conf = $w . $h . $aoe . $q . $zc . $f;
         $default_image = $phpThumbURL . $src . $conf;
         $default_image = '<img class="fccat_image" style="float:' . $cat_image_float . '" src="' . $default_image . '" alt="%s" title="%s"/>';
     } else {
         $default_image = '';
     }
     // Create category image/description/etc data
     $cat = $category;
     $image = "";
     if ($cat) {
         if ($cat->id && $show_cat_image) {
             $cat->image = $params->get('image');
             $cat->introtext =& $cat->description;
             $cat->fulltext = "";
             if ($cat_image_source && $cat->image && JFile::exists(JPATH_SITE . DS . $joomla_image_path . $cat->image)) {
                 $src = JURI::base(true) . "/" . $joomla_image_url . $cat->image;
                 $ext = pathinfo($src, PATHINFO_EXTENSION);
                 $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                 $conf = $w . $h . $aoe . $q . $zc . $f;
                 $image = $phpThumbURL . $src . $conf;
             } else {
                 if ($cat_image_source != 1 && ($src = flexicontent_html::extractimagesrc($cat))) {
                     $ext = pathinfo($src, PATHINFO_EXTENSION);
                     $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                     $conf = $w . $h . $aoe . $q . $zc . $f;
                     $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
                     $src = $base_url . $src;
                     $image = $phpThumbURL . $src . $conf;
                 }
             }
             $cat->image_src = @$src;
             // Also add image category URL for developers
             if ($image) {
                 $image = '<img class="fccat_image" src="' . $image . '" alt="' . $this->escape($cat->title) . '" title="' . $this->escape($cat->title) . '"/>';
             } else {
                 if ($default_image) {
                     $image = sprintf($default_image, $cat->title, $cat->title);
                 }
             }
             if ($cat_link_image && $image) {
                 $image = '<a href="' . JRoute::_(FlexicontentHelperRoute::getCategoryRoute($cat->slug)) . '">' . $image . '</a>';
             }
         }
         $cat->image = $image;
     }
     // ******************************
     // SUBCATEGORIES (some templates)
     // ******************************
     // sub-category image params
     $show_cat_image = $params->get('show_description_image_subcat', 1);
     // we use different name for variable
     $cat_image_source = $params->get('subcat_image_source', 2);
     // 0: extract, 1: use param, 2: use both
     $cat_link_image = $params->get('subcat_link_image', 1);
     $cat_image_method = $params->get('subcat_image_method', 1);
     $cat_image_width = $params->get('subcat_image_width', 24);
     $cat_image_height = $params->get('subcat_image_height', 24);
     $cat_default_image = $params->get('subcat_default_image', '');
     if ($show_cat_image) {
         $h = '&amp;h=' . $cat_image_height;
         $w = '&amp;w=' . $cat_image_width;
         $aoe = '&amp;aoe=1';
         $q = '&amp;q=95';
         $zc = $cat_image_method ? '&amp;zc=' . $cat_image_method : '';
     }
     if ($cat_default_image) {
         $src = JURI::base(true) . "/" . $joomla_image_url . $cat_default_image;
         $ext = pathinfo($src, PATHINFO_EXTENSION);
         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
         $conf = $w . $h . $aoe . $q . $zc . $f;
         $default_image = $phpThumbURL . $src . $conf;
         $default_image = '<img class="fccat_image" style="float:' . $cat_image_float . '" src="' . $default_image . '" alt="%s" title="%s"/>';
     } else {
         $default_image = '';
     }
     // Create sub-category image/description/etc data
     foreach ($categories as $cat) {
         $image = "";
         if ($show_cat_image) {
             if (!is_object($cat->params)) {
                 $cat->params = new JRegistry($cat->params);
             }
             $cat->image = $cat->params->get('image');
             $cat->introtext =& $cat->description;
             $cat->fulltext = "";
             if ($cat_image_source && $cat->image && JFile::exists(JPATH_SITE . DS . $joomla_image_path . $cat->image)) {
                 $src = JURI::base(true) . "/" . $joomla_image_url . $cat->image;
                 $ext = pathinfo($src, PATHINFO_EXTENSION);
                 $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                 $conf = $w . $h . $aoe . $q . $zc . $f;
                 $image = $phpThumbURL . $src . $conf;
             } else {
                 if ($cat_image_source != 1 && ($src = flexicontent_html::extractimagesrc($cat))) {
                     $ext = pathinfo($src, PATHINFO_EXTENSION);
                     $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                     $conf = $w . $h . $aoe . $q . $zc . $f;
                     $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
                     $src = $base_url . $src;
                     $image = $phpThumbURL . $src . $conf;
                 }
             }
             $cat->image_src = @$src;
             // Also add image category URL for developers
             if ($image) {
                 $image = '<img class="fccat_image" src="' . $image . '" alt="' . $this->escape($cat->title) . '" title="' . $this->escape($cat->title) . '"/>';
             } else {
                 if ($default_image) {
                     $image = sprintf($default_image, $cat->title, $cat->title);
                 }
             }
             if ($cat_link_image && $image) {
                 $image = '<a href="' . JRoute::_(FlexicontentHelperRoute::getCategoryRoute($cat->slug)) . '">' . $image . '</a>';
             }
         }
         $cat->image = $image;
     }
     // *******************************
     // PEERCATEGORIES (some templates)
     // *******************************
     // peer-category image params
     $show_cat_image = $params->get('show_description_image_peercat', 1);
     // we use different name for variable
     $cat_image_source = $params->get('peercat_image_source', 2);
     // 0: extract, 1: use param, 2: use both
     $cat_link_image = $params->get('peercat_link_image', 1);
     $cat_image_method = $params->get('peercat_image_method', 1);
     $cat_image_width = $params->get('peercat_image_width', 24);
     $cat_image_height = $params->get('peercat_image_height', 24);
     $cat_default_image = $params->get('peercat_default_image', '');
     if ($show_cat_image) {
         $h = '&amp;h=' . $cat_image_height;
         $w = '&amp;w=' . $cat_image_width;
         $aoe = '&amp;aoe=1';
         $q = '&amp;q=95';
         $zc = $cat_image_method ? '&amp;zc=' . $cat_image_method : '';
     }
     if ($cat_default_image) {
         $src = JURI::base(true) . "/" . $joomla_image_url . $cat_default_image;
         $ext = pathinfo($src, PATHINFO_EXTENSION);
         $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
         $conf = $w . $h . $aoe . $q . $zc . $f;
         $default_image = $phpThumbURL . $src . $conf;
         $default_image = '<img class="fccat_image" style="float:' . $cat_image_float . '" src="' . $default_image . '" alt="%s" title="%s"/>';
     } else {
         $default_image = '';
     }
     // Create peer-category image/description/etc data
     foreach ($peercats as $cat) {
         $image = "";
         if ($show_cat_image) {
             if (!is_object($cat->params)) {
                 $cat->params = new JRegistry($cat->params);
             }
             $cat->image = $cat->params->get('image');
             $cat->introtext =& $cat->description;
             $cat->fulltext = "";
             if ($cat_image_source && $cat->image && JFile::exists(JPATH_SITE . DS . $joomla_image_path . $cat->image)) {
                 $src = JURI::base(true) . "/" . $joomla_image_url . $cat->image;
                 $ext = pathinfo($src, PATHINFO_EXTENSION);
                 $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                 $conf = $w . $h . $aoe . $q . $zc . $f;
                 $image = $phpThumbURL . $src . $conf;
             } else {
                 if ($cat_image_source != 1 && ($src = flexicontent_html::extractimagesrc($cat))) {
                     $ext = pathinfo($src, PATHINFO_EXTENSION);
                     $f = in_array($ext, array('png', 'ico', 'gif')) ? '&amp;f=' . $ext : '';
                     $conf = $w . $h . $aoe . $q . $zc . $f;
                     $base_url = !preg_match("#^http|^https|^ftp|^/#i", $src) ? JURI::base(true) . '/' : '';
                     $src = $base_url . $src;
                     $image = $phpThumbURL . $src . $conf;
                 }
             }
             $cat->image_src = @$src;
             // Also add image category URL for developers
             if ($image) {
                 $image = '<img class="fccat_image" src="' . $image . '" alt="' . $this->escape($cat->title) . '" title="' . $this->escape($cat->title) . '"/>';
             } else {
                 if ($default_image) {
                     $image = sprintf($default_image, $cat->title, $cat->title);
                 }
             }
             if ($cat_link_image && $image) {
                 $image = '<a href="' . JRoute::_(FlexicontentHelperRoute::getCategoryRoute($cat->slug)) . '">' . $image . '</a>';
             }
         }
         $cat->image = $image;
     }
     // remove previous alpha index filter
     //$uri->delVar('letter');
     // remove filter variables (includes search box and sort order)
     preg_match_all('/filter[^=]*/', $uri->toString(), $matches);
     foreach ($matches[0] as $match) {
         //$uri->delVar($match);
     }
     // Build Lists
     $lists = array();
     //ordering
     $lists['filter_order'] = JRequest::getCmd('filter_order', 'i.title', 'default');
     $lists['filter_order_Dir'] = JRequest::getCmd('filter_order_Dir', 'ASC', 'default');
     $lists['filter'] = JRequest::getString('filter', '', 'default');
     // Add html to filter objects
     $form_name = 'adminForm';
     if ($filters) {
         FlexicontentFields::renderFilters($params, $filters, $form_name);
     }
     // ****************************
     // Create the pagination object
     // ****************************
     $pageNav = $this->get('pagination');
     $resultsCounter = $pageNav->getResultsCounter();
     // for overriding model's result counter
     // **********************************************************************
     // Print link ... must include layout and current filtering url vars, etc
     // **********************************************************************
     $curr_url = $_SERVER['REQUEST_URI'];
     $print_link = $curr_url . (strstr($curr_url, '?') ? '&amp;' : '?') . 'pop=1&amp;tmpl=component&amp;print=1';
     $pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
     $this->assignRef('layout_vars', $layout_vars);
     $this->assignRef('action', $category_link);
     $this->assignRef('print_link', $print_link);
     $this->assignRef('category', $category);
     $this->assignRef('categories', $categories);
     $this->assignRef('peercats', $peercats);
     $this->assignRef('items', $items);
     $this->assignRef('authordescr_item_html', $authordescr_item_html);
     $this->assignRef('lists', $lists);
     $this->assignRef('params', $params);
     $this->assignRef('pageNav', $pageNav);
     $this->assignRef('pageclass_sfx', $pageclass_sfx);
     $this->assignRef('pagination', $pageNav);
     // compatibility Alias for old templates
     $this->assignRef('resultsCounter', $resultsCounter);
     // for overriding model's result counter
     $this->assignRef('limitstart', $limitstart);
     // compatibility shortcut
     $this->assignRef('filters', $filters);
     $this->assignRef('comments', $comments);
     $this->assignRef('alpha', $alpha);
     $this->assignRef('tmpl', $tmpl);
     //HERE WE NEED TO PRINT THE DATA || But I think it is not protected yet
     echo @json_encode($items);
 }
コード例 #26
0
ファイル: items.php プロジェクト: khetsothea/flexicontent-cck
 /**
  * Logic to save an item
  *
  * @access public
  * @return void
  * @since 1.0
  */
 function save()
 {
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     //echo '<html>  <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <body>';
     // Initialize variables
     $app = JFactory::getApplication();
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $config = JFactory::getConfig();
     $session = JFactory::getSession();
     $task = JRequest::getVar('task');
     $ctrl_task = 'task=items.';
     // *********************
     // Get data from request
     // *********************
     // Retrieve form data these are subject to basic filtering
     $data = JRequest::getVar('jform', array(), 'post', 'array');
     // Core Fields and and item Parameters
     $custom = JRequest::getVar('custom', array(), 'post', 'array');
     // Custom Fields
     $jfdata = JRequest::getVar('jfdata', array(), 'post', 'array');
     // Joomfish Data
     // Set into model: id (needed for loading correct item), and type id (e.g. needed for getting correct type parameters for new items)
     $data_id = (int) $data['id'];
     $isnew = $data_id == 0;
     // If new make sure that type id is set too, before creating the model
     if ($isnew) {
         $typeid = JRequest::setvar('typeid', (int) @$data['type_id']);
     }
     // Get the model
     $model = $this->getModel('item');
     $model->setId($data_id);
     // Make sure id is correct
     // Get some flags this will also trigger item loading if not already loaded
     $isOwner = $model->get('created_by') == $user->get('id');
     // Get merged parameters: component, type, menu (FE)
     $params = new JRegistry();
     $model_params = $model->getComponentTypeParams();
     $params->merge($model_params);
     // Unique id for new items, needed by some fields for temporary data
     $unique_tmp_itemid = JRequest::getVar('unique_tmp_itemid');
     // Auto title for some content types
     if ($params->get('auto_title', 0)) {
         $data['title'] = (int) $data['id'];
     }
     // item id or ZERO for new items
     // *************************************
     // ENFORCE can change category ACL perms
     // *************************************
     $perms = FlexicontentHelperPerm::getPerm();
     // Per content type change category permissions
     $current_type_id = $isnew || !$model->get('type_id') ? (int) @$data['type_id'] : $model->get('type_id');
     // GET current (existing/old) item TYPE ID
     $CanChangeFeatCat = $user->authorise('flexicontent.change.cat.feat', 'com_flexicontent.type.' . $current_type_id);
     $CanChangeSecCat = $user->authorise('flexicontent.change.cat.sec', 'com_flexicontent.type.' . $current_type_id);
     $CanChangeCat = $user->authorise('flexicontent.change.cat', 'com_flexicontent.type.' . $current_type_id);
     $AutoApproveChanges = $perms->AutoApproveChanges;
     $enable_featured_cid_selector = $perms->MultiCat && $CanChangeFeatCat;
     $enable_cid_selector = $perms->MultiCat && $CanChangeSecCat;
     $enable_catid_selector = $isnew && !$params->get('catid_default') || !$isnew && !$model->get('catid') || $CanChangeCat;
     // Enforce maintaining featured categories
     $featured_cats_parent = $params->get('featured_cats_parent', 0);
     $featured_cats = array();
     if ($featured_cats_parent && !$enable_featured_cid_selector) {
         $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
         $disabled_cats = $params->get('featured_cats_parent_disable', 1) ? array($featured_cats_parent) : array();
         $featured_cid = array();
         if (!$isnew) {
             foreach ($model->get('categories') as $item_cat) {
                 if (isset($featured_tree[$item_cat]) && !isset($disabled_cats[$item_cat])) {
                     $featured_cid[] = $item_cat;
                 }
             }
         }
         $data['featured_cid'] = $featured_cid;
     }
     // Enforce maintaining secondary categories
     if (!$enable_cid_selector) {
         if ($isnew) {
             $data['cid'] = $params->get('cid_default');
         } else {
             if (isset($featured_cid)) {
                 $featured_cid_arr = array_flip($featured_cid);
                 $sec_cid = array();
                 foreach ($model->get('cats') as $item_cat) {
                     if (!isset($featured_cid_arr[$item_cat])) {
                         $sec_cid[] = $item_cat;
                     }
                 }
                 $data['cid'] = $sec_cid;
             } else {
                 $data['cid'] = $model->get('cats');
             }
         }
     }
     if (!$enable_catid_selector) {
         if ($isnew && $params->get('catid_default')) {
             $data['catid'] = $params->get('catid_default');
         } else {
             if ($model->get('catid')) {
                 $data['catid'] = $model->get('catid');
             }
         }
     }
     // **************************
     // Basic Form data validation
     // **************************
     // Get the JForm object, but do not pass any data we only want the form object,
     // in order to validate the data and not create a filled-in form
     $form = $model->getForm();
     // Validate Form data for core fields and for parameters
     $post = $model->validate($form, $data);
     // Check for validation error
     if (!$post) {
         // Get the validation messages and push up to three validation messages out to the user
         $errors = $form->getErrors();
         for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
             $app->enqueueMessage($errors[$i] instanceof Exception ? $errors[$i]->getMessage() : $errors[$i], 'error');
         }
         // Set POST form date into the session, so that they get reloaded
         $app->setUserState($form->option . '.edit.' . $form->context . '.data', $data);
         // Save the jform data in the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.custom', $custom);
         // Save the custom fields data in the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', $jfdata);
         // Save the falang translations into the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', $unique_tmp_itemid);
         // Save temporary unique item id into the session
         // Redirect back to the item form
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         return false;
         //die('error');
     }
     // Some values need to be assigned after validation
     $post['attribs'] = @$data['attribs'];
     // Workaround for item's template parameters being clear by validation since they are not present in item.xml
     $post['custom'] =& $custom;
     // Assign array of custom field values, they are in the 'custom' form array instead of jform
     $post['jfdata'] =& $jfdata;
     // Assign array of Joomfish field values, they are in the 'jfdata' form array instead of jform
     // Assign template parameters of the select ilayout as an sub-array (the DB model will handle the merging of parameters)
     $ilayout = $data['attribs']['ilayout'];
     if (!empty($data['layouts'][$ilayout])) {
         //echo "<pre>"; print_r($post['attribs']);
         //$post['attribs'] = array_merge($post['attribs'], $data['layouts'][$ilayout]);
         $post['attribs']['layouts'] = $data['layouts'];
         //echo "<pre>"; print_r($post['attribs']); exit;
     }
     // USEFULL FOR DEBUGING for J2.5 (do not remove commented code)
     //$diff_arr = array_diff_assoc ( $data, $post);
     //echo "<pre>"; print_r($diff_arr); jexit();
     // Make sure Content ID in the REQUEST is set, this is needed in BACKEND, needed in some cases
     // NOTE this is not the same as jform['cid'] which is the category IDs of the Content Item
     JRequest::setVar('cid', array($model->getId()), 'post', 'array');
     // ********************************************************************************
     // PERFORM ACCESS CHECKS, NOTE: we need to check access again, despite having
     // checked them on edit form load, because user may have tampered with the form ...
     // ********************************************************************************
     $itemAccess = $model->getItemAccess();
     $canAdd = $itemAccess->get('access-create');
     // includes check of creating in at least one category
     $canEdit = $itemAccess->get('access-edit');
     // includes privileges edit and edit-own
     $type_id = (int) @$post['type_id'];
     // Typecast to int, (already done for J2.5 via validating)
     if (!$isnew && $model->get('type_id') == $type_id) {
         // Existing item with Type not being ALTERED, content type can be maintained regardless of privilege
         $canCreateType = true;
     } else {
         // New item or existing item with Type is being ALTERED, check privilege to create items of this type
         $canCreateType = $model->canCreateType(array($type_id), true, $types);
     }
     // *****************************************************************
     // Calculate user's CREATE / EDIT privileges on current content item
     // *****************************************************************
     $hasCoupon = false;
     // Normally used in frontend only
     if (!$isnew) {
         // If no edit privilege, check if item is editable till logoff
         if (!$canEdit) {
             if ($session->has('rendered_uneditable', 'flexicontent')) {
                 $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
                 $canEdit = isset($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')];
                 $hasCoupon = isset($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')] == 2;
                 // editable via coupon
             }
         }
     } else {
         // No special CREATE allowing case for backend
     }
     // New item: check if user can create in at least one category
     if ($isnew && !$canAdd) {
         JError::raiseWarning(403, JText::_('FLEXI_NO_ACCESS_CREATE'));
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         return;
     }
     // Existing item: Check if user can edit current item
     if (!$isnew && !$canEdit) {
         JError::raiseWarning(403, JText::_('FLEXI_NO_ACCESS_EDIT'));
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         return;
     }
     if (!$canCreateType) {
         $msg = isset($types[$type_id]) ? JText::sprintf('FLEXI_NO_ACCESS_CREATE_CONTENT_OF_TYPE', JText::_($types[$type_id]->name)) : ' Content Type ' . $type_id . ' was not found OR is not published';
         JError::raiseWarning(403, $msg);
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         return;
     }
     // Get "BEFORE SAVE" categories for information mail
     $before_cats = array();
     if (!$isnew) {
         $query = 'SELECT DISTINCT c.id, c.title FROM #__categories AS c' . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.catid = c.id' . ' WHERE rel.itemid = ' . (int) $model->get('id');
         $db->setQuery($query);
         $before_cats = $db->loadObjectList('id');
         $before_maincat = $model->get('catid');
         $original_item = $model->getItem($post['id'], $check_view_access = false, $no_cache = true, $force_version = 0);
     }
     // ****************************************
     // Try to store the form data into the item
     // ****************************************
     if (!$model->store($post)) {
         // Set error message about saving failed, and also the reason (=model's error message)
         $msg = JText::_('FLEXI_ERROR_STORING_ITEM');
         JError::raiseWarning(500, $msg . ": " . $model->getError());
         // Set POST form date into the session, so that they get reloaded
         $app->setUserState($form->option . '.edit.' . $form->context . '.data', $data);
         // Save the jform data in the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.custom', $custom);
         // Save the custom fields data in the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', $jfdata);
         // Save the falang translations into the session
         $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', $unique_tmp_itemid);
         // Save temporary unique item id into the session
         // Saving has failed check-in and redirect back to the item form,
         // redirect back to the item form reloading the posted data
         $model->checkin();
         $this->setRedirect($_SERVER['HTTP_REFERER']);
         if (JRequest::getVar('fc_doajax_submit')) {
             echo flexicontent_html::get_system_messages_html();
             exit;
             // Ajax submit, do not rerender the view
         }
         return;
         //die('save error');
     }
     // **************************************************
     // Check in model and get item id in case of new item
     // **************************************************
     $model->checkin();
     $post['id'] = $isnew ? (int) $model->get('id') : $post['id'];
     // Get items marked as newly submitted
     $newly_submitted = $session->get('newly_submitted', array(), 'flexicontent');
     if ($isnew) {
         // Mark item as newly submitted, to allow to a proper "THANKS" message after final save & close operation (since user may have clicked add instead of add & close)
         $newly_submitted[$model->get('id')] = 1;
         $session->set('newly_submitted', $newly_submitted, 'flexicontent');
     }
     $newly_submitted_item = @$newly_submitted[$model->get('id')];
     // ***********************************************************************************************************
     // Get newly saved -latest- version (store task gets latest) of the item, and also calculate publish privelege
     // ***********************************************************************************************************
     $item = $model->getItem($post['id'], $check_view_access = false, $no_cache = true, $force_version = -1);
     $canPublish = $model->canEditState($item, $check_cat_perm = true) || $hasCoupon;
     // ********************************************************************************************
     // Use session to detect multiple item saves to avoid sending notification EMAIL multiple times
     // ********************************************************************************************
     $is_first_save = true;
     if ($session->has('saved_fcitems', 'flexicontent')) {
         $saved_fcitems = $session->get('saved_fcitems', array(), 'flexicontent');
         $is_first_save = $isnew ? true : !isset($saved_fcitems[$model->get('id')]);
     }
     // Add item to saved items of the corresponding session array
     $saved_fcitems[$model->get('id')] = $timestamp = time();
     // Current time as seconds since Unix epoc;
     $session->set('saved_fcitems', $saved_fcitems, 'flexicontent');
     // ********************************************
     // Get categories added / removed from the item
     // ********************************************
     $query = 'SELECT DISTINCT c.id, c.title FROM #__categories AS c' . ' JOIN #__flexicontent_cats_item_relations AS rel ON rel.catid = c.id' . ' WHERE rel.itemid = ' . (int) $model->get('id');
     $db->setQuery($query);
     $after_cats = $db->loadObjectList('id');
     if (!$isnew) {
         $cats_added_ids = array_diff(array_keys($after_cats), array_keys($before_cats));
         foreach ($cats_added_ids as $cats_added_id) {
             $cats_added_titles[] = $after_cats[$cats_added_id]->title;
         }
         $cats_removed_ids = array_diff(array_keys($before_cats), array_keys($after_cats));
         foreach ($cats_removed_ids as $cats_removed_id) {
             $cats_removed_titles[] = $before_cats[$cats_removed_id]->title;
         }
         $cats_altered = count($cats_added_ids) + count($cats_removed_ids);
         $after_maincat = $model->get('catid');
     }
     // *******************************************************************************************************************
     // We need to get emails to notify, from Global/item's Content Type parameters -AND- from item's categories parameters
     // *******************************************************************************************************************
     $notify_emails = array();
     if ($is_first_save || $cats_altered || $params->get('nf_enable_debug', 0)) {
         // Get needed flags regarding the saved items
         $approve_version = 2;
         $pending_approval_state = -3;
         $draft_state = -4;
         $current_version = FLEXIUtilities::getCurrentVersions($item->id, true);
         // Get current item version
         $last_version = FLEXIUtilities::getLastVersions($item->id, true);
         // Get last version (=latest one saved, highest version id),
         // $post variables vstate & state may have been (a) tampered in the form, and/or (b) altered by save procedure so better not use them
         $needs_version_reviewal = !$isnew && $last_version > $current_version && !$canPublish && !$AutoApproveChanges;
         $needs_publication_approval = $isnew && $item->state == $pending_approval_state && !$canPublish;
         $draft_from_non_publisher = $item->state == $draft_state && !$canPublish;
         if ($draft_from_non_publisher) {
             // Suppress notifications for draft-state items (new or existing ones), for these each author will publication approval manually via a button
             $nConf = false;
         } else {
             // Get notifications configuration and select appropriate emails for current saving case
             $nConf = $model->getNotificationsConf($params);
             //echo "<pre>"; print_r($nConf); "</pre>";
         }
         if ($nConf) {
             $states_notify_new = $params->get('states_notify_new', array(1, 0, FLEXI_J16GE ? 2 : -1, -3, -4, -5));
             if (empty($states_notify_new)) {
                 $states_notify_new = array();
             } else {
                 if (!is_array($states_notify_new)) {
                     $states_notify_new = !FLEXI_J16GE ? array($states_notify_new) : explode("|", $states_notify_new);
                 }
             }
             $states_notify_existing = $params->get('states_notify_existing', array(1, 0, FLEXI_J16GE ? 2 : -1, -3, -4, -5));
             if (empty($states_notify_existing)) {
                 $states_notify_existing = array();
             } else {
                 if (!is_array($states_notify_existing)) {
                     $states_notify_existing = !FLEXI_J16GE ? array($states_notify_existing) : explode("|", $states_notify_existing);
                 }
             }
             $n_state_ok = in_array($item->state, $states_notify_new);
             $e_state_ok = in_array($item->state, $states_notify_existing);
             if ($needs_publication_approval) {
                 $notify_emails = $nConf->emails->notify_new_pending;
             } else {
                 if ($isnew && $n_state_ok) {
                     $notify_emails = $nConf->emails->notify_new;
                 } else {
                     if ($isnew) {
                         $notify_emails = array();
                     } else {
                         if ($needs_version_reviewal) {
                             $notify_emails = $nConf->emails->notify_existing_reviewal;
                         } else {
                             if (!$isnew && $e_state_ok) {
                                 $notify_emails = $nConf->emails->notify_existing;
                             } else {
                                 if (!$isnew) {
                                     $notify_emails = array();
                                 }
                             }
                         }
                     }
                 }
             }
             if ($needs_publication_approval) {
                 $notify_text = $params->get('text_notify_new_pending');
             } else {
                 if ($isnew) {
                     $notify_text = $params->get('text_notify_new');
                 } else {
                     if ($needs_version_reviewal) {
                         $notify_text = $params->get('text_notify_existing_reviewal');
                     } else {
                         if (!$isnew) {
                             $notify_text = $params->get('text_notify_existing');
                         }
                     }
                 }
             }
             //print_r($notify_emails); jexit();
         }
     }
     // *********************************************************************************************************************
     // If there are emails to notify for current saving case, then send the notifications emails, but
     // *********************************************************************************************************************
     if (!empty($notify_emails) && count($notify_emails)) {
         $notify_vars = new stdClass();
         $notify_vars->needs_version_reviewal = $needs_version_reviewal;
         $notify_vars->needs_publication_approval = $needs_publication_approval;
         $notify_vars->isnew = $isnew;
         $notify_vars->notify_emails = $notify_emails;
         $notify_vars->notify_text = $notify_text;
         $notify_vars->before_cats = $before_cats;
         $notify_vars->after_cats = $after_cats;
         $notify_vars->original_item = @$original_item;
         $model->sendNotificationEmails($notify_vars, $params, $manual_approval_request = 0);
     }
     // ***************************************************
     // CLEAN THE CACHE so that our changes appear realtime
     // ***************************************************
     $cache = FLEXIUtilities::getCache($group = '', 0);
     $cache->clean('com_flexicontent_items');
     $cache->clean('com_flexicontent_filters');
     $cache = FLEXIUtilities::getCache($group = '', 1);
     $cache->clean('com_flexicontent_items');
     $cache->clean('com_flexicontent_filters');
     // ****************************************************************************************************************************
     // Recalculate EDIT PRIVILEGE of new item. Reason for needing to do this is because we can have create permission in a category
     // and thus being able to set this category as item's main category, but then have no edit/editown permission for this category
     // ****************************************************************************************************************************
     $asset = 'com_content.article.' . $model->get('id');
     $canEdit = $user->authorise('core.edit', $asset) || $user->authorise('core.edit.own', $asset) && $isOwner;
     // ALTERNATIVE 1
     //$canEdit = $model->getItemAccess()->get('access-edit'); // includes privileges edit and edit-own
     // ALTERNATIVE 2
     //$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $model->get('id'));
     //$canEdit = in_array('edit', $rights) || (in_array('edit.own', $rights) && $isOwner) ;
     // *******************************************************************************************************
     // Check if user can not edit item further (due to changed main category, without edit/editown permission)
     // *******************************************************************************************************
     if (!$canEdit) {
         if ($task == 'apply' || $task == 'apply_type') {
             // APPLY TASK: Temporarily set item to be editable till closing it and not through all session
             // (we will/should clear this flag when item is closed, since we have another flag to indicate new items
             $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
             $rendered_uneditable[$model->get('id')] = -1;
             $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
             $canEdit = 1;
         } else {
             if ($newly_submitted_item) {
                 // NEW ITEM: Do not use editable till logoff behaviour
                 // ALSO: Clear editable FLAG set in the case that 'apply' button was used during new item creation
                 if (!$params->get('items_session_editable', 0)) {
                     $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
                     if (isset($rendered_uneditable[$model->get('id')])) {
                         unset($rendered_uneditable[$model->get('id')]);
                         $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
                     }
                 }
             } else {
                 // EXISTING ITEM: (if enabled) Use the editable till logoff behaviour
                 if ($params->get('items_session_editable', 0)) {
                     // Set notice for existing item being editable till logoff
                     JError::raiseNotice(403, JText::_('FLEXI_CANNOT_EDIT_AFTER_LOGOFF'));
                     // Allow item to be editable till logoff
                     $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
                     $rendered_uneditable[$model->get('id')] = 1;
                     $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
                     $canEdit = 1;
                 }
             }
         }
         // Set notice about saving an item that cannot be changed further
         if (!$canEdit) {
             $app->enqueueMessage(JText::_('FLEXI_CANNOT_MAKE_FURTHER_CHANGES_TO_CONTENT'), 'message');
         }
     }
     // ****************************************************************
     // Check for new Content Item is being closed, and clear some flags
     // ****************************************************************
     if ($task != 'apply' && $task != 'apply_type' && $newly_submitted_item) {
         // Clear item from being marked as newly submitted
         unset($newly_submitted[$model->get('id')]);
         $session->set('newly_submitted', $newly_submitted, 'flexicontent');
         // The 'apply' task may set 'editable till logoff' FLAG ...
         // CLEAR IT, since NEW content this is meant to be used temporarily
         if (!$params->get('items_session_editable', 0)) {
             $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
             if (isset($rendered_uneditable[$model->get('id')])) {
                 unset($rendered_uneditable[$model->get('id')]);
                 $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
             }
         }
     }
     // ****************************************
     // Saving is done, decide where to redirect
     // ****************************************
     switch ($task) {
         case 'apply':
         case 'apply_type':
             $link = 'index.php?option=com_flexicontent&' . $ctrl_task . 'edit&cid=' . (int) $model->get('id');
             break;
         case 'saveandnew':
             $link = $type_id ? 'index.php?option=com_flexicontent&view=item&typeid=' . $type_id : 'index.php?option=com_flexicontent&view=item';
             break;
         default:
             $link = 'index.php?option=com_flexicontent&view=items';
             break;
     }
     $msg = JText::_('FLEXI_ITEM_SAVED');
     $this->setRedirect($link, $msg);
     if (JRequest::getVar('fc_doajax_submit')) {
         JFactory::getApplication()->enqueueMessage($msg, 'message');
         echo flexicontent_html::get_system_messages_html();
         exit;
         // Ajax submit, do not rerender the view
     }
 }
コード例 #27
0
ファイル: view.html.php プロジェクト: kosmosby/medicine-prof
 function display($tpl = null)
 {
     global $globalcats;
     $app = JFactory::getApplication();
     $option = JRequest::getVar('option');
     //initialise variables
     $db = JFactory::getDBO();
     $document = JFactory::getDocument();
     $template = $app->isSite() ? !FLEXI_J16GE ? 'khepri' : (FLEXI_J30GE ? 'hathor' : 'bluestork') : $app->getTemplate();
     JHTML::_('behavior.tooltip');
     JHTML::_('behavior.modal');
     //get var
     $filter_order = $app->getUserStateFromRequest($option . '.itemelement.filter_order', 'filter_order', 'i.ordering', 'cmd');
     $filter_order_Dir = $app->getUserStateFromRequest($option . '.itemelement.filter_order_Dir', 'filter_order_Dir', '', 'word');
     $filter_state = $app->getUserStateFromRequest($option . '.itemelement.filter_state', 'filter_state', '*', 'word');
     $filter_cats = $app->getUserStateFromRequest($option . '.itemelement.filter_cats', 'filter_cats', 0, 'int');
     $filter_type = $app->getUserStateFromRequest($option . '.itemelement.filter_type', 'filter_type', 0, 'int');
     if (FLEXI_FISH || FLEXI_J16GE) {
         $filter_lang = $app->getUserStateFromRequest($option . '.itemelement.filter_lang', 'filter_lang', '', 'cmd');
     }
     $search = $app->getUserStateFromRequest($option . '.itemelement.search', 'search', '', 'string');
     $search = FLEXI_J16GE ? $db->escape(trim(JString::strtolower($search))) : $db->getEscaped(trim(JString::strtolower($search)));
     //prepare the document
     $document->setTitle(JText::_('FLEXI_SELECTITEM'));
     $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/flexicontentbackend.css');
     if (FLEXI_J30GE) {
         $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j3x.css');
     } else {
         if (FLEXI_J16GE) {
             $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j25.css');
         } else {
             $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j15.css');
         }
     }
     $document->addStyleSheet(JURI::root() . 'administrator/templates/' . $template . (FLEXI_J16GE ? '/css/template.css' : '/css/general.css'));
     //Get data from the model
     $rows = $this->get('Data');
     $types = $this->get('Typeslist');
     $pageNav = $this->get('Pagination');
     if (FLEXI_FISH || FLEXI_J16GE) {
         $langs = FLEXIUtilities::getLanguages('code');
     }
     // build the categories select list for filter
     $categories = $globalcats;
     $lists['filter_cats'] = flexicontent_cats::buildcatselect($categories, 'filter_cats', $filter_cats, 2, 'class="inputbox" size="1" onchange="submitform( );"', $actions_allowed = array('core.create'), true);
     // table ordering
     $lists['order_Dir'] = $filter_order_Dir;
     $lists['order'] = $filter_order;
     $ordering = $lists['order'] == 'i.ordering';
     //build type select list
     $lists['filter_type'] = flexicontent_html::buildtypesselect($types, 'filter_type', $filter_type, true, 'class="inputbox" size="1" onchange="submitform( );"', 'filter_type');
     // search filter
     $lists['search'] = $search;
     $state[] = JHTML::_('select.option', '', JText::_('FLEXI_SELECT_STATE'));
     $state[] = JHTML::_('select.option', 'P', JText::_('FLEXI_PUBLISHED'));
     $state[] = JHTML::_('select.option', 'U', JText::_('FLEXI_UNPUBLISHED'));
     $state[] = JHTML::_('select.option', 'PE', JText::_('FLEXI_PENDING'));
     $state[] = JHTML::_('select.option', 'OQ', JText::_('FLEXI_TO_WRITE'));
     $state[] = JHTML::_('select.option', 'IP', JText::_('FLEXI_IN_PROGRESS'));
     $state[] = JHTML::_('select.option', 'A', JText::_('FLEXI_ARCHIVED'));
     $lists['state'] = JHTML::_('select.genericlist', $state, 'filter_state', 'class="inputbox" size="1" onchange="submitform( );"', 'value', 'text', $filter_state);
     if (FLEXI_FISH || FLEXI_J16GE) {
         //build languages filter
         $lists['filter_lang'] = flexicontent_html::buildlanguageslist('filter_lang', 'class="inputbox" onchange="submitform();"', $filter_lang, 2);
     }
     //assign data to template
     if (FLEXI_FISH || FLEXI_J16GE) {
         $this->assignRef('langs', $langs);
     }
     $this->assignRef('lists', $lists);
     $this->assignRef('rows', $rows);
     $this->assignRef('pageNav', $pageNav);
     $this->assignRef('ordering', $ordering);
     $this->assignRef('filter_cats', $filter_cats);
     parent::display($tpl);
 }
コード例 #28
0
ファイル: view.html.php プロジェクト: kosmosby/medicine-prof
 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('&', '&amp;', $popup_load_url), 600, 440);
     }
     //if (FLEXI_J16GE)
     //	$toolbar->appendButton('Popup', 'move', JText::_('FLEXI_COPY_MOVE'), JURI::base().'index.php?option=com_flexicontent&amp;view=categories&amp;layout=batch&amp;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);
 }
コード例 #29
0
ファイル: item.php プロジェクト: khetsothea/flexicontent-cck
 /**
  * Method to CHECK item's -VIEWING- ACCESS, this could be moved to the controller,
  * if we do this, then we must check the view variable, because DISPLAY() CONTROLLER TASK
  * is shared among all views ... or create a separate FRONTEND controller for the ITEM VIEW
  *
  * @access	private
  * @return	array
  * @since	1.5
  */
 function _check_viewing_access($version = false)
 {
     global $globalcats;
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     $session = JFactory::getSession();
     $aid = (int) $user->get('aid');
     $gid = (int) $user->get('gid');
     $cid = $this->_cid;
     $params = $this->_item->parameters;
     $cparams = $this->_cparams;
     $fcreturn = serialize(array('id' => @$this->_item->id, 'cid' => $cid));
     // a special url parameter, used by some SEF code
     $referer = @$_SERVER['HTTP_REFERER'];
     // the previously viewed page (refer)
     if (!flexicontent_html::is_safe_url($referer)) {
         $referer = JURI::base();
     }
     // Ignore it if potentially non safe URL, e.g. non-internal
     // a basic item title string
     $title_str = "<br />" . JText::_('FLEXI_TITLE') . ": " . $this->_item->title . '[id: ' . $this->_item->id . ']';
     // Since we will check access for VIEW (=read) only, we skip checks if TASK Variable is set,
     // the edit() or add() or other controller task, will be responsible for checking permissions.
     if (@$this->_item->id && !JRequest::getVar('task', false) && JRequest::getVar('view') == FLEXI_ITEMVIEW) {
         //*************************************************************
         // STEP A: Calculate ownership, edit permission and read access
         // (a) isOwner, (b) canedititem, (c) canviewitem
         //*************************************************************
         // (a) Calculate if owned by current user
         $isOwner = $this->_item->created_by == $user->get('id');
         // (b) Calculate edit access ...
         // NOTE: we will allow view access if current user can edit the item (but set a warning message about it, see bellow)
         $canedititem = $params->get('access-edit');
         $caneditstate = $params->get('access-edit-state');
         if (!$caneditstate) {
             // Item not editable, check if item is editable till logoff
             if ($session->has('rendered_uneditable', 'flexicontent')) {
                 $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
                 $canedititem = isset($rendered_uneditable[$this->_item->id]);
             }
         }
         // (c) Calculate read access ... also considering the access level of parent categories
         $_cid_ = $cid ? $cid : $this->_item->catid;
         if (!isset($this->_item->ancestor_cats_accessible)) {
             $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
             $allowed_levels = array_flip($aid_arr);
             $catshelper = new flexicontent_cats($_cid_);
             $parents = $catshelper->getParentlist($all_cols = false);
             $ancestor_cats_accessible = true;
             foreach ($parents as $parent) {
                 if (!isset($allowed_levels[$parent->access])) {
                     $ancestor_cats_accessible = false;
                     break;
                 }
             }
             $this->_item->ancestor_cats_accessible = $ancestor_cats_accessible;
         }
         $canviewitem = $params->get('access-view') && $this->_item->ancestor_cats_accessible;
         // *********************************************************************************************
         // STEP B: Calculate SOME ITEM PUBLICATION STATE FLAGS, used to decide if current item is active
         // FLAGS: item_is_published, item_is_scheduled, item_is_expired, ancestor_cats_published
         // *********************************************************************************************
         $item_is_published = $this->_item->state == 1 || $this->_item->state == -5 || $this->_item->state == (FLEXI_J16GE ? 2 : -1);
         $item_is_scheduled = $this->_item->publication_scheduled;
         $item_is_expired = $this->_item->publication_expired;
         if ($cid) {
             // cid is set, check state of current item category only
             // NOTE:  J1.6+ all ancestor categories from current one to the root, for J1.5 only the current one ($cid)
             if (!isset($this->_item->ancestor_cats_published)) {
                 $ancestor_cats_published = true;
                 foreach ($globalcats[$cid]->ancestorsarray as $pcid) {
                     $ancestor_cats_published = $ancestor_cats_published && $globalcats[$pcid]->published == 1;
                 }
                 $this->_item->ancestor_cats_published = $ancestor_cats_published;
             }
             $ancestor_cats_published = $this->_item->ancestor_cats_published;
             //$this->_item->catpublished;
             $cats_np_err_mssg = JText::sprintf('FLEXI_CONTENT_UNAVAILABLE_ITEM_CURRCAT_UNPUBLISHED', $cid);
         } else {
             // cid is not set, we have no current category, the item is visible if it belongs to at one published category
             $itemcats = $this->_item->categories;
             $ancestor_cats_published = true;
             foreach ($itemcats as $catid) {
                 if (!isset($globalcats[$catid])) {
                     continue;
                 }
                 $ancestor_cats_published |= $globalcats[$catid]->published;
                 // For J1.6+ check all ancestor categories from current one to the root
                 foreach ($globalcats[$catid]->ancestorsarray as $pcid) {
                     $ancestor_cats_published = $ancestor_cats_published && $globalcats[$pcid]->published == 1;
                 }
             }
             $cats_np_err_mssg = JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_ALLCATS_UNPUBLISHED');
         }
         // Calculate if item is active ... and viewable is also it's (current or All) categories are published
         $item_active = $item_is_published && !$item_is_scheduled && !$item_is_expired;
         $item_n_cat_active = $item_active && $ancestor_cats_published;
         $previewing_and_unlogged = $version && $user->guest;
         // this is a flag indicates to redirect to login instead of 404 error
         $ignore_publication = $canedititem || $caneditstate || $isOwner || $previewing_and_unlogged;
         $inactive_notice_set = false;
         $item_state_pending = $this->_item->state == -3;
         $item_state_draft = $this->_item->state == -4;
         //***********************************************************************************************************************
         // STEP C: CHECK item state, if publication state is not ignored terminate with 404 NOT found, otherwise add a notice
         // NOTE: Asking all users to login when item is not active maybe wrong approach, so instead we raise 404 error, but we
         // will ask them to login only if previewing a latest or specific version (so ignore publication FLAG includes this case)
         // (a) Check that item is PUBLISHED (1,-5) or ARCHIVED (-1)
         // (b) Check that item has expired publication date
         // (c) Check that item has scheduled publication date
         // (d) Check that current item category or all items categories are published
         //***********************************************************************************************************************
         // (a) Check that item is PUBLISHED (1,-5) or ARCHIVED (-1)
         if (!$caneditstate && ($item_state_pending || $item_state_draft) && $isOwner) {
             // SPECIAL workflow case, regardless of (view/edit privilege), allow users to view unpublished owned content, (a) if waiting for approval, or (b) if can request approval
             $inactive_notice_set = true;
         } else {
             if (!$item_is_published && !$ignore_publication) {
                 // Raise error that the item is unpublished
                 $msg = JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_UNPUBLISHED') . $title_str;
                 if (FLEXI_J16GE) {
                     throw new Exception($msg, 404);
                 } else {
                     JError::raiseError(404, $msg);
                 }
             } else {
                 if (!$item_is_published && !$inactive_notice_set) {
                     // Item edittable, set warning that ...
                     JError::raiseNotice(404, JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_UNPUBLISHED'));
                     $inactive_notice_set = true;
                 }
             }
         }
         // NOTE: First, we check for expired publication, since if item expired, scheduled publication is meaningless
         // (b) Check that item has expired publication date
         if ($item_is_expired && !$ignore_publication) {
             // Raise error that the item is scheduled for publication
             $msg = JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_EXPIRED') . $title_str;
             if (FLEXI_J16GE) {
                 throw new Exception($msg, 404);
             } else {
                 JError::raiseError(404, $msg);
             }
         } else {
             if ($item_is_expired && !$inactive_notice_set) {
                 // Item edittable, set warning that ...
                 JError::raiseNotice(404, JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_EXPIRED'));
                 $inactive_notice_set = true;
             }
         }
         // (c) Check that item has scheduled publication date
         if ($item_is_scheduled && !$ignore_publication) {
             // Raise error that the item is scheduled for publication
             $msg = JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_SCHEDULED') . $title_str;
             if (FLEXI_J16GE) {
                 throw new Exception($msg, 404);
             } else {
                 JError::raiseError(404, $msg);
             }
         } else {
             if ($item_is_scheduled && !$inactive_notice_set) {
                 // Item edittable, set warning that ...
                 JError::raiseNotice(404, JText::_('FLEXI_CONTENT_UNAVAILABLE_ITEM_SCHEDULED'));
                 $inactive_notice_set = true;
             }
         }
         // (d) Check that current item category or all items categories are published
         if (!$ancestor_cats_published && !$ignore_publication) {
             // Terminate execution with a HTTP not-found Server Error
             $msg = $cats_np_err_mssg . $title_str;
             if (FLEXI_J16GE) {
                 throw new Exception($msg, 404);
             } else {
                 JError::raiseError(404, $msg);
             }
         } else {
             if (!$ancestor_cats_published && !$inactive_notice_set) {
                 // Item edittable, set warning that item's (ancestor) category is unpublished
                 JError::raiseNotice(404, $cats_np_err_mssg);
                 $inactive_notice_set = true;
             }
         }
         //*******************************************************************************************
         // STEP D: CHECK viewing access in relation to if user being logged and being owner / editor
         // (a) redirect user previewing a non-current item version, to either current item version or to refer if has no edit permission
         // (b) redirect item owner to previous page if user has no access (read/edit) to the item
         // (c) redirect unlogged user to login, so that user can possible login to privileged account
         // (d) redirect unauthorized logged user to the unauthorized page (if this is set)
         // (e) finally raise a 403 forbidden Server Error if user is unauthorized to access item
         //*******************************************************************************************
         // SPECIAL case when previewing an non-current version of an item, this is allowed only if user can edit the item
         $current_version = FLEXIUtilities::getCurrentVersions($this->_id, true);
         // Get current item version
         if ($version && $version != $current_version && !$canedititem && !$previewing_and_unlogged) {
             // (a) redirect user previewing a non-current item version, to either current item version or to refer if has no edit permission
             JError::raiseNotice(403, JText::_('FLEXI_ALERTNOTAUTH_PREVIEW_UNEDITABLE') . "<br />" . JText::_('FLEXI_ALERTNOTAUTH_TASK'));
             if ($item_n_cat_active && $canviewitem) {
                 $app->redirect(JRoute::_(FlexicontentHelperRoute::getItemRoute($this->_item->slug, $this->_item->categoryslug, 0, $this->_item)));
             } else {
                 $app->redirect($referer);
                 // Item not viewable OR no view access, redirect to refer page
             }
         } else {
             if (!$item_n_cat_active && !$previewing_and_unlogged) {
                 if (!$caneditstate && ($item_state_pending || $item_state_draft) && $isOwner) {
                     // no redirect, SET message to owners, to wait for approval or to request approval of their content
                     $app->enqueueMessage(JText::_($item_state_pending ? 'FLEXI_ALERT_VIEW_OWN_PENDING_STATE' : 'FLEXI_ALERT_VIEW_OWN_DRAFT_STATE'), 'notice');
                 } else {
                     if (!$canedititem && !$caneditstate && $isOwner) {
                         // (b) redirect item owner to previous page if user cannot access (read/edit) the item
                         JError::raiseNotice(403, JText::_($item_state_pending ? 'FLEXI_ALERTNOTAUTH_VIEW_OWN_PENDING' : 'FLEXI_ALERTNOTAUTH_VIEW_OWN_UNPUBLISHED'));
                         $app->redirect($referer);
                     } else {
                         if ($canedititem || $caneditstate) {
                             // no redirect, SET notice to the editors, that they are viewing unreadable content because they can edit the item
                             $app->enqueueMessage(JText::_('FLEXI_CONTENT_ACCESS_ALLOWED_BECAUSE_EDITABLE_PUBLISHABLE'), 'notice');
                         } else {
                             $app->enqueueMessage('INTERNAL ERROR: item inactive but checks were ignored despite current user not begin item owner or item assigned editor', 'notice');
                             $app->redirect($referer);
                         }
                     }
                 }
             } else {
                 if (!$canviewitem && !$canedititem || !$item_n_cat_active) {
                     if ($user->guest) {
                         // (c) redirect unlogged user to login, so that user can possible login to privileged account
                         $uri = JFactory::getURI();
                         $return = $uri->toString();
                         $com_users = FLEXI_J16GE ? 'com_users' : 'com_user';
                         $url = $cparams->get('login_page', 'index.php?option=' . $com_users . '&view=login');
                         $return = strtr(base64_encode($return), '+/=', '-_,');
                         $url .= '&return=' . $return;
                         //$url .= '&return='.base64_encode($return);
                         $url .= '&fcreturn=' . base64_encode($fcreturn);
                         JError::raiseWarning(403, JText::sprintf("FLEXI_LOGIN_TO_ACCESS", $url));
                         $app->redirect($url);
                     } else {
                         $msg = JText::_('FLEXI_ALERTNOTAUTH_VIEW');
                         $msg .= $item->type_id && !$this->_item->has_type_access ? "<br/>" . JText::_("FLEXI_ALERTNOTAUTH_VIEW_TYPE") : '';
                         $msg .= $item->catid && !$this->_item->has_mcat_access ? "<br/>" . JText::_("FLEXI_ALERTNOTAUTH_VIEW_MCAT") : '';
                         $msg .= $cid && !$this->_item->ancestor_cats_accessible ? "<br/>" . JText::_("FLEXI_ALERTNOTAUTH_VIEW_MCAT") : '';
                         if ($cparams->get('unauthorized_page', '')) {
                             // (d) redirect unauthorized logged user to the unauthorized page (if this is set)
                             JError::raiseNotice(403, $msg);
                             $app->redirect($cparams->get('unauthorized_page'));
                         } else {
                             // (e) finally raise a 403 forbidden Server Error if user is unauthorized to access item
                             if (FLEXI_J16GE) {
                                 throw new Exception($msg, 403);
                             } else {
                                 JError::raiseError(403, $msg);
                             }
                         }
                     }
                 } else {
                 }
             }
         }
     }
     // End of Existing item (not new)
 }