Exemplo n.º 1
0
 function display($tpl = null)
 {
     $user = JFactory::getUser();
     $dispatcher = JDispatcher::getInstance();
     // Initialize some variables
     $item =& $this->get('Item');
     $params =& $item->parameters;
     $fields =& $this->get('Extrafields');
     $tags =& $item->tags;
     $categories =& $item->categories;
     $favourites = $item->favourites;
     $favoured = $item->favoured;
     // process the new plugins
     JPluginHelper::importPlugin('content', 'image');
     if (!FLEXI_J16GE) {
         $dispatcher->trigger('onPrepareContent', array(&$item, &$params, 0));
     } else {
         $dispatcher->trigger('onContentPrepare', array('com_content.article', &$item, &$params, 0));
     }
     $document = JFactory::getDocument();
     // set document information
     $document->setTitle($item->title);
     $document->setName($item->alias);
     $document->setDescription($item->metadesc);
     $document->setMetaData('keywords', $item->metakey);
     // prepare header lines
     $document->setHeader($this->_getHeaderText($item, $params));
     $pdf_format_fields = trim($params->get("pdf_format_fields"));
     $pdf_format_fields = !$pdf_format_fields ? array() : preg_split("/[\\s]*,[\\s]*/", $pdf_format_fields);
     $methodnames = array();
     foreach ($pdf_format_fields as $pdf_format_field) {
         @(list($fieldname, $methodname) = preg_split("/[\\s]*:[\\s]*/", $pdf_format_field));
         $methodnames[$fieldname] = empty($methodname) ? 'display' : $methodname;
     }
     // IF no fields set then just print the item's description text
     if (!count($pdf_format_fields)) {
         echo $item->text;
         return;
     }
     foreach ($fields as $field) {
         if (!isset($methodnames[$field->name])) {
             continue;
         }
         if ($field->iscore) {
             FlexicontentFields::loadFieldConfig($field, $item);
             //$results = $dispatcher->trigger('onDisplayCoreFieldValue', array( &$field, $item, &$params, $tags, $categories, $favourites, $favoured ));
             FLEXIUtilities::call_FC_Field_Func('core', 'onDisplayCoreFieldValue', array(&$field, $item, &$params, $tags, $categories, $favourites, $favoured));
         } else {
             //$results = $dispatcher->trigger('onDisplayFieldValue', array( &$field, $item ));
             FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
         }
         if (@$field->display) {
             echo '<b>' . $field->label . '</b>: ';
             echo $field->display . '<br /><br />';
         }
     }
 }
Exemplo n.º 2
0
 function display($tpl = null)
 {
     $mainframe = JFactory::getApplication();
     $option = JRequest::getVar('option');
     //initialise variables
     $db = JFactory::getDBO();
     $document = JFactory::getDocument();
     $template = $mainframe->getTemplate();
     $dispatcher = JDispatcher::getInstance();
     $rev = JRequest::getInt('version', '', 'request');
     $codemode = JRequest::getInt('codemode', 0);
     $cparams = JComponentHelper::getParams('com_flexicontent');
     FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
     flexicontent_html::loadFramework('jQuery');
     JHTML::_('behavior.tooltip');
     JHTML::_('behavior.modal');
     //a trick to avoid loosing general style in modal window
     $css = 'body, td, th { font-size: 11px; } .novalue { color: gray; font-style: italic; }';
     $document->addStyleDeclaration($css);
     //Get data from the model
     $model = $this->getModel();
     $row = $this->get('Item');
     $fields = $this->get('Extrafields');
     $versions = $this->get('VersionList');
     $tparams = $this->get('Typeparams');
     // Create the type parameters
     $tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
     // Add html to field object trought plugins
     foreach ($fields as $field) {
         if ($field->value) {
             //$results = $dispatcher->trigger('onDisplayFieldValue', array( &$field, $row ));
             $fieldname = $field->iscore ? 'core' : $field->field_type;
             FLEXIUtilities::call_FC_Field_Func($fieldname, 'onDisplayFieldValue', array(&$field, $row));
         } else {
             $field->display = '<span class="novalue">' . JText::_('FLEXI_NO_VALUE') . '</span>';
         }
         if ($field->version) {
             //$results = $dispatcher->trigger('onDisplayFieldValue', array( &$field, $row, $field->version, 'displayversion' ));
             $fieldname = $field->iscore ? 'core' : $field->field_type;
             FLEXIUtilities::call_FC_Field_Func($fieldname, 'onDisplayFieldValue', array(&$field, $row, $field->version, 'displayversion'));
         } else {
             $field->displayversion = '<span class="novalue">' . JText::_('FLEXI_NO_VALUE') . '</span>';
         }
     }
     //assign data to template
     $this->assignRef('document', $document);
     $this->assignRef('row', $row);
     $this->assignRef('fields', $fields);
     $this->assignRef('versions', $versions);
     $this->assignRef('rev', $rev);
     $this->assignRef('tparams', $tparams);
     $this->assignRef('cparams', $cparams);
     $this->assignRef('codemode', $codemode);
     parent::display($tpl);
 }
Exemplo n.º 3
0
    /**
     * Creates the item submit form
     *
     * @since 1.0
     */
    function _displayForm($tpl)
    {
        jimport('joomla.html.parameter');
        // ... we use some strings from administrator part
        // load english language file for 'com_content' component then override with current language file
        JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR, 'en-GB', true);
        JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR, null, true);
        // load english language file for 'com_flexicontent' component then override with current language file
        JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, 'en-GB', true);
        JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, null, true);
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $uri = JFactory::getURI();
        $nullDate = $db->getNullDate();
        $menu = $app->getMenu()->getActive();
        // We do not have item parameters yet, but we need to do some work before creating the item
        // Get the COMPONENT only parameter
        $params = new JRegistry();
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $params->merge($cparams);
        // Merge the active menu parameters
        if ($menu) {
            $params->merge($menu->params);
        }
        // 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
        // *****************
        FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
        flexicontent_html::loadFramework('jQuery');
        flexicontent_html::loadFramework('select2');
        flexicontent_html::loadFramework('flexi-lib');
        // Load custom behaviours: form validation, popup tooltips
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        JHTML::_('behavior.tooltip');
        if (FLEXI_J30GE) {
            JHtml::_('bootstrap.tooltip');
        }
        //JHTML::_('script', 'joomla.javascript.js', 'includes/js/');
        // Add css files to the document <head> section (also load CSS joomla template override)
        $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontent.css');
        if (file_exists(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css')) {
            $document->addStyleSheet($this->baseurl . '/templates/' . $app->getTemplate() . '/css/flexicontent.css');
        }
        // Fields common CSS
        $document->addStyleSheet($this->baseurl . '/components/com_flexicontent/assets/css/flexi_form_fields.css');
        // Load backend / frontend shared and Joomla version specific CSS (different for frontend / backend)
        FLEXI_J30GE ? $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css') : $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j25.css');
        // Add js function to overload the joomla submitform
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/admin.js');
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/validate.js');
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/itemscreen.js');
        // *********************************************************
        // Get item data and create item form (that loads item data)
        // *********************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        // ** WE NEED TO get OR decide the Content Type, before we call the getItem
        // ** We rely on typeid Request variable to decide type for new items so make sure this is set,
        // ZERO means allow user to select type, but if user is only allowed a single type, then autoselect it!
        // Try type from session
        $jdata = $app->getUserState('com_flexicontent.edit.item.data');
        //print_r($jdata);
        if (!empty($jdata['type_id'])) {
            JRequest::setVar('typeid', (int) $jdata['type_id']);
            // This also forces zero if value not set
        } else {
            if ($menu && isset($menu->query['typeid'])) {
                JRequest::setVar('typeid', (int) $menu->query['typeid']);
                // This also forces zero if value not set
            }
        }
        $new_typeid = JRequest::getVar('typeid', 0, '', 'int');
        // Verify type is allowed to the user
        if (!$new_typeid) {
            $types = $model->getTypeslist($type_ids_arr = false, $check_perms = true, $_published = true);
            if ($types && count($types) == 1) {
                $new_typeid = $types[0]->id;
            }
            JRequest::setVar('typeid', $new_typeid);
            $canCreateType = true;
        }
        // FORCE model to load versioned data (URL specified version or latest version (last saved))
        $version = JRequest::getVar('version', 0, 'request', 'int');
        // Load specific item version (non-zero), 0 version: is unversioned data, -1 version: is latest version (=default for edit form)
        $item = $model->getItem(null, $check_view_access = false, $no_cache = true, $force_version = $version != 0 ? $version : -1);
        // -1 version means latest
        // Replace component/menu 'params' with thee merged component/category/type/item/menu ETC ... parameters
        $params =& $item->parameters;
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // Load permissions (used by form template)
        $perms = $this->_getItemPerms($item);
        // Create submit configuration (for new items) into the session, this is needed before creating the item form
        $submitConf = $this->_createSubmitConf($item, $perms);
        // Most core field are created via calling methods of the form (J2.5)
        $form = $this->get('Form');
        // is new item and ownership Flags
        $isnew = !$item->id;
        $isOwner = $item->created_by == $user->get('id');
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get type parameters, these are needed besides the 'merged' item parameters, e.g. to get Type's default layout
        $tparams = $this->get('Typeparams');
        $tparams = new JRegistry($tparams);
        // *********************************************************************************************************
        // Get language stuff, and also load Template-Specific language file to override or add new language strings
        // *********************************************************************************************************
        if ($enable_translation_groups) {
            $langAssocs = $params->get('uselang_fe') == 1 ? $this->get('LangAssocs') : false;
        }
        $langs = FLEXIUtilities::getLanguages('code');
        FLEXIUtilities::loadTemplateLanguageFile($params->get('ilayout', 'default'));
        // *************************************
        // Create captcha field via custom logic
        // *************************************
        // create and set (into HTTP request) a unique item id for plugins that needed it
        if ($item->id) {
            $unique_tmp_itemid = $item->id;
        } 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);
        // Component / Menu Item parameters
        $allowunauthorize = $params->get('allowunauthorize', 0);
        // allow unauthorised user to submit new content
        $unauthorized_page = $params->get('unauthorized_page', '');
        // page URL for unauthorized users (via global configuration)
        $notauth_itemid = $params->get('notauthurl', '');
        // menu itemid (to redirect) when user is not authorized to create content
        // Create captcha field or messages
        // Maybe some code can be removed by using Joomla's built-in form element (in XML file), instead of calling the captcha plugin ourselves
        $use_captcha = $params->get('use_captcha', 1);
        // 1 for guests, 2 for any user
        $captcha_formop = $params->get('captcha_formop', 0);
        // 0 for submit, 1 for submit/edit (aka always)
        $display_captcha = $use_captcha >= 2 || $use_captcha == 1 && $user->guest;
        $display_captcha = $display_captcha && ($isnew || $captcha_formop);
        // Trigger the configured captcha plugin
        if ($display_captcha) {
            // Get configured captcha plugin
            $c_plugin = $params->get('captcha', $app->getCfg('captcha'));
            // TODO add param to override default
            if ($c_plugin) {
                $c_name = 'captcha_response_field';
                $c_id = $c_plugin == 'recaptcha' ? 'dynamic_recaptcha_1' : 'fc_dynamic_captcha';
                $c_class = ' required';
                $c_namespace = 'fc_item_form';
                // Try to load the configured captcha plugin, (check if disabled or uninstalled), Joomla will enqueue an error message if needed
                $captcha_obj = JCaptcha::getInstance($c_plugin, array('namespace' => $c_namespace));
                if ($captcha_obj) {
                    $captcha_field = $captcha_obj->display($c_name, $c_id, $c_class);
                    $label_class = 'flexi_label';
                    $label_class .= FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
                    $label_tooltip = flexicontent_html::getToolTip(null, 'FLEXI_CAPTCHA_ENTER_CODE_DESC', 1, 1);
                    $captcha_field = '
						<label id="' . $c_name . '-lbl" for="' . $c_name . '" class="' . $label_class . '" title="' . $label_tooltip . '" >
						' . JText::_('FLEXI_CAPTCHA_ENTER_CODE') . '
						</label>
						<div id="container_fcfield_' . $c_plugin . '" class="container_fcfield container_fcfield_name_' . $c_plugin . '">
							<div class="fcfieldval_container valuebox fcfieldval_container_' . $c_plugin . '">
							' . $captcha_field . '
							</div>
						</div>';
                }
            }
        }
        // *******************************
        // CHECK EDIT / CREATE PERMISSIONS
        // *******************************
        // User Group / Author parameters
        $authorparams = flexicontent_db::getUserConfig($user->id);
        $max_auth_limit = intval($authorparams->get('max_auth_limit', 0));
        // maximum number of content items the user can create
        $hasTmpEdit = false;
        $hasCoupon = false;
        // Check session
        if ($session->has('rendered_uneditable', 'flexicontent')) {
            $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
            $hasTmpEdit = !empty($rendered_uneditable[$model->get('id')]);
            $hasCoupon = !empty($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')] == 2;
            // editable via coupon
        }
        if (!$isnew) {
            // EDIT action
            // Finally check if item is currently being checked-out (currently being edited)
            if ($model->isCheckedOut($user->get('id'))) {
                $msg = JText::sprintf('FLEXI_DESCBEINGEDITTED', $model->get('title'));
                $app->redirect(JRoute::_('index.php?view=' . FLEXI_ITEMVIEW . '&cid=' . $model->get('catid') . '&id=' . $model->get('id'), false), $msg);
            }
            //Checkout the item
            $model->checkout();
            // Get edit access, this includes privileges edit and edit-own and the temporary EDIT flag ('rendered_uneditable')
            $canEdit = $model->getItemAccess()->get('access-edit');
            // If no edit privilege, check if edit COUPON was provided
            if (!$canEdit) {
                $edittok = JRequest::getCmd('edittok', false);
                if ($edittok) {
                    $query = 'SHOW TABLES LIKE "' . $app->getCfg('dbprefix') . 'flexicontent_edit_coupons"';
                    $db->setQuery($query);
                    $tbl_exists = (bool) count($db->loadObjectList());
                    if ($tbl_exists) {
                        $query = 'SELECT * FROM #__flexicontent_edit_coupons ' . ' WHERE token = ' . $db->Quote($edittok) . ' AND id = ' . $model->get('id');
                        $db->setQuery($query);
                        $tokdata = $db->loadObject();
                        if ($tokdata) {
                            $hasCoupon = true;
                            $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
                            $rendered_uneditable[$model->get('id')] = 2;
                            // 2: indicates, that has edit via EDIT Coupon
                            $session->set('rendered_uneditable', $rendered_uneditable, 'flexicontent');
                            $canEdit = 1;
                        } else {
                            JError::raiseNotice(403, JText::_('EDIT_TOKEN_IS_INVALID') . ' : ' . $edittok);
                        }
                    }
                }
            }
            // Edit check finished, throw error if needed
            if (!$canEdit) {
                if ($user->guest) {
                    $uri = JFactory::getURI();
                    $return = $uri->toString();
                    $fcreturn = serialize(array('id' => @$this->_item->id, 'cid' => $cid));
                    // a special url parameter, used by some SEF code
                    $com_users = FLEXI_J16GE ? 'com_users' : 'com_user';
                    $url = $params->get('login_page', 'index.php?option=' . $com_users . '&view=login');
                    $return = strtr(base64_encode($return), '+/=', '-_,');
                    $url .= '&return=' . $return;
                    //$url .= '&return='.urlencode(base64_encode($return));
                    $url .= '&fcreturn=' . base64_encode($fcreturn);
                    JError::raiseWarning(403, JText::sprintf("FLEXI_LOGIN_TO_ACCESS", $url));
                    $app->redirect($url);
                } else {
                    if ($unauthorized_page) {
                        //  unauthorized page via global configuration
                        JError::raiseNotice(403, JText::_('FLEXI_ALERTNOTAUTH_TASK'));
                        $app->redirect($unauthorized_page);
                    } else {
                        // user isn't authorize to edit this content
                        $msg = JText::_('FLEXI_ALERTNOTAUTH_TASK');
                        if (FLEXI_J16GE) {
                            throw new Exception($msg, 403);
                        } else {
                            JError::raiseError(403, $msg);
                        }
                    }
                }
            }
        } else {
            // CREATE action
            // Get create access, this includes check of creating in at least one category, and type's "create items"
            $canAdd = $model->getItemAccess()->get('access-create');
            $not_authorised = !$canAdd;
            // Check if Content Type can be created by current user
            if (empty($canCreateType)) {
                if ($new_typeid) {
                    // not needed, already done be model when type_id is set, check and remove
                    $canCreateType = $model->canCreateType(array($new_typeid));
                    // Can create given Content Type
                } else {
                    // needed not done be model yet
                    $canCreateType = $model->canCreateType();
                    // Can create at least one Content Type
                }
            }
            $not_authorised = $not_authorised || !$canCreateType;
            // Allow item submission by unauthorized users, ... even guests ...
            if ($allowunauthorize == 2) {
                $allowunauthorize = !$user->guest;
            }
            if ($not_authorised && !$allowunauthorize) {
                if (!$canCreateType) {
                    $type_name = isset($types[$new_typeid]) ? '"' . JText::_($types[$new_typeid]->name) . '"' : JText::_('FLEXI_ANY');
                    $msg = JText::sprintf('FLEXI_NO_ACCESS_CREATE_CONTENT_OF_TYPE', $type_name);
                } else {
                    $msg = JText::_('FLEXI_ALERTNOTAUTH_CREATE');
                }
            } else {
                if ($max_auth_limit) {
                    $db->setQuery('SELECT COUNT(id) FROM #__content WHERE created_by = ' . $user->id);
                    $authored_count = $db->loadResult();
                    $content_is_limited = $authored_count >= $max_auth_limit;
                    $msg = $content_is_limited ? JText::sprintf('FLEXI_ALERTNOTAUTH_CREATE_MORE', $max_auth_limit) : '';
                }
            }
            if ($not_authorised && !$allowunauthorize || @$content_is_limited) {
                // User isn't authorize to add ANY content
                if ($notauth_menu = $app->getMenu()->getItem($notauth_itemid)) {
                    // a. custom unauthorized submission page via menu item
                    $internal_link_vars = @$notauth_menu->component ? '&Itemid=' . $notauth_itemid . '&option=' . $notauth_menu->component : '';
                    $notauthurl = JRoute::_($notauth_menu->link . $internal_link_vars, false);
                    JError::raiseNotice(403, $msg);
                    $app->redirect($notauthurl);
                } else {
                    if ($unauthorized_page) {
                        // b. General unauthorized page via global configuration
                        JError::raiseNotice(403, $msg);
                        $app->redirect($unauthorized_page);
                    } else {
                        // c. Finally fallback to raising a 403 Exception/Error that will redirect to site's default 403 unauthorized page
                        if (FLEXI_J16GE) {
                            throw new Exception($msg, 403);
                        } else {
                            JError::raiseError(403, $msg);
                        }
                    }
                }
            }
        }
        // *****************************************************************************
        // Get (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'
        // *****************************************************************************
        // 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);
        //$modify_untraslatable_values = $enable_translation_groups && !$is_content_default_lang; // && $item->lang_parent_id && $item->lang_parent_id!=$item->id;
        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 = '<div class="alert alert-info fc-small fc-iblock">' . JText::_('FLEXI_FIELD_VALUE_IS_NON_TRANSLATABLE') . '</div>' . "\n" . $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;
        }
        // Tags used by the item
        $usedtagsids = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtagsdata = $model->getUsedtagsData($usedtagsids);
        // Get the edit lists
        $lists = $this->_buildEditLists($perms, $params, $authorparams);
        // Get number of subscribers
        $subscribers = $this->get('SubscribersCount');
        // Get menu overridden categories/main category fields
        $menuCats = $this->_getMenuCats($item, $perms);
        // Create placement configuration for CORE properties
        $placementConf = $this->_createPlacementConf($item, $fields);
        // Item language related vars
        $languages = FLEXIUtilities::getLanguages();
        $itemlang = new stdClass();
        $itemlang->shortcode = substr($item->language, 0, 2);
        $itemlang->name = $languages->{$item->language}->name;
        $itemlang->image = '<img src="' . @$languages->{$item->language}->imgsrc . '" alt="' . $languages->{$item->language}->name . '" />';
        //Load the JEditor object
        $editor = JFactory::getEditor();
        // **********************************************************
        // Calculate a (browser window) page title and a page heading
        // **********************************************************
        // Verify menu item points to current FLEXIcontent object
        if ($menu) {
            $menu_matches = false;
            $view_ok = FLEXI_ITEMVIEW == @$menu->query['view'] || 'article' == @$menu->query['view'];
            $menu_matches = $view_ok;
            //$menu_params = $menu->params;  // Get active menu item parameters
        } else {
            $menu_matches = false;
        }
        // MENU ITEM matched, use its page heading (but use menu title if the former is not set)
        if ($menu_matches) {
            $default_heading = FLEXI_J16GE ? $menu->title : $menu->name;
            // Cross set (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
            $params->def('page_heading', $params->get('page_title', $default_heading));
            $params->def('page_title', $params->get('page_heading', $default_heading));
            $params->def('show_page_heading', $params->get('show_page_title', 0));
            $params->def('show_page_title', $params->get('show_page_heading', 0));
        } else {
            // Calculate default page heading (=called page title in J1.5), which in turn will be document title below !! ...
            $default_heading = !$isnew ? JText::_('FLEXI_EDIT') : JText::_('FLEXI_NEW');
            // Decide to show page heading (=J1.5 page title), there is no need for this in item view
            $show_default_heading = 0;
            // Set both (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
            $params->set('page_title', $default_heading);
            $params->set('page_heading', $default_heading);
            $params->set('show_page_heading', $show_default_heading);
            $params->set('show_page_title', $show_default_heading);
        }
        // ************************************************************
        // Create the document title, by from page title and other data
        // ************************************************************
        // Use the page heading as document title, (already calculated above via 'appropriate' logic ...)
        $doc_title = $params->get('page_title');
        // Check and prepend or append site name
        // Add Site Name to page title
        if ($app->getCfg('sitename_pagetitles', 0) == 1) {
            $doc_title = $app->getCfg('sitename') . " - " . $doc_title;
        } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
            $doc_title = $doc_title . " - " . $app->getCfg('sitename');
        }
        // Finally, set document title
        $document->setTitle($doc_title);
        // Add title to pathway
        $pathway = $app->getPathWay();
        $pathway->addItem($doc_title, '');
        // Get pageclass suffix
        $pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
        // Ensure the row data is safe html
        // @TODO: check if this is really required as it conflicts with the escape function in the tmpl
        //JFilterOutput::objectHTMLSafe( $item );
        $this->assign('action', $uri->toString());
        $this->assignRef('item', $item);
        $this->assignRef('form', $form);
        // most core field are created via calling methods of the form (J2.5)
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        $this->assignRef('langs', $langs);
        $this->assignRef('params', $params);
        $this->assignRef('lists', $lists);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('editor', $editor);
        $this->assignRef('user', $user);
        $this->assignRef('usedtagsdata', $usedtagsdata);
        $this->assignRef('fields', $fields);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('perms', $perms);
        $this->assignRef('document', $document);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('menuCats', $menuCats);
        $this->assignRef('submitConf', $submitConf);
        $this->assignRef('placementConf', $placementConf);
        $this->assignRef('itemlang', $itemlang);
        $this->assignRef('pageclass_sfx', $pageclass_sfx);
        $this->assign('captcha_errmsg', @$captcha_errmsg);
        $this->assign('captcha_field', @$captcha_field);
        // ****************************************************************
        // SET INTO THE FORM, parameter values for various parameter groups
        // ****************************************************************
        if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $nullDate) {
            $item->publish_down = JText::_('FLEXI_NEVER');
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        }
        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) {
            if (FLEXI_J16GE) {
                $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
                $jform->load($tmpl->params);
                $tmpl->params = $jform;
                foreach ($tmpl->params->getGroup('attribs') as $field) {
                    $fieldname = $field->__get('fieldname');
                    $value = $item->itemparams->get($fieldname);
                    if (strlen($value)) {
                        $tmpl->params->setValue($fieldname, 'attribs', $value);
                    }
                }
            } else {
                $tmpl->params->loadINI($item->attribs);
            }
        }
        $this->assignRef('tmpls', $tmpls);
        // 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;
        }
    }
Exemplo n.º 4
0
 /**
  * Creates the page's display
  *
  * @since 1.0
  */
 function display($tpl = null)
 {
     //initialize variables
     $option = JRequest::getVar('option');
     $app = JFactory::getApplication();
     $document = JFactory::getDocument();
     $db = JFactory::getDBO();
     $menus = $app->getMenu();
     $menu = $menus->getActive();
     $uri = JFactory::getURI();
     $pathway = $app->getPathway();
     // Get view's Model
     $model = $this->getModel();
     $error = '';
     $rows = null;
     $total = 0;
     $form_id = $form_name = "searchForm";
     // Get parameters via model
     $params = $model->getParams();
     // Get various data from the model
     $areas = $this->get('areas');
     $state = $this->get('state');
     $searchword = $state->get('keyword');
     $searchphrase = $state->get('match');
     $searchordering = $state->get('ordering');
     // ***********************************************************
     // some parameter shortcuts common with advanced search plugin
     // ***********************************************************
     $canseltypes = $params->get('canseltypes', 1);
     $txtmode = $params->get('txtmode', 0);
     // 0: BASIC Index, 1: ADVANCED Index without search fields user selection, 2: ADVANCED Index with search fields user selection
     // Get if text searching according to specific (single) content type
     $show_txtfields = $params->get('show_txtfields', 1);
     //0:hide, 1:according to content, 2:use custom configuration
     $show_txtfields = $txtmode ? 0 : $show_txtfields;
     // disable this flag if using BASIC index for text search
     // Get if filtering according to specific (single) content type
     $show_filters = $params->get('show_filters', 1);
     //0:hide, 1:according to content, 2:use custom configuration
     // Force single type selection and showing the content type selector
     $type_based_search = $show_filters == 1 || $show_txtfields == 1;
     $canseltypes = $type_based_search ? 1 : $canseltypes;
     // ********************************
     // Load needed JS libs & CSS styles
     // ********************************
     FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
     flexicontent_html::loadFramework('jQuery');
     flexicontent_html::loadFramework('flexi_tmpl_common');
     // Add css files to the document <head> section (also load CSS joomla template override)
     if (!$params->get('disablecss', '')) {
         $document->addStyleSheetVersion($this->baseurl . '/components/com_flexicontent/assets/css/flexicontent.css', FLEXI_VERSION);
         $document->addStyleSheetVersion($this->baseurl . '/components/com_flexicontent/assets/css/flexi_filters.css', FLEXI_VERSION);
         //$document->addCustomTag('<!--[if IE]><style type="text/css">.floattext {zoom:1;}</style><![endif]-->');
     }
     if (file_exists(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css')) {
         $document->addStyleSheetVersion($this->baseurl . '/templates/' . $app->getTemplate() . '/css/flexicontent.css', FLEXI_VERSION);
     }
     // **********************************************************
     // Calculate a (browser window) page title and a page heading
     // **********************************************************
     // Verify menu item points to current FLEXIcontent object
     if ($menu) {
         $view_ok = 'search' == @$menu->query['view'];
         $menu_matches = $view_ok;
         //$menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);  // Get active menu item parameters
     } else {
         $menu_matches = false;
     }
     // MENU ITEM matched, use its page heading (but use menu title if the former is not set)
     if ($menu_matches) {
         $default_heading = FLEXI_J16GE ? $menu->title : $menu->name;
         // Cross set (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->def('page_heading', $params->get('page_title', $default_heading));
         $params->def('page_title', $params->get('page_heading', $default_heading));
         $params->def('show_page_heading', $params->get('show_page_title', 0));
         $params->def('show_page_title', $params->get('show_page_heading', 0));
     } else {
         // Clear some menu parameters
         //$params->set('pageclass_sfx',	'');  // CSS class SUFFIX is behavior, so do not clear it ?
         // Calculate default page heading (=called page title in J1.5), which in turn will be document title below !! ...
         // meta_params->get('page_title') is meant for <title> but let's use as ... default page heading
         $default_heading = JText::_('FLEXI_SEARCH');
         // Decide to show page heading (=J1.5 page title), this default to no
         $show_default_heading = 0;
         // Set both (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
         $params->set('page_title', $default_heading);
         $params->set('page_heading', $default_heading);
         $params->set('show_page_heading', $show_default_heading);
         $params->set('show_page_title', $show_default_heading);
     }
     // Prevent showing the page heading if ... currently no reason
     if (0) {
         $params->set('show_page_heading', 0);
         $params->set('show_page_title', 0);
     }
     // ************************************************************
     // Create the document title, by from page title and other data
     // ************************************************************
     // Use the page heading as document title, (already calculated above via 'appropriate' logic ...)
     $doc_title = $params->get('page_title');
     // Check and prepend or append site name to page title
     if ($doc_title != $app->getCfg('sitename')) {
         if ($app->getCfg('sitename_pagetitles', 0) == 1) {
             $doc_title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $doc_title);
         } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
             $doc_title = JText::sprintf('JPAGETITLE', $doc_title, $app->getCfg('sitename'));
         }
     }
     // Finally, set document title
     $document->setTitle($doc_title);
     // ************************
     // Set document's META tags
     // ************************
     // Workaround for Joomla not setting the default value for 'robots', so component must do it
     $app_params = $app->getParams();
     if ($_mp = $app_params->get('robots')) {
         $document->setMetadata('robots', $_mp);
     }
     // Overwrite with menu META data if menu matched
     if ($menu_matches) {
         if ($_mp = $menu->params->get('menu-meta_description')) {
             $document->setDescription($_mp);
         }
         if ($_mp = $menu->params->get('menu-meta_keywords')) {
             $document->setMetadata('keywords', $_mp);
         }
         if ($_mp = $menu->params->get('robots')) {
             $document->setMetadata('robots', $_mp);
         }
         if ($_mp = $menu->params->get('secure')) {
             $document->setMetadata('secure', $_mp);
         }
     }
     // ********************************************************************
     // Get Content Types allowed for user selection in the Search Form
     // Also retrieve their configuration, plus the currently selected types
     // ********************************************************************
     // Get them from configuration
     $contenttypes = $params->get('contenttypes', array());
     // Sanitize them
     $contenttypes = !is_array($contenttypes) ? array($contenttypes) : $contenttypes;
     $contenttypes = array_unique(array_map('intval', $contenttypes));
     // Make sure these are integers since we will be using them UNQUOTED
     // Force hidden content type selection if only 1 content type was initially configured
     $canseltypes = count($contenttypes) == 1 ? 0 : $canseltypes;
     // Type data and configuration (parameters), if no content types specified then all will be retrieved
     $typeData = flexicontent_db::getTypeData(implode(",", $contenttypes));
     $contenttypes = array();
     foreach ($typeData as $tdata) {
         $contenttypes[] = $tdata->id;
     }
     // Get Content Types to use either those currently selected in the Search Form, or those hard-configured in the search menu item
     if ($canseltypes) {
         $form_contenttypes = JRequest::getVar('contenttypes', array());
         // Sanitize them
         $form_contenttypes = !is_array($form_contenttypes) ? array($form_contenttypes) : $form_contenttypes;
         $form_contenttypes = array_unique(array_map('intval', $form_contenttypes));
         // Make sure these are integers since we will be using them UNQUOTED
         $_contenttypes = array_intersect($contenttypes, $form_contenttypes);
         if (!empty($_contenttypes)) {
             $contenttypes = $_contenttypes;
         }
         // catch empty case: no content types were given or not-allowed content types were passed
     }
     // Check for zero content type (can occur during sanitizing content ids to integers)
     if (!empty($contenttypes)) {
         foreach ($contenttypes as $i => $v) {
             if (!strlen($contenttypes[$i])) {
                 unset($contenttypes[$i]);
             }
         }
     }
     // Type based seach, get a single content type (first one, if more than 1 were given ...)
     if ($type_based_search && !empty($contenttypes)) {
         $single_contenttype = reset($contenttypes);
         $contenttypes = array($single_contenttype);
     } else {
         $single_contenttype = false;
     }
     // *************************************
     // Text Search Fields of the search form
     // *************************************
     if (!$txtmode) {
         $txtflds = array();
         $fields_text = array();
     } else {
         $txtflds = '';
         if ($show_txtfields) {
             if ($show_txtfields == 1) {
                 $txtflds = $single_contenttype ? $typeData[$single_contenttype]->params->get('searchable', '') : '';
             } else {
                 $txtflds = $params->get('txtflds', '');
             }
         }
         // Sanitize them
         $txtflds = preg_replace("/[\"'\\\\]/u", "", $txtflds);
         $txtflds = array_unique(preg_split("/\\s*,\\s*/u", $txtflds));
         if (!strlen($txtflds[0])) {
             unset($txtflds[0]);
         }
         // Create a comma list of them
         $txtflds_list = count($txtflds) ? "'" . implode("','", $txtflds) . "'" : '';
         // Retrieve field properties/parameters, verifying the support to be used as Text Search Fields
         // This will return all supported fields if field limiting list is empty
         $fields_text = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', $txtflds_list, $contenttypes, $load_params = true, 0, 'search');
         if (empty($fields_text)) {
             // all entries of field limiting list were invalid , get ALL
             if (!empty($contenttypes)) {
                 $fields_text = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', null, $contenttypes, $load_params = true, 0, 'search');
             } else {
                 $fields_text = array();
             }
         }
     }
     // ********************************
     // Filter Fields of the search form
     // ********************************
     // Get them from type configuration or from search menu item
     $filtflds = '';
     if ($show_filters) {
         if ($show_filters == 1) {
             $filtflds = $single_contenttype ? $typeData[$single_contenttype]->params->get('filters', '') : '';
         } else {
             $filtflds = $params->get('filtflds', '');
         }
     }
     // Sanitize them
     $filtflds = preg_replace("/[\"'\\\\]/u", "", $filtflds);
     $filtflds = array_unique(preg_split("/\\s*,\\s*/u", $filtflds));
     if (!strlen($filtflds[0])) {
         unset($filtflds[0]);
     }
     // Create a comma list of them
     $filtflds_list = count($filtflds) ? "'" . implode("','", $filtflds) . "'" : '';
     // Retrieve field properties/parameters, verifying the support to be used as Filter Fields
     // This will return all supported fields if field limiting list is empty
     if (count($filtflds)) {
         $filters_tmp = FlexicontentFields::getSearchFields($key = 'name', $indexer = 'advanced', $filtflds_list, $contenttypes, $load_params = true, 0, 'filter');
         // Use custom order
         $filters = array();
         if ($canseltypes && $show_filters) {
             foreach ($filtflds as $field_name) {
                 if (empty($filters_tmp[$field_name])) {
                     continue;
                 }
                 $filter_id = $filters_tmp[$field_name]->id;
                 $filters[$filter_id] = $filters_tmp[$field_name];
             }
         } else {
             foreach ($filters_tmp as $filter) {
                 $filters[$filter->id] = $filter;
                 // index by filter_id in this case too (for consistency, although we do not use the array index ?)
             }
         }
         unset($filters_tmp);
     }
     // If configured filters were not found/invalid for the current content type(s)
     // then retrieve all fields marked as filterable for the give content type(s) this is useful to list per content type filters automatically, even when not set or misconfigured
     if (empty($filters)) {
         if (!empty($contenttypes)) {
             $filters = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', null, $contenttypes, $load_params = true, 0, 'filter');
         } else {
             $filters = array();
         }
     }
     // ****************************************
     // Create Form Elements (the 'lists' array)
     // ****************************************
     $lists = array();
     // *** Selector of Content Types
     if ($canseltypes) {
         $types = array();
         if ($show_filters) {
             $types[] = JHTML::_('select.option', '', JText::_('FLEXI_PLEASE_SELECT'));
         }
         foreach ($typeData as $type) {
             $types[] = JHTML::_('select.option', $type->id, JText::_($type->name));
         }
         $multiple_param = $show_filters ? ' onchange="adminFormPrepare(this.form); this.form.submit();" ' : ' multiple="multiple" ';
         $attribs = $multiple_param . ' size="5" class="fc_field_filter use_select2_lib fc_label_internal fc_prompt_internal"';
         $attribs .= ' data-fc_label_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_CLICK_TO_LIST'), 's') . '"';
         $attribs .= ' data-fc_prompt_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_TYPE_TO_FILTER'), 's') . '"';
         $lists['contenttypes'] = JHTML::_('select.genericlist', $types, 'contenttypes[]', $attribs, 'value', 'text', empty($form_contenttypes) ? '' : $form_contenttypes, 'contenttypes');
         /*
         $checked = !count($form_contenttypes) || !strlen($form_contenttypes[0]);
         $checked_attr = $checked ? 'checked="checked"' : '';
         $checked_class = $checked ? 'fc_highlight' : '';
         
         $lists['contenttypes']  = '<ul class="fc_field_filter fc_checkradio_group">';
         $lists['contenttypes'] .= ' <li class="fc_checkradio_option fc_checkradio_special">';
         $lists['contenttypes'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\', 1);" ';
         $lists['contenttypes'] .= '    id="_contenttypes_0" type="checkbox" name="contenttypes[0]" ';
         $lists['contenttypes'] .= '    value="" '.$checked_attr.' class="fc_checkradio" />';
         $lists['contenttypes'] .= '  <label class="'.$checked_class.'" for="_contenttypes_0">';
         $lists['contenttypes'] .= '   -'.JText::_('FLEXI_ALL').'-';
         $lists['contenttypes'] .= '  </label>';
         $lists['contenttypes'] .= ' </li>';
         foreach($typeData as $type) {
         	$checked = in_array($type->value, $form_contenttypes);
         	$checked_attr = $checked ? 'checked=checked' : '';
         	$checked_class = $checked ? ' fc_highlight' : '';
         	$lists['contenttypes'] .= ' <li class="fc_checkradio_option">';
         	$lists['contenttypes'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\');" ';
         	$lists['contenttypes'] .= '    id="_contenttypes_'.$type->value.'" type="checkbox" name="contenttypes[]" ';
         	$lists['contenttypes'] .= '    value="'.$type->value.'" '.$checked_attr.' class="fc_checkradio" />';
         	$lists['contenttypes'] .= '  <label class="'.$checked_class.'" for="_contenttypes_'.$type->value.'">';
         	$lists['contenttypes'] .= '   '.JText::_($type->text);
         	$lists['contenttypes'] .= '  </label>';
         	$lists['contenttypes'] .= ' </li>';
         }
         $lists['contenttypes'] .= '</ul>';
         */
     }
     // *** Selector of Fields for text searching
     if ($txtmode == 2 && count($fields_text)) {
         // Get selected text fields in the Search Form
         $form_txtflds = JRequest::getVar('txtflds', array());
         if (!$form_txtflds || empty($form_txtflds)) {
             $form_txtflds = array();
             //array('__FC_ALL__'); //array_keys($fields_text);
         }
         $attribs = ' multiple="multiple" size="5" class="fc_field_filter use_select2_lib fc_label_internal fc_prompt_internal"';
         $attribs .= ' data-fc_label_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_CLICK_TO_LIST'), 's') . '"';
         $attribs .= ' data-fc_prompt_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_TYPE_TO_FILTER'), 's') . '"';
         $lists['txtflds'] = JHTML::_('select.genericlist', $fields_text, 'txtflds[]', $attribs, 'name', 'label', $form_txtflds, 'txtflds');
         /*
         $checked = !count($form_txtflds) || !strlen($form_txtflds[0]);
         $checked_attr = $checked ? 'checked="checked"' : '';
         $checked_class = $checked ? 'fc_highlight' : '';
         
         $lists['txtflds']  = '<ul class="fc_field_filter fc_checkradio_group">';
         $lists['txtflds'] .= ' <li class="fc_checkradio_option fc_checkradio_special">';
         $lists['txtflds'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\', 1);" ';
         $lists['txtflds'] .= '    id="_txtflds_0" type="checkbox" name="txtflds[0]" value="" ';
         $lists['txtflds'] .= '    value="" '.$checked_attr.' class="fc_checkradio" />';
         $lists['txtflds'] .= '  <label class="'.$checked_class.'" for="_txtflds_0">';
         $lists['txtflds'] .= '   -'.JText::_('FLEXI_ALL').'-';
         $lists['txtflds'] .= '  </label>';
         $lists['txtflds'] .= ' </li>';
         foreach($fields_text as $field) {
         	$checked = in_array($field->name, $form_txtflds);
         	$checked_attr = $checked ? 'checked=checked' : '';
         	$checked_class = $checked ? ' fc_highlight' : '';
         	$lists['txtflds'] .= ' <li class="fc_checkradio_option">';
         	$lists['txtflds'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\');" ';
         	$lists['txtflds'] .= '    id="_txtflds_'.$field->id.'" type="checkbox" name="txtflds[]" ';
         	$lists['txtflds'] .= '    value="'.$field->name.'" '.$checked_attr.' class="fc_checkradio" />';
         	$lists['txtflds'] .= '  <label class="class=""'.$checked_class.'" for="_txtflds_'.$field->id.'">';
         	$lists['txtflds'] .= '   '.JText::_($field->label);
         	$lists['txtflds'] .= '  </label>';
         	$lists['txtflds'] .= ' </li>';
         }
         $lists['txtflds'] .= '</ul>';
         */
     }
     // *** Selector of FLEXIcontent Results Ordering
     if ($orderby_override = $params->get('orderby_override', 1)) {
         $lists['orderby'] = flexicontent_html::ordery_selector($params, $form_id, $autosubmit = 0);
     }
     // *** Selector of Pagination Limit
     if ($limit_override = $params->get('limit_override', 1)) {
         $lists['limit'] = flexicontent_html::limit_selector($params, $form_id, $autosubmit = 0);
     }
     // *** Selector of non-FLEXIcontent Results Ordering
     if ($show_searchordering = $params->get('show_searchordering', 1)) {
         // built select lists
         $orders = array();
         $orders[] = JHTML::_('select.option', 'newest', JText::_('FLEXI_ADV_NEWEST_FIRST'));
         $orders[] = JHTML::_('select.option', 'oldest', JText::_('FLEXI_ADV_OLDEST_FIRST'));
         $orders[] = JHTML::_('select.option', 'popular', JText::_('FLEXI_ADV_MOST_POP'));
         $orders[] = JHTML::_('select.option', 'alpha', JText::_('FLEXI_ADV_ALPHA'));
         $orders[] = JHTML::_('select.option', 'category', JText::_('FLEXI_ADV_SEARCH_SEC_CAT'));
         $lists['ordering'] = JHTML::_('select.genericlist', $orders, 'o', 'class="fc_field_filter use_select2_lib"', 'value', 'text', $searchordering, 'ordering');
     }
     // *** Selector for usage of Search Text
     if ($show_searchphrase = $params->get('show_searchphrase', 1)) {
         $searchphrase_names = array('natural' => 'FLEXI_NATURAL_PHRASE', 'natural_expanded' => 'FLEXI_NATURAL_PHRASE_GUESS_RELEVANT', 'all' => 'FLEXI_ALL_WORDS', 'any' => 'FLEXI_ANY_WORDS', 'exact' => 'FLEXI_EXACT_PHRASE');
         $phrases = array();
         foreach ($searchphrase_names as $searchphrase_value => $searchphrase_name) {
             $_obj = new stdClass();
             $_obj->value = $searchphrase_value;
             $_obj->text = $searchphrase_name;
             $phrases[] = $_obj;
         }
         $lists['searchphrase'] = JHTML::_('select.genericlist', $phrases, 'p', 'class="fc_field_filter use_select2_lib"', 'value', 'text', $searchphrase, 'searchphrase', $_translate = true);
         /*$lists['searchphrase']  = '<ul class="fc_field_filter fc_checkradio_group">';
         		foreach ($searchphrase_names as $searchphrase_value => $searchphrase_name) {
         			$lists['searchphrase'] .= ' <li class="fc_checkradio_option fc_checkradio_special">';
         			$checked = $searchphrase_value == $searchphrase;
         			$checked_attr = $checked ? 'checked=checked' : '';
         			$checked_class = $checked ? 'fc_highlight' : '';
         			$lists['searchphrase'] .= '  <input href="javascript:;" onclick="fc_toggleClassGrp(this.parentNode, \'fc_highlight\');" id="searchphrase_'.$searchphrase_value.'" type="radio" name="p" value="'.$searchphrase_value.'" '.$checked_attr.' />';
         			$lists['searchphrase'] .= '  <label class="'.$checked_class.'" style="display:inline-block; white-space:nowrap;" for="searchphrase_'.$searchphrase_value.'">';
         			$lists['searchphrase'] .=     JText::_($searchphrase_name);
         			$lists['searchphrase'] .= '  </label>';
         			$lists['searchphrase'] .= ' </li>';
         		}
         		$lists['searchphrase']  .= '</ul>';*/
     }
     // *** Selector for filter combination
     /*if($show_filtersop = $params->get('show_filtersop', 1)) {
     			$default_filtersop = $params->get('default_filtersop', 'all');
     			$filtersop = JRequest::getVar('filtersop', $default_filtersop);
     			$filtersop_arr		= array();
     			$filtersop_arr[] = JHTML::_('select.option',  'all', JText::_( 'FLEXI_SEARCH_ALL' ) );
     			$filtersop_arr[] = JHTML::_('select.option',  'any', JText::_( 'FLEXI_SEARCH_ANY' ) );
     			$lists['filtersop']= JHTML::_('select.radiolist',  $filtersop_arr, 'filtersop', '', 'value', 'text', $filtersop );
     		}*/
     // *** Selector of Search Areas
     // If showing this is disabled, then FLEXIcontent (advanced) search model will not use all search areas,
     // but instead it will use just 'flexicontent' search area, that is the search area of FLEXIcontent (advanced) search plugin
     if ($params->get('show_searchareas', 0)) {
         // Get Content Types currently selected in the Search Form
         $form_areas = JRequest::getVar('areas', array());
         //if ( empty($form_areas) || !count($form_areas) )  $form_areas = array('flexicontent');
         $checked = empty($form_areas) || !count($form_areas);
         $checked_attr = $checked ? 'checked="checked"' : '';
         $checked_class = $checked ? 'fc_highlight' : '';
         // Create array of area options
         $options = array();
         foreach ($areas['search'] as $area => $label) {
             $_area = new stdClass();
             $_area->text = $label;
             $_area->value = $area;
             $options[] = $_area;
         }
         $attribs = ' multiple="multiple" size="5" class="fc_field_filter use_select2_lib fc_label_internal fc_prompt_internal"';
         $attribs .= ' data-fc_label_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_CLICK_TO_LIST'), 's') . '"';
         $attribs .= ' data-fc_prompt_text="' . flexicontent_html::escapeJsText(JText::_('FLEXI_TYPE_TO_FILTER'), 's') . '"';
         $lists['areas'] = JHTML::_('select.genericlist', $options, 'areas[]', $attribs, 'value', 'text', $form_areas, 'areas', $do_jtext = true);
         /*
         $lists['areas']  = '<ul class="fc_field_filter fc_checkradio_group">';
         $lists['areas'] .= ' <li class="fc_checkradio_option fc_checkradio_special">';
         $lists['areas'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\', 1);" ';
         $lists['areas'] .= '    id="area_0" type="checkbox" name="area[0]" ';
         $lists['areas'] .= '    value="" '.$checked_attr.' class="fc_checkradio" />';
         $lists['areas'] .= '  <label class="'.$checked_class.'" for="_txtflds_0">';
         $lists['areas'] .= '   -'.JText::_('FLEXI_CONTENT_ONLY').'-';
         $lists['areas'] .= '  </label>';
         $lists['areas'] .= ' </li>';
         foreach($areas['search'] as $area_name => $area_label) {
         	$checked = in_array($area_name, $form_areas);
         	$checked_attr = $checked ? 'checked=checked' : '';
         	$checked_class = $checked ? ' fc_highlight' : '';
         	$lists['areas'] .= ' <li class="fc_checkradio_option">';
         	$lists['areas'] .= '  <input href="javascript:;" onclick="fc_toggleClass(this, \'fc_highlight\');" ';
         	$lists['areas'] .= '    id="area_'.$area_name.'" type="checkbox" name="areas[]" ';
         	$lists['areas'] .= '    value="'.$area_name.'" '.$checked_attr.' class="fc_checkradio" />';
         	$lists['areas'] .= '  <label class="'.$checked_class.'" for="area_'.$area_name.'">';
         	$lists['areas'] .= '  '.JText::_($area_label);
         	$lists['areas'] .= '  </label>';
         	$lists['areas'] .= ' </li>';
         }
         $lists['areas'] .= '</ul>';
         */
     }
     // log the search
     FLEXIadvsearchHelper::logSearch($searchword);
     //limit searchword
     $min_word_len = $app->getUserState($option . '.min_word_len', 0);
     $min = $min_word_len ? $min_word_len : $params->get('minchars', 3);
     $max = $params->get('maxchars', 200);
     if (FLEXIadvsearchHelper::limitSearchWord($searchword, $min, $max)) {
         $error = JText::sprintf('FLEXI_SEARCH_MESSAGE', $min, $max);
     }
     // sanitise searchword
     if (FLEXIadvsearchHelper::santiseSearchWord($searchword, $state->get('match'), $min)) {
         $error = JText::_('IGNOREKEYWORD');
     }
     if (!$searchword && count(JRequest::get('post'))) {
         //$error = JText::_( 'Enter a search keyword' );
     }
     // put the filtered results back into the model
     // for next release, the checks should be done in the model perhaps...
     $state->set('keyword', $searchword);
     $filter_word_like_any = $params->get('filter_word_like_any', 0);
     if (!$error) {
         require_once JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'route.php';
         $results = $this->get('data');
         $total = $this->get('total');
         $pageNav = $this->get('pagination');
         // URL-encode filter values
         foreach ($_GET as $i => $v) {
             if (substr($i, 0, 6) === "filter") {
                 $_revert = array('%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')');
                 $v = str_replace('&', '__amp__', $v);
                 $v = strtr(rawurlencode($v), $_revert);
                 $pageNav->setAdditionalUrlParam($i, $v);
             }
         }
         if ($state->get('match') == 'exact') {
             $searchwords = array($searchword);
             //$needle = $searchword;
         } else {
             $searchwords = preg_split("/\\s+/u", $searchword);
             //print_r($searchwords);
         }
         // Create regular expressions, for highlighting the matched words
         $w_regexp_highlight = array();
         foreach ($searchwords as $n => $_word) {
             $w_regexp_highlight[$_word] = mb_strlen($_word, 'utf-8') <= 2 || $n + 1 < count($searchwords) ? '#\\b(' . preg_quote($_word, '#') . ')\\b#iu' : '#\\b(' . preg_quote($_word, '#') . ')#iu';
         }
         for ($i = 0; $i < count($results); $i++) {
             $result =& $results[$i];
             if (strlen($searchwords[0])) {
                 $parts = FLEXIadvsearchHelper::prepareSearchContent($result->text, $params->get('text_chars', 200), $searchwords);
                 //if( count($parts)>1 ) { echo "<pre>"; print_r($parts); exit;}
                 foreach ($parts as $word_found => $part) {
                     if (!$word_found) {
                         continue;
                     }
                     $searchRegex = $w_regexp_highlight[$word_found];
                     $parts[$word_found] = preg_replace($searchRegex, '_fc_highlight_start_\\0_fc_highlight_end_', $part);
                 }
                 $result->text = implode($parts, " <br/> ");
                 $replace_count_total = 0;
                 // This is for LIKE %word% search for languages without spaces
                 if ($filter_word_like_any) {
                     if (strlen($word_found) <= 2) {
                         continue;
                     }
                     // Do not highlight too small words, since we do not consider spaces
                     foreach ($searchwords as $_word) {
                         $searchRegex = '#(' . preg_quote($_word, '#') . '[^\\s]*)#iu';
                         $result->text = preg_replace($searchRegex, '_fc_highlight_start_\\0_fc_highlight_end_', $result->text, 1, $replace_count);
                         if ($replace_count) {
                             $replace_count_total++;
                         }
                     }
                 }
                 $result->text = str_replace('_fc_highlight_start_', '<span class="highlight">', $result->text);
                 $result->text = str_replace('_fc_highlight_end_', '</span>', $result->text);
                 // Add some message about matches
                 /*if ( $state->get('match')=='any' ) {
                 			$text_search_header = "<u><b>".JText::sprintf('Text Search matched at least %d %% (%d out of %d words)', $replace_count_total/count($searchwords) * 100, $replace_count_total, count($searchwords)).": </b></u><br/>";
                 		} else if ( $state->get('match')=='all' ) {
                 			$text_search_header = "<u><b>".JText::sprintf('Text Search (all %d words required)', count($searchwords)).": </b></u><br/>";
                 		} else if ( $state->get('match')=='exact' ) {
                 			$text_search_header = "<u><b>".JText::_('Text Search (exact phrase)').": </b></u><br/>";
                 		} else if ( $state->get('match')=='natural_expanded' ) {
                 			$text_search_header = "<u><b>".JText::_('Text Search (phrase, guessing related)').": </b></u><br/>";
                 		} else if ( $state->get('match')=='natural' ) {
                 			$text_search_header = "<u><b>".JText::_('Text Search (phrase)').": </b></u><br/>";
                 		}
                 		$result->text = $text_search_header . $result->text;*/
             } else {
                 $parts = FLEXIadvsearchHelper::prepareSearchContent($result->text, $params->get('text_chars', 200), array());
                 $result->text = implode($parts, " <br/> ");
             }
             /*if ( !empty($result->fields_text) ) {
             			$result->text .= "<br/><u><b>".JText::_('Attribute filters matched')." : </b></u>";
             			$result->fields_text = str_replace('[span=highlight]', '<span class="highlight">', $result->fields_text);
             			$result->fields_text = str_replace('[/span]', '</span>', $result->fields_text);
             			$result->fields_text = str_replace('[br /]', '<br />', $result->fields_text);
             			$result->text .= $result->fields_text;
             		}*/
             $result->text = str_replace('[[[', '<', $result->text);
             $result->text = str_replace(']]]', '>', $result->text);
             $result->created = $result->created ? JHTML::Date($result->created) : '';
             $result->count = $i + 1;
         }
     }
     $this->result = JText::sprintf('FLEXI_TOTALRESULTSFOUND', $total);
     // ******************************************************************
     // Create HTML of filters (-AFTER- getData of model have been called)
     // ******************************************************************
     foreach ($filters as $filter) {
         $filter->parameters->set('display_label_filter_s', 0);
         $filter->value = JRequest::getVar('filter_' . $filter->id, false);
         //$fieldsearch = $app->getUserStateFromRequest( 'flexicontent.search.'.'filter_'.$filter->id, 'filter_'.$filter->id, array(), 'array' );
         //echo "Field name: ".$filter->name; echo ":: ". 'filter_'.$filter->id ." :: value: "; print_r($filter->value); echo "<br/>\n";
         $field_filename = $filter->iscore ? 'core' : $filter->field_type;
         FLEXIUtilities::call_FC_Field_Func($field_filename, 'onAdvSearchDisplayFilter', array(&$filter, $filter->value, $form_id));
     }
     //echo "<pre>"; print_r($_GET); exit;
     // Create links
     $link = JRoute::_(FlexicontentHelperRoute::getSearchRoute(0, $menu_matches ? $menu->id : 0));
     //$print_link = JRoute::_('index.php?view=search&pop=1&tmpl=component&print=1');
     $curr_url = str_replace('&', '&amp;', $_SERVER['REQUEST_URI']);
     $print_link = $curr_url . (strstr($curr_url, '?') ? '&amp;' : '?') . 'pop=1&amp;tmpl=component&amp;print=1';
     $pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
     $this->assignRef('action', $link);
     // $uri->toString()
     $this->assignRef('print_link', $print_link);
     $this->assignRef('contenttypes', $contenttypes);
     $this->assignRef('filters', $filters);
     $this->assignRef('results', $results);
     $this->assignRef('lists', $lists);
     $this->assignRef('params', $params);
     $this->assignRef('pageNav', $pageNav);
     $this->assignRef('pageclass_sfx', $pageclass_sfx);
     $this->assignRef('typeData', $typeData);
     $this->assign('ordering', $state->get('ordering'));
     $this->assign('searchword', $searchword);
     $this->assign('searchphrase', $state->get('match'));
     $this->assign('searchareas', $areas);
     $this->assign('total', $total);
     $this->assign('error', $error);
     $this->assignRef('document', $document);
     $this->assign('form_id', $form_id);
     $this->assign('form_name', $form_name);
     $print_logging_info = $params->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
         $start_microtime = microtime(true);
     }
     parent::display($tpl);
     if ($print_logging_info) {
         @($fc_run_times['template_render'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
 }
Exemplo n.º 5
0
    /**
     * Creates the item page
     *
     * @since 1.0
     */
    function display($tpl = null)
    {
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        global $globalcats;
        $categories = $globalcats;
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $config = JFactory::getConfig();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $option = JRequest::getVar('option');
        $nullDate = $db->getNullDate();
        // Get the COMPONENT only parameters
        // Get component parameters
        $params = new JRegistry();
        $cparams = JComponentHelper::getParams('com_flexicontent');
        $params->merge($cparams);
        $params = clone JComponentHelper::getParams('com_flexicontent');
        // Some flags
        $enable_translation_groups = flexicontent_db::useAssociations();
        //$params->get("enable_translation_groups");
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        // Add css to document
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontentbackend.css', FLEXI_VERSION);
        $document->addStyleSheetVersion(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css', FLEXI_VERSION);
        // Fields common CSS
        $document->addStyleSheetVersion(JURI::root(true) . '/components/com_flexicontent/assets/css/flexi_form_fields.css', FLEXI_VERSION);
        // Add JS frameworks
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        flexicontent_html::loadFramework('flexi-lib');
        // Add js function to overload the joomla submitform validation
        JHTML::_('behavior.formvalidation');
        // load default validation JS to make sure it is overriden
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/admin.js', FLEXI_VERSION);
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/validate.js', FLEXI_VERSION);
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScriptVersion(JURI::root(true) . '/components/com_flexicontent/assets/js/itemscreen.js', FLEXI_VERSION);
        // ***********************
        // Get data from the model
        // ***********************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        $item = $model->getItem();
        $form = $this->get('Form');
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // ***************************
        // Get Associated Translations
        // ***************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        $langs = FLEXIUtilities::getLanguages('code');
        // Get item id and new flag
        $cid = $model->getId();
        $isnew = !$cid;
        // Create and set a unique item id for plugins that needed it
        if ($cid) {
            $unique_tmp_itemid = $cid;
        } else {
            $unique_tmp_itemid = $app->getUserState('com_flexicontent.edit.item.unique_tmp_itemid');
            $unique_tmp_itemid = $unique_tmp_itemid ? $unique_tmp_itemid : date('_Y_m_d_h_i_s_', time()) . uniqid(true);
        }
        //print_r($unique_tmp_itemid);
        JRequest::setVar('unique_tmp_itemid', $unique_tmp_itemid);
        // Get number of subscribers
        $subscribers = $model->getSubscribersCount();
        // ******************
        // Version Panel data
        // ******************
        // Get / calculate some version related variables
        $versioncount = $model->getVersionCount();
        $versionsperpage = $params->get('versionsperpage', 10);
        $pagecount = (int) ceil($versioncount / $versionsperpage);
        // Data need by version panel: (a) current version page, (b) currently active version
        $current_page = 1;
        $k = 1;
        $allversions = $model->getVersionList();
        foreach ($allversions as $v) {
            if ($k > 1 && ($k - 1) % $versionsperpage == 0) {
                $current_page++;
            }
            if ($v->nr == $item->version) {
                break;
            }
            $k++;
        }
        // Finally fetch the version data for versions in current page
        $versions = $model->getVersionList(($current_page - 1) * $versionsperpage, $versionsperpage);
        // Create display of average rating
        $ratings = $model->getRatingDisplay();
        // *****************
        // Type related data
        // *****************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get and merge type parameters
        $tparams = $this->get('Typeparams');
        $tparams = new JRegistry($tparams);
        $params->merge($tparams);
        // Apply type configuration if it type is set
        // Get user allowed permissions on the item ... to be used by the form rendering
        // Also hide parameters panel if user can not edit parameters
        $perms = $this->_getItemPerms($item);
        if (!$perms['canparams']) {
            $document->addStyleDeclaration('#details-options {display:none;}');
        }
        // ******************
        // Create the toolbar
        // ******************
        $toolbar = JToolBar::getInstance('toolbar');
        $tip_class = FLEXI_J30GE ? ' hasTooltip' : ' hasTip';
        // SET toolbar title
        if ($cid) {
            JToolBarHelper::title(JText::_('FLEXI_EDIT_ITEM'), 'itemedit');
            // Editing existing item
        } else {
            JToolBarHelper::title(JText::_('FLEXI_NEW_ITEM'), 'itemadd');
            // Creating new item
        }
        // **************
        // Common Buttons
        // **************
        // Applying new item type is a special case that has not loaded custom fieds yet
        JToolBarHelper::apply($item->type_id ? 'items.apply' : 'items.apply_type', !$isnew ? 'FLEXI_APPLY' : ($typesselected->id ? 'FLEXI_ADD' : 'FLEXI_APPLY_TYPE'), false);
        /*if (!$isnew || $item->version) flexicontent_html::addToolBarButton(
        		'FLEXI_FAST_APPLY', $btn_name='apply_ajax', $full_js="Joomla.submitbutton('items.apply_ajax')", $msg_alert='', $msg_confirm='',
        		$btn_task='items.apply_ajax', $extra_js='', $btn_list=false, $btn_menu=true, $btn_confirm=false, $btn_class="".$tip_class, $btn_icon="icon-loop",
        		'data-placement="bottom" title="Fast saving, without reloading the form. <br/><br/>Note: new files will not be uploaded, <br/>- in such a case please use \'Apply\'"');*/
        if (!$isnew || $item->version) {
            JToolBarHelper::save('items.save');
        }
        if (!$isnew || $item->version) {
            JToolBarHelper::custom('items.saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
        }
        JToolBarHelper::cancel('items.cancel');
        // ***********************
        // Add a preview button(s)
        // ***********************
        //$_sh404sef = JPluginHelper::isEnabled('system', 'sh404sef') && $config->get('sef');
        $_sh404sef = defined('SH404SEF_IS_RUNNING') && $config->get('sef');
        if ($cid) {
            // Domain URL and autologin vars
            $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
            $autologin = '';
            //$params->get('autoflogin', 1) ? '&fcu='.$user->username . '&fcp='.$user->password : '';
            // Check if we are in the backend, in the back end we need to set the application to the site app instead
            // we do not remove 'isAdmin' check so that we can copy later without change, e.g. to a plugin
            $isAdmin = JFactory::getApplication()->isAdmin();
            if ($isAdmin && !$_sh404sef) {
                JFactory::$application = JApplication::getInstance('site');
            }
            // Create the URL
            $item_url = FlexicontentHelperRoute::getItemRoute($item->id . ':' . $item->alias, $categories[$item->catid]->slug) . ($item->language != '*' ? '&lang=' . substr($item->language, 0, 2) : '');
            $item_url = $_sh404sef ? Sh404sefHelperGeneral::getSefFromNonSef($item_url, $fullyQualified = true, $xhtml = false, $ssl = null) : JRoute::_($item_url);
            // Check if we are in the backend again
            // In backend we need to remove administrator from URL as it is added even though we've set the application to the site app
            if ($isAdmin && !$_sh404sef) {
                $admin_folder = str_replace(JURI::root(true), '', JURI::base(true));
                $item_url = str_replace($admin_folder . '/', '/', $item_url);
                // Restore application
                JFactory::$application = JApplication::getInstance('administrator');
            }
            $previewlink = $item_url . (strstr($item_url, '?') ? '&amp;' : '?') . 'preview=1' . $autologin;
            //$previewlink     = str_replace('&amp;', '&', $previewlink);
            //$previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $categories[$item->catid]->slug)) .$autologin;
            // PREVIEW for latest version
            if (!$params->get('use_versioning', 1) || $item->version == $item->current_version && $item->version == $item->last_version) {
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small btn-info spaced-btn" onClick="window.open(\'' . $previewlink . '\');"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('Preview') . '</button>', 'preview');
            } else {
                // Add a preview button for (currently) LOADED version of the item
                $previewlink_loaded_ver = $previewlink . '&version=' . $item->version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_loaded_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FORM_LOADED_VERSION') . ' [' . $item->version . ']</button>', 'preview');
                // Add a preview button for currently ACTIVE version of the item
                $previewlink_active_ver = $previewlink . '&version=' . $item->current_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_active_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_FRONTEND_ACTIVE_VERSION') . ' [' . $item->current_version . ']</button>', 'preview');
                // Add a preview button for currently LATEST version of the item
                $previewlink_last_ver = $previewlink;
                //'&version='.$item->last_version;
                $toolbar->appendButton('Custom', '<button class="preview btn btn-small" onClick="window.open(\'' . $previewlink_last_ver . '\');" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-screen"></span>' . JText::_('FLEXI_PREVIEW_LATEST_SAVED_VERSION') . ' [' . $item->last_version . ']</button>', 'preview');
            }
            JToolBarHelper::spacer();
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
        }
        // ************************
        // Add modal layout editing
        // ************************
        if ($perms['cantemplates']) {
            JToolBarHelper::divider();
            if (!$isnew || $item->version) {
                flexicontent_html::addToolBarButton('FLEXI_EDIT_LAYOUT', $btn_name = 'apply_ajax', $full_js = "var url = jQuery(this).attr('data-href'); fc_showDialog(url, 'fc_modal_popup_container'); return false;", $msg_alert = '', $msg_confirm = '', $btn_task = 'items.apply_ajax', $extra_js = '', $btn_list = false, $btn_menu = true, $btn_confirm = false, $btn_class = "btn-info" . $tip_class, $btn_icon = "icon-pencil", 'data-placement="bottom" data-href="index.php?option=com_flexicontent&amp;view=template&amp;type=items&amp;tmpl=component&amp;ismodal=1&amp;folder=' . $item->itemparams->get('ilayout', $tparams->get('ilayout', 'default')) . '" title="Edit the display layout of this item. <br/><br/>Note: this layout maybe assigned to content types or other items, thus changing it will effect them too"');
            }
        }
        // Check if saving an item that translates an original content in site's default language
        $site_default = substr(flexicontent_html::getSiteDefaultLang(), 0, 2);
        $is_content_default_lang = $site_default == substr($item->language, 0, 2);
        // *****************************************************************************
        // Get (CORE & CUSTOM) fields and their VERSIONED values and then
        // (a) Apply Content Type Customization to CORE fields (label, description, etc)
        // (b) Create the edit html of the CUSTOM fields by triggering 'onDisplayField'
        // *****************************************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $fields = $this->get('Extrafields');
        $item->fields =& $fields;
        if ($print_logging_info) {
            $fc_run_times['get_field_vals'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $jcustom = $app->getUserState('com_flexicontent.edit.item.custom');
        //print_r($jcustom);
        foreach ($fields as $field) {
            // a. Apply CONTENT TYPE customizations to CORE FIELDS, e.g a type specific label & description
            // NOTE: the field parameters are already created so there is not need to call this for CUSTOM fields, which do not have CONTENT TYPE customizations
            if ($field->iscore) {
                FlexicontentFields::loadFieldConfig($field, $item);
            }
            // b. Create field 's editing HTML (the form field)
            // NOTE: this is DONE only for CUSTOM fields, since form field html is created by the form for all CORE fields, EXCEPTION is the 'text' field (see bellow)
            if (!$field->iscore) {
                if (isset($jcustom[$field->name])) {
                    $field->value = array();
                    foreach ($jcustom[$field->name] as $i => $_val) {
                        $field->value[$i] = $_val;
                    }
                }
                $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                if ($is_editable) {
                    FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    if ($field->untranslatable) {
                        $field->html = (!isset($field->html) ? '<div class="fc-mssg-inline fc-warning" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_PLEASE_PUBLISH_THIS_PLUGIN') . '</div><div class="clear"></div>' : '') . '<div class="alert alert-info fc-small fc-iblock" style="margin:0 4px 6px 4px; max-width: unset;">' . JText::_('FLEXI_FIELD_VALUE_IS_NON_TRANSLATABLE') . '</div>' . "\n" . (isset($field->html) ? '<div class="clear"></div>' . $field->html : '');
                    }
                } else {
                    if ($field->valueseditable == 1) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                    } else {
                        if ($field->valueseditable == 2) {
                            FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                            $field->html = '<div class="fc-mssg fc-note">' . JText::_($field->parameters->get('no_acc_msg_form') ? $field->parameters->get('no_acc_msg_form') : 'FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>' . "\n" . $field->display;
                        } else {
                            if ($field->valueseditable == 3) {
                                FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayFieldValue', array(&$field, $item));
                                $field->html = $field->display;
                            } else {
                                if ($field->valueseditable == 4) {
                                    $field->html = '';
                                    $field->formhidden = 4;
                                }
                            }
                        }
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // *************************
        // Get tags used by the item
        // *************************
        $usedtagsIds = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtags = $model->getUsedtagsData($usedtagsIds);
        // *******************************
        // Get categories used by the item
        // *******************************
        if ($isnew) {
            // Case for preselected main category for new items
            $maincat = $item->catid ? $item->catid : JRequest::getInt('maincat', 0);
            if (!$maincat) {
                $maincat = $app->getUserStateFromRequest($option . '.items.filter_cats', 'filter_cats', '', 'int');
            }
            if ($maincat) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($tparams->get('cid_default')) {
                $selectedcats = $tparams->get('cid_default');
            }
            if ($tparams->get('catid_default')) {
                $item->catid = $tparams->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        //$selectedcats 	= $isnew ? array() : $fields['categories']->value;
        //echo "<br/>row->tags: "; print_r($item->tags);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsIds);
        //echo "<br/>usedtags (data): "; print_r($usedtags);
        //echo "<br/>row->categories: "; print_r($item->categories);
        //echo "<br/>selectedcats: "; print_r($selectedcats);
        // *********************************************************************************************
        // Build select lists for the form field. Only few of them are used in J1.6+, since we will use:
        // (a) form XML file to declare them and then (b) getInput() method form field to create them
        // *********************************************************************************************
        // First clean form data, we do this after creating the description field which may contain HTML
        JFilterOutput::objectHTMLSafe($item, ENT_QUOTES);
        $lists = array();
        // build state list
        $non_publishers_stategrp = $perms['isSuperAdmin'] || $item->state == -3 || $item->state == -4;
        $special_privelege_stategrp = $item->state == 2 || $perms['canarchive'] || ($item->state == -2 || $perms['candelete']);
        $state = array();
        // Using <select> groups
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_PUBLISHERS_WORKFLOW_STATES'));
        }
        $state[] = JHTML::_('select.option', 1, JText::_('FLEXI_PUBLISHED'));
        $state[] = JHTML::_('select.option', 0, JText::_('FLEXI_UNPUBLISHED'));
        $state[] = JHTML::_('select.option', -5, JText::_('FLEXI_IN_PROGRESS'));
        // States reserved for workflow
        if ($non_publishers_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_NON_PUBLISHERS_WORKFLOW_STATES'));
        }
        if ($item->state == -3 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -3, JText::_('FLEXI_PENDING'));
        }
        if ($item->state == -4 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -4, JText::_('FLEXI_TO_WRITE'));
        }
        // Special access states
        if ($special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_SPECIAL_ACTION_STATES'));
        }
        if ($item->state == 2 || $perms['canarchive']) {
            $state[] = JHTML::_('select.option', 2, JText::_('FLEXI_ARCHIVED'));
        }
        if ($item->state == -2 || $perms['candelete']) {
            $state[] = JHTML::_('select.option', -2, JText::_('FLEXI_TRASHED'));
        }
        // Close last <select> group
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
        }
        $fieldname = 'jform[state]';
        $elementid = 'jform_state';
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, $fieldname, $attribs, 'value', 'text', $item->state, $elementid);
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
            // build featured flag
            $fieldname = 'jform[featured]';
            $elementid = 'jform_featured';
            /*
            $options = array();
            $options[] = JHTML::_('select.option',  0, JText::_( 'FLEXI_NO' ) );
            $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_YES' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
            $lists['featured'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $item->featured, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array(0 => JText::_('FLEXI_NO'), 1 => JText::_('FLEXI_YES'));
            $lists['featured'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id == $item->featured ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['featured'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // *** EOF: J1.5 SPECIFIC SELECT LISTS
        // build version approval list
        $fieldname = 'jform[vstate]';
        $elementid = 'jform_vstate';
        /*
        $options = array();
        $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_NO' ) );
        $options[] = JHTML::_('select.option',  2, JText::_( 'FLEXI_YES' ) );
        $attribs = FLEXI_J16GE ? ' style ="float:left!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
        $lists['vstate'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', 2, $elementid);
        */
        $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
        $attribs = ' class="' . $classes . '" ';
        $i = 1;
        $options = array(1 => JText::_('FLEXI_NO'), 2 => JText::_('FLEXI_YES'));
        $lists['vstate'] = '';
        foreach ($options as $option_id => $option_label) {
            $checked = $option_id == 2 ? ' checked="checked"' : '';
            $elementid_no = $elementid . '_' . $i;
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
            }
            $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
            $lists['vstate'] .= ' <input type="radio" id="' . $elementid_no . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '&nbsp;' . JText::_($option_label) . '</label>';
            }
            $i++;
        }
        // build field for notifying subscribers
        if (!$subscribers) {
            $lists['notify'] = !$isnew ? JText::_('FLEXI_NO_SUBSCRIBERS_EXIST') : '';
        } else {
            // b. Check if notification emails to subscribers , were already sent during current session
            $subscribers_notified = $session->get('subscribers_notified', array(), 'flexicontent');
            if (!empty($subscribers_notified[$item->id])) {
                $lists['notify'] = JText::_('FLEXI_SUBSCRIBERS_ALREADY_NOTIFIED');
            } else {
                // build favs notify field
                $fieldname = 'jform[notify]';
                $elementid = 'jform_notify';
                /*
                $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
                $lists['notify'] = '<input type="checkbox" name="jform[notify]" id="jform_notify" '.$attribs.' /> '. $lbltxt;
                */
                $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
                $attribs = ' class="' . $classes . '" ';
                $lbltxt = $subscribers . ' ' . JText::_($subscribers > 1 ? 'FLEXI_SUBSCRIBERS' : 'FLEXI_SUBSCRIBER');
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '<label class="fccheckradio_lbl" for="' . $elementid . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-labeltext="' . $lbltxt . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['notify'] = ' <input type="checkbox" id="' . $elementid . '" data-element-grpid="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="1" ' . $extra_params . ' checked="checked" />';
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '&nbsp;' . $lbltxt . '</label>';
                }
            }
        }
        // Retrieve author configuration
        $authorparams = flexicontent_db::getUserConfig($user->id);
        // Get author's maximum allowed categories per item and set js limitation
        $max_cat_assign = intval($authorparams->get('max_cat_assign', 0));
        $document->addScriptDeclaration('
			max_cat_assign_fc = ' . $max_cat_assign . ';
			existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
		');
        JText::script('FLEXI_TOO_MANY_ITEM_CATEGORIES', true);
        // Creating categorories tree for item assignment, we use the 'create' privelege
        $actions_allowed = array('core.create');
        // Featured categories form field
        $featured_cats_parent = $params->get('featured_cats_parent', 0);
        $featured_cats = array();
        $enable_featured_cid_selector = $perms['multicat'] && $perms['canchange_featcat'];
        if ($featured_cats_parent) {
            $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
            $disabled_cats = $params->get('featured_cats_parent_disable', 1) ? array($featured_cats_parent) : array();
            $featured_sel = array();
            foreach ($selectedcats as $item_cat) {
                if (isset($featured_tree[$item_cat])) {
                    $featured_sel[] = $item_cat;
                }
            }
            $class = "use_select2_lib select2_list_selected";
            $attribs = 'class="' . $class . '" multiple="multiple" size="8"';
            $attribs .= $enable_featured_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[featured_cid][]';
            $lists['featured_cid'] = ($enable_featured_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($featured_tree, $fieldname, $featured_sel, 3, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            // Do not display, if not configured or not allowed to the user
            $lists['featured_cid'] = false;
        }
        // Multi-category form field, for user allowed to use multiple categories
        $lists['cid'] = '';
        $enable_cid_selector = $perms['multicat'] && $perms['canchange_seccat'];
        if (1) {
            if ($tparams->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('cid_allowed_parent'), $depth_limit = 0);
                $disabled_cats = $tparams->get('cid_allowed_parent_disable', 1) ? array($tparams->get('cid_allowed_parent')) : array();
            } else {
                $cid_tree =& $categories;
                $disabled_cats = array();
            }
            // Get author's maximum allowed categories per item and set js limitation
            $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
            $document->addScriptDeclaration('
				max_cat_assign_fc = ' . $max_cat_assign . ';
				existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
			');
            $class = "mcat use_select2_lib select2_list_selected";
            $class .= $max_cat_assign ? " validate-fccats" : " validate";
            $attribs = 'class="' . $class . '" multiple="multiple" size="20"';
            $attribs .= $enable_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = 'jform[cid][]';
            $skip_subtrees = $featured_cats_parent ? array($featured_cats_parent) : array();
            $lists['cid'] = ($enable_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($cid_tree, $fieldname, $selectedcats, false, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees, $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (count($selectedcats) > 1) {
                foreach ($selectedcats as $catid) {
                    $cat_titles[$catid] = $globalcats[$catid]->title;
                }
                $lists['cid'] .= implode(', ', $cat_titles);
            } else {
                $lists['cid'] = false;
            }
        }
        // Main category form field
        $class = 'scat use_select2_lib';
        if ($perms['multicat']) {
            $class .= ' validate-catid';
        } else {
            $class .= ' required';
        }
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[catid]';
        $enable_catid_selector = $isnew && !$tparams->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($tparams->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('catid_allowed_parent'), $depth_limit = 0);
            $disabled_cats = $tparams->get('catid_allowed_parent_disable', 1) ? array($tparams->get('catid_allowed_parent')) : array();
        } else {
            $catid_tree =& $categories;
            $disabled_cats = array();
        }
        $lists['catid'] = false;
        if (!empty($catid_tree)) {
            $disabled = $enable_catid_selector ? '' : ' disabled="disabled"';
            $attribs .= $disabled;
            $lists['catid'] = ($enable_catid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($catid_tree, $fieldname, $item->catid, 2, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees = array(), $disable_subtrees = array(), $custom_options = array(), $disabled_cats);
        } else {
            if (!$isnew && $item->catid) {
                $lists['catid'] = $globalcats[$item->catid]->title;
            }
        }
        //buid types selectlist
        $class = 'required use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $fieldname = 'jform[type_id]';
        $elementid = 'jform_type_id';
        $lists['type'] = flexicontent_html::buildtypesselect($types, $fieldname, $typesselected->id, 1, $attribs, $elementid, $check_perms = true);
        //build languages list
        $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        if (!$isnew && $allowed_langs) {
            $allowed_langs[] = $item->language;
        }
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $lists['languages'] = flexicontent_html::buildlanguageslist('jform[language]', 'class="use_select2_lib"', $item->language, 2, $allowed_langs);
        // Label for current item state: published, unpublished, archived etc
        switch ($item->state) {
            case 0:
                $published = JText::_('FLEXI_UNPUBLISHED');
                break;
            case 1:
                $published = JText::_('FLEXI_PUBLISHED');
                break;
            case -1:
                $published = JText::_('FLEXI_ARCHIVED');
                break;
            case -3:
                $published = JText::_('FLEXI_PENDING');
                break;
            case -5:
                $published = JText::_('FLEXI_IN_PROGRESS');
                break;
            case -4:
            default:
                $published = JText::_('FLEXI_TO_WRITE');
                break;
        }
        // **************************************************************
        // Handle Item Parameters Creation and Load their values for J1.5
        // In J1.6+ we declare them in the item form XML file
        // **************************************************************
        if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
            $form->setValue('publish_down', null, '');
            // Setting to text will break form date element
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        } else {
            if (!is_array($allowed_tmpls)) {
                $allowed_tmpls = explode("|", $allowed_tmpls);
            }
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
            $jform->load($tmpl->params);
            $tmpl->params = $jform;
            foreach ($tmpl->params->getGroup('attribs') as $field) {
                $fieldname = $field->__get('fieldname');
                $value = $item->itemparams->get($fieldname);
                if (strlen($value)) {
                    $tmpl->params->setValue($fieldname, 'attribs', $value);
                }
            }
        }
        // ******************************
        // Assign data to VIEW's template
        // ******************************
        $this->assignRef('document', $document);
        $this->assignRef('lists', $lists);
        $this->assignRef('row', $item);
        if (FLEXI_J16GE) {
            $this->assignRef('form', $form);
        } else {
            $this->assignRef('editor', $editor);
            $this->assignRef('pane', $pane);
            $this->assignRef('formparams', $formparams);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('typesselected', $typesselected);
        $this->assignRef('published', $published);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('fields', $fields);
        $this->assignRef('versions', $versions);
        $this->assignRef('ratings', $ratings);
        $this->assignRef('pagecount', $pagecount);
        $this->assignRef('params', $params);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('tmpls', $tmpls);
        $this->assignRef('usedtags', $usedtags);
        $this->assignRef('perms', $perms);
        $this->assignRef('current_page', $current_page);
        // Clear custom form data from session
        $app->setUserState($form->option . '.edit.' . $form->context . '.custom', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.jfdata', false);
        $app->setUserState($form->option . '.edit.' . $form->context . '.unique_tmp_itemid', false);
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        parent::display($tpl);
        if ($print_logging_info) {
            $fc_run_times['form_rendering'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
    }
Exemplo n.º 6
0
 /**
  * Logic to delete files
  *
  * @access public
  * @return void
  * @since 1.5
  */
 function remove()
 {
     // Check for request forgeries
     JRequest::checkToken() or jexit('Invalid Token');
     require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'file.php';
     $user = JFactory::getUser();
     $db = JFactory::getDBO();
     $model = $this->getModel('file');
     $file = $model->getFile();
     $app = JFactory::getApplication();
     $fieldid = JRequest::getVar('fieldid', 0);
     $u_item_id = JRequest::getVar('u_item_id', 0);
     $file_mode = JRequest::getVar('folder_mode', 0) ? 'folder_mode' : 'db_mode';
     if ($file_mode == 'folder_mode') {
         $filename = JRequest::getVar('filename');
         $db->setQuery("SELECT * FROM #__flexicontent_fields WHERE id='" . $fieldid . "'");
         $field = $db->loadObject();
         $field->parameters = new JRegistry($field->attribs);
         $field->item_id = $u_item_id;
         $result = FLEXIUtilities::call_FC_Field_Func($field->field_type, 'removeOriginalFile', array(&$field, $filename));
         if (!$result) {
             JError::raiseWarning(100, JText::_('FLEXI_UNABLE_TO_CLEANUP_ORIGINAL_FILE') . ": " . $path);
             $msg = '';
         } else {
             $msg = JText::_('FLEXI_FILES_DELETED');
         }
         $vc_start = mb_strrpos('?', $_SERVER['HTTP_REFERER']) ? '&' : '?';
         $this->setRedirect($_SERVER['HTTP_REFERER'] . $vc_start . 'delfilename=' . base64_encode($filename), $msg);
         return;
     }
     // calculate access
     $candelete = $user->authorise('flexicontent.deletefile', 'com_flexicontent');
     $candeleteown = $user->authorise('flexicontent.deleteownfile', 'com_flexicontent') && $file->uploaded_by == $user->get('id');
     $is_authorised = $candelete || $candeleteown;
     // check access
     if (!$is_authorised) {
         JError::raiseNotice(403, JText::_('FLEXI_ALERTNOTAUTH'));
         $this->setRedirect('index.php?option=com_flexicontent&view=filemanager', '');
         return;
     }
     $cid = JRequest::getVar('cid', array(0), 'post', 'array');
     $model = $this->getModel('filemanager');
     if (!is_array($cid) || count($cid) < 1) {
         $msg = '';
         JError::raiseWarning(500, JText::_('FLEXI_SELECT_ITEM_DELETE'));
     } else {
         if (!$model->candelete($cid)) {
             JError::raiseWarning(500, JText::_('FLEXI_YOU_CANNOT_REMOVE_THIS_FILE'));
         } else {
             if (!$model->delete($cid)) {
                 $msg = JText::_('FLEXI_OPERATION_FAILED') . ' : ' . $model->getError();
                 if (FLEXI_J16GE) {
                     throw new Exception($msg, 500);
                 } else {
                     JError::raiseError(500, $msg);
                 }
             }
             $msg = count($cid) . ' ' . JText::_('FLEXI_FILES_DELETED');
             $cache = JFactory::getCache('com_flexicontent');
             $cache->clean();
         }
     }
     $this->setRedirect('index.php?option=com_flexicontent&view=filemanager', $msg);
 }
Exemplo n.º 7
0
    /**
     * Creates the item submit form
     *
     * @since 1.0
     */
    function _displayForm($tpl)
    {
        jimport('joomla.html.parameter');
        // ... we use some strings from administrator part
        // load english language file for 'com_content' component then override with current language file
        JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR, 'en-GB', true);
        JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR, null, true);
        // load english language file for 'com_flexicontent' component then override with current language file
        JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, 'en-GB', true);
        JFactory::getLanguage()->load('com_flexicontent', JPATH_ADMINISTRATOR, null, true);
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $uri = JFactory::getURI();
        $nullDate = $db->getNullDate();
        $menu = $app->getMenu()->getActive();
        // Get the COMPONENT only parameters, then merge the menu parameters
        $comp_params = JComponentHelper::getComponent('com_flexicontent')->params;
        $params = FLEXI_J16GE ? clone $comp_params : new JParameter($comp_params);
        // clone( JComponentHelper::getParams('com_flexicontent') );
        if ($menu) {
            $menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);
            $params->merge($menu_params);
        }
        // Some flags
        $enable_translation_groups = $params->get("enable_translation_groups") && (FLEXI_J16GE || FLEXI_FISH);
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
        flexicontent_html::loadFramework('jQuery');
        flexicontent_html::loadFramework('select2');
        // Load custom behaviours: form validation, popup tooltips
        //JHTML::_('behavior.formvalidation');
        JHTML::_('behavior.tooltip');
        if (FLEXI_J30GE) {
            JHtml::_('bootstrap.tooltip');
        }
        //JHTML::_('script', 'joomla.javascript.js', 'includes/js/');
        // Add css files to the document <head> section (also load CSS joomla template override)
        $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/flexicontent.css');
        if (file_exists(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css')) {
            $document->addStyleSheet(JPATH_SITE . DS . 'templates' . DS . $app->getTemplate() . DS . 'css' . DS . 'flexicontent.css');
        }
        if (!FLEXI_J16GE) {
            $document->addStyleSheet($this->baseurl . '/administrator/templates/khepri/css/general.css');
        }
        //$document->addCustomTag('<!--[if IE]><style type="text/css">.floattext{zoom:1;}, * html #flexicontent dd { height: 1%; }</style><![endif]-->');
        // Load backend / frontend shared and Joomla version specific CSS (different for frontend / backend)
        $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/flexi_shared.css');
        // NOTE: this is imported by main Frontend CSS file
        if (FLEXI_J30GE) {
            $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j3x.css');
        } else {
            if (FLEXI_J16GE) {
                $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j25.css');
            } else {
                $document->addStyleSheet(JURI::base(true) . '/components/com_flexicontent/assets/css/j15.css');
            }
        }
        // Add js function to overload the joomla submitform
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/admin.js');
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/validate.js');
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScript(JURI::base(true) . '/components/com_flexicontent/assets/js/itemscreen.js');
        // ***********************************************
        // Get item and create form (that loads item data)
        // ***********************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        // ** WE NEED TO get OR decide the Content Type, before we call the getItem
        // ** We rely on typeid Request variable to decide type for new items so make sure this is set,
        // ZERO means allow user to select type, but if user is only allowed a single type, then autoselect it!
        if ($menu && isset($menu->query['typeid'])) {
            JRequest::setVar('typeid', (int) $menu->query['typeid']);
            // This also forces zero if value not set
        }
        $new_typeid = JRequest::getVar('typeid', 0, '', 'int');
        if (!$new_typeid) {
            $types = $model->getTypeslist($type_ids_arr = false, $check_perms = true);
            if ($types && count($types) == 1) {
                $new_typeid = $types[0]->id;
            }
            JRequest::setVar('typeid', $new_typeid);
            $canCreateType = true;
        }
        $item = $this->get('Item');
        if (FLEXI_J16GE) {
            $form = $this->get('Form');
        }
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // *********************************************************************************************************
        // Get language stuff, and also load Template-Specific language file to override or add new language strings
        // *********************************************************************************************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $langs = FLEXIUtilities::getLanguages('code');
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            FLEXIUtilities::loadTemplateLanguageFile($item->parameters->get('ilayout', 'default'));
        }
        // ****************************************************************************************
        // CHECK EDIT / CREATE PERMISSIONS (this is duplicate since it also done at the controller)
        // ****************************************************************************************
        // new item and ownership variables
        $isnew = !$item->id;
        $isOwner = $item->created_by == $user->get('id');
        // create and set (into HTTP request) a unique item id for plugins that needed it
        JRequest::setVar('unique_tmp_itemid', $item->id ? $item->id : date('_Y_m_d_h_i_s_', time()) . uniqid(true));
        // Component / Menu Item parameters
        $allowunauthorize = $params->get('allowunauthorize', 0);
        // allow unauthorised user to submit new content
        $unauthorized_page = $params->get('unauthorized_page', '');
        // page URL for unauthorized users (via global configuration)
        $notauth_itemid = $params->get('notauthurl', '');
        // menu itemid (to redirect) when user is not authorized to create content
        // Create captcha field or messages
        if (FLEXI_J16GE) {
            $use_captcha = $params->get('use_captcha', 1);
            // 1 for guests, 2 for any user
            $captcha_formop = $params->get('captcha_formop', 0);
            // 0 for submit, 1 for submit/edit (aka always)
            $display_captcha = $use_captcha >= 2 || $use_captcha == 1 && $user->guest;
            $display_captcha = $display_captcha && ($isnew || $captcha_formop);
            // Force using recaptcha
            if ($display_captcha) {
                // Try to force the use of recaptcha plugin
                JFactory::getConfig()->set('captcha', 'recaptcha');
                if (!$app->getCfg('captcha')) {
                    $captcha_errmsg = '-- Please select <b>CAPTCHA Type</b> at global Joomla parameters';
                } else {
                    if ($app->getCfg('captcha') != 'recaptcha') {
                        $captcha_errmsg = '-- Captcha Type: <b>' . $app->getCfg('captcha') . '</b> not supported';
                    } else {
                        if (!JPluginHelper::isEnabled('captcha', 'recaptcha')) {
                            $captcha_errmsg = '-- Please enable & configure the Joomla <b>ReCaptcha Plugin</b>';
                        } else {
                            $captcha_errmsg = '';
                            JPluginHelper::importPlugin('captcha');
                            $dispatcher->trigger('onInit', 'dynamic_recaptcha_1');
                            $field_description = JText::_('FLEXI_CAPTCHA_ENTER_CODE_DESC');
                            $label_tooltip = 'class="hasTip flexi_label" title="' . '::' . htmlspecialchars($field_description, ENT_COMPAT, 'UTF-8') . '"';
                            $captcha_field = '
						<label id="recaptcha_response_field-lbl" for="recaptcha_response_field" ' . $label_tooltip . ' >
						' . JText::_('FLEXI_CAPTCHA_ENTER_CODE') . '
						</label>
						<div class="container_fcfield container_fcfield_name_captcha">
							<div id="dynamic_recaptcha_1"></div>
						</div>
						';
                        }
                    }
                }
            }
        }
        // User Group / Author parameters
        $db->setQuery('SELECT author_basicparams FROM #__flexicontent_authors_ext WHERE user_id = ' . $user->id);
        $authorparams = $db->loadResult();
        $authorparams = FLEXI_J16GE ? new JRegistry($authorparams) : new JParameter($authorparams);
        $max_auth_limit = $authorparams->get('max_auth_limit', 0);
        // maximum number of content items the user can create
        if (!$isnew) {
            // EDIT action
            // Finally check if item is currently being checked-out (currently being edited)
            if ($model->isCheckedOut($user->get('id'))) {
                $msg = JText::sprintf('FLEXI_DESCBEINGEDITTED', $model->get('title'));
                $app->redirect(JRoute::_('index.php?view=' . FLEXI_ITEMVIEW . '&cid=' . $model->get('catid') . '&id=' . $model->get('id'), false), $msg);
            }
            //Checkout the item
            $model->checkout();
            if (FLEXI_J16GE) {
                $canEdit = $model->getItemAccess()->get('access-edit');
                // includes privileges edit and edit-own
                // ALTERNATIVE 1
                //$asset = 'com_content.article.' . $model->get('id');
                //$canEdit = $user->authorise('core.edit', $asset) || ($user->authorise('core.edit.own', $asset) && $model->get('created_by') == $user->get('id'));
                // ALTERNATIVE 2
                //$rights = FlexicontentHelperPerm::checkAllItemAccess($user->get('id'), 'item', $model->get('id'));
                //$canEdit = in_array('edit', $rights) || (in_array('edit.own', $rights) && $model->get('created_by') == $user->get('id')) ;
            } else {
                if ($user->gid >= 25) {
                    $canEdit = true;
                } else {
                    if (FLEXI_ACCESS) {
                        $rights = FAccess::checkAllItemAccess('com_content', 'users', $user->gmid, $model->get('id'), $model->get('catid'));
                        $canEdit = in_array('edit', $rights) || in_array('editown', $rights) && $model->get('created_by') == $user->get('id');
                    } else {
                        $canEdit = $user->authorize('com_content', 'edit', 'content', 'all') || $user->authorize('com_content', 'edit', 'content', 'own') && $model->get('created_by') == $user->get('id');
                        //$canEdit = ($user->gid >= 20);  // At least J1.5 Editor
                    }
                }
            }
            if (!$canEdit) {
                // No edit privilege, check if item is editable till logoff
                if ($session->has('rendered_uneditable', 'flexicontent')) {
                    $rendered_uneditable = $session->get('rendered_uneditable', array(), 'flexicontent');
                    $canEdit = isset($rendered_uneditable[$model->get('id')]) && $rendered_uneditable[$model->get('id')];
                }
            }
            if (!$canEdit) {
                if ($user->guest) {
                    $uri = JFactory::getURI();
                    $return = $uri->toString();
                    $fcreturn = serialize(array('id' => @$this->_item->id, 'cid' => $cid));
                    // a special url parameter, used by some SEF code
                    $com_users = FLEXI_J16GE ? 'com_users' : 'com_user';
                    $url = $params->get('login_page', 'index.php?option=' . $com_users . '&view=login');
                    $return = strtr(base64_encode($return), '+/=', '-_,');
                    $url .= '&return=' . $return;
                    //$url .= '&return='.urlencode(base64_encode($return));
                    $url .= '&fcreturn=' . base64_encode($fcreturn);
                    JError::raiseWarning(403, JText::sprintf("FLEXI_LOGIN_TO_ACCESS", $url));
                    $app->redirect($url);
                } else {
                    if ($unauthorized_page) {
                        //  unauthorized page via global configuration
                        JError::raiseNotice(403, JText::_('FLEXI_ALERTNOTAUTH_TASK'));
                        $app->redirect($unauthorized_page);
                    } else {
                        // user isn't authorize to edit this content
                        $msg = JText::_('FLEXI_ALERTNOTAUTH_TASK');
                        if (FLEXI_J16GE) {
                            throw new Exception($msg, 403);
                        } else {
                            JError::raiseError(403, $msg);
                        }
                    }
                }
            }
        } else {
            // CREATE action
            if (FLEXI_J16GE) {
                $canAdd = $model->getItemAccess()->get('access-create');
                // includes check of creating in at least one category
                $not_authorised = !$canAdd;
            } else {
                if ($user->gid >= 25) {
                    $not_authorised = 0;
                } else {
                    if (FLEXI_ACCESS) {
                        $canAdd = FAccess::checkUserElementsAccess($user->gmid, 'submit');
                        $not_authorised = !(@$canAdd['content'] || @$canAdd['category']);
                    } else {
                        $canAdd = $user->authorize('com_content', 'add', 'content', 'all');
                        //$canAdd = ($user->gid >= 19);  // At least J1.5 Author
                        $not_authorised = !$canAdd;
                    }
                }
            }
            // Check if Content Type can be created by current user
            if (empty($canCreateType)) {
                if ($new_typeid) {
                    $canCreateType = $model->canCreateType(array($new_typeid));
                    // Can create given Content Type
                } else {
                    $canCreateType = $model->canCreateType();
                    // Can create at least one Content Type
                }
            }
            $not_authorised = $not_authorised || !$canCreateType;
            // Allow item submission by unauthorized users, ... even guests ...
            if ($allowunauthorize == 2) {
                $allowunauthorize = !$user->guest;
            }
            if ($not_authorised && !$allowunauthorize) {
                if (!$canCreateType) {
                    $type_name = isset($types[$new_typeid]) ? '"' . JText::_($types[$new_typeid]->name) . '"' : JText::_('FLEXI_ANY');
                    $msg = JText::sprintf('FLEXI_NO_ACCESS_CREATE_CONTENT_OF_TYPE', $type_name);
                } else {
                    $msg = JText::_('FLEXI_ALERTNOTAUTH_CREATE');
                }
            } else {
                if ($max_auth_limit) {
                    $db->setQuery('SELECT COUNT(id) FROM #__content WHERE created_by = ' . $user->id);
                    $authored_count = $db->loadResult();
                    $content_is_limited = $authored_count >= $max_auth_limit;
                    $msg = $content_is_limited ? JText::sprintf('FLEXI_ALERTNOTAUTH_CREATE_MORE', $max_auth_limit) : '';
                }
            }
            if ($not_authorised && !$allowunauthorize || @$content_is_limited) {
                // User isn't authorize to add ANY content
                if ($notauth_menu = $app->getMenu()->getItem($notauth_itemid)) {
                    // a. custom unauthorized submission page via menu item
                    $internal_link_vars = @$notauth_menu->component ? '&Itemid=' . $notauth_itemid . '&option=' . $notauth_menu->component : '';
                    $notauthurl = JRoute::_($notauth_menu->link . $internal_link_vars, false);
                    JError::raiseNotice(403, $msg);
                    $app->redirect($notauthurl);
                } else {
                    if ($unauthorized_page) {
                        // b. General unauthorized page via global configuration
                        JError::raiseNotice(403, $msg);
                        $app->redirect($unauthorized_page);
                    } else {
                        // c. Finally fallback to raising a 403 Exception/Error that will redirect to site's default 403 unauthorized page
                        if (FLEXI_J16GE) {
                            throw new Exception($msg, 403);
                        } else {
                            JError::raiseError(403, $msg);
                        }
                    }
                }
            }
        }
        // *********************************************
        // Get more variables to push into the FORM view
        // *********************************************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Create the type parameters
        $tparams = $this->get('Typeparams');
        $tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
        // Merge item parameters, or type/menu parameters for new item
        if ($isnew) {
            if ($new_typeid) {
                $params->merge($tparams);
            }
            // Apply type configuration if it type is set
            if ($menu) {
                $params->merge($menu_params);
            }
            // Apply menu configuration if it menu is set, to override type configuration
        } else {
            $params = $item->parameters;
        }
        // Check if saving an item that translates an original content in site's default language
        $is_content_default_lang = substr(flexicontent_html::getSiteDefaultLang(), 0, 2) == substr($item->language, 0, 2);
        $modify_untraslatable_values = $enable_translation_groups && !$is_content_default_lang && $item->lang_parent_id && $item->lang_parent_id != $item->id;
        // *****************************************************************************
        // Get (CORE & CUSTOM) fields and their VERSIONED values and then
        // (a) Apply Content Type Customization to CORE fields (label, description, etc)
        // (b) Create the edit html of the CUSTOM fields by triggering 'onDisplayField'
        // *****************************************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $fields = $this->get('Extrafields');
        if ($print_logging_info) {
            $fc_run_times['get_field_vals'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        foreach ($fields as $field) {
            // a. Apply CONTENT TYPE customizations to CORE FIELDS, e.g a type specific label & description
            // NOTE: the field parameters are already created so there is not need to call this for CUSTOM fields, which do not have CONTENT TYPE customizations
            if ($field->iscore) {
                FlexicontentFields::loadFieldConfig($field, $item);
            }
            // b. Create field 's editing HTML (the form field)
            // NOTE: this is DONE only for CUSTOM fields, since form field html is created by the form for all CORE fields, EXCEPTION is the 'text' field (see bellow)
            if (!$field->iscore) {
                if (FLEXI_J16GE) {
                    $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                } else {
                    if (FLEXI_ACCESS && $user->gid < 25) {
                        $is_editable = !$field->valueseditable || FAccess::checkAllContentAccess('com_content', 'submit', 'users', $user->gmid, 'field', $field->id);
                    } else {
                        $is_editable = 1;
                    }
                }
                if (!$is_editable) {
                    $field->html = '<div class="fc-mssg fc-warning">' . JText::_('FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                } else {
                    if ($modify_untraslatable_values && $field->untranslatable) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_('FLEXI_FIELD_VALUE_IS_UNTRANSLATABLE') . '</div>';
                    } else {
                        FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // Tags used by the item
        $usedtagsids = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        //$usedtagsIds 	= $isnew ? array() : $fields['tags']->value;
        $usedtagsdata = $model->getUsedtagsData($usedtagsids);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsids);
        //echo "<br/>usedtags (data): "; print_r($usedtagsdata);
        // Compatibility for old overriden templates ...
        if (!FLEXI_J16GE) {
            $tags = $this->get('Alltags');
            $usedtags = $this->get('UsedtagsIds');
        }
        // Load permissions (used by form template)
        $perms = $this->_getItemPerms($item, $typesselected);
        // Get the edit lists
        $lists = $this->_buildEditLists($perms, $params, $authorparams, $typesselected, $tparams);
        // Get number of subscribers
        $subscribers = $this->get('SubscribersCount');
        // Get menu overridden categories/main category fields
        $menuCats = $this->_getMenuCats($item, $perms, $params);
        // Create submit configuration (for new items) into the session
        $submitConf = $this->_createSubmitConf($item, $perms, $params);
        // Create placement configuration for CORE properties
        $placementConf = $this->_createPlacementConf($fields, $params, $item);
        // Item language related vars
        if (FLEXI_FISH || FLEXI_J16GE) {
            $languages = FLEXIUtilities::getLanguages();
            $itemlang = new stdClass();
            $itemlang->shortcode = substr($item->language, 0, 2);
            $itemlang->name = $languages->{$item->language}->name;
            $itemlang->image = '<img src="' . @$languages->{$item->language}->imgsrc . '" alt="' . $languages->{$item->language}->name . '" />';
        }
        //Load the JEditor object
        $editor = JFactory::getEditor();
        // **********************************************************
        // Calculate a (browser window) page title and a page heading
        // **********************************************************
        // Verify menu item points to current FLEXIcontent object
        if ($menu) {
            $menu_matches = false;
            $view_ok = FLEXI_ITEMVIEW == @$menu->query['view'] || 'article' == @$menu->query['view'];
            $menu_matches = $view_ok;
            //$menu_params = FLEXI_J16GE ? $menu->params : new JParameter($menu->params);  // Get active menu item parameters
        } else {
            $menu_matches = false;
        }
        // MENU ITEM matched, use its page heading (but use menu title if the former is not set)
        if ($menu_matches) {
            $default_heading = FLEXI_J16GE ? $menu->title : $menu->name;
            // Cross set (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
            $params->def('page_heading', $params->get('page_title', $default_heading));
            $params->def('page_title', $params->get('page_heading', $default_heading));
            $params->def('show_page_heading', $params->get('show_page_title', 0));
            $params->def('show_page_title', $params->get('show_page_heading', 0));
        } else {
            // Calculate default page heading (=called page title in J1.5), which in turn will be document title below !! ...
            $default_heading = !$isnew ? JText::_('FLEXI_EDIT') : JText::_('FLEXI_NEW');
            // Decide to show page heading (=J1.5 page title), there is no need for this in item view
            $show_default_heading = 0;
            // Set both (show_) page_heading / page_title for compatibility of J2.5+ with J1.5 template (and for J1.5 with J2.5 template)
            $params->set('page_title', $default_heading);
            $params->set('page_heading', $default_heading);
            $params->set('show_page_heading', $show_default_heading);
            $params->set('show_page_title', $show_default_heading);
        }
        // ************************************************************
        // Create the document title, by from page title and other data
        // ************************************************************
        // Use the page heading as document title, (already calculated above via 'appropriate' logic ...)
        $doc_title = $params->get('page_title');
        // Check and prepend or append site name
        if (FLEXI_J16GE) {
            // Not available in J1.5
            // Add Site Name to page title
            if ($app->getCfg('sitename_pagetitles', 0) == 1) {
                $doc_title = $app->getCfg('sitename') . " - " . $doc_title;
            } elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
                $doc_title = $doc_title . " - " . $app->getCfg('sitename');
            }
        }
        // Finally, set document title
        $document->setTitle($doc_title);
        // Add title to pathway
        $pathway = $app->getPathWay();
        $pathway->addItem($doc_title, '');
        // Get pageclass suffix
        $pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
        // Ensure the row data is safe html
        // @TODO: check if this is really required as it conflicts with the escape function in the tmpl
        //JFilterOutput::objectHTMLSafe( $item );
        $this->assign('action', $uri->toString());
        $this->assignRef('item', $item);
        if (FLEXI_J16GE) {
            // most core field are created via calling methods of the form (J2.5)
            $this->assignRef('form', $form);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('params', $params);
        $this->assignRef('lists', $lists);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('editor', $editor);
        $this->assignRef('user', $user);
        if (!FLEXI_J16GE) {
            // compatibility old templates
            $this->assignRef('tags', $tags);
            $this->assignRef('usedtags', $usedtags);
        }
        $this->assignRef('usedtagsdata', $usedtagsdata);
        $this->assignRef('fields', $fields);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('perms', $perms);
        $this->assignRef('document', $document);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('menuCats', $menuCats);
        $this->assignRef('submitConf', $submitConf);
        $this->assignRef('placementConf', $placementConf);
        $this->assignRef('itemlang', $itemlang);
        $this->assignRef('pageclass_sfx', $pageclass_sfx);
        $this->assign('captcha_errmsg', @$captcha_errmsg);
        $this->assign('captcha_field', @$captcha_field);
        // **************************************************************************************
        // Load a different template file for parameters depending on whether we use FLEXI_ACCESS
        // **************************************************************************************
        if (!FLEXI_J16GE) {
            if (FLEXI_ACCESS) {
                $formparams = new JParameter('', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'models' . DS . 'item2.xml');
            } else {
                $formparams = new JParameter('', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'models' . DS . 'item.xml');
            }
        }
        // ****************************************************************
        // SET INTO THE FORM, parameter values for various parameter groups
        // ****************************************************************
        if (!FLEXI_J16GE) {
            // Permissions (Access) Group
            if (!FLEXI_ACCESS) {
                $formparams->set('access', $item->access);
            }
            // Set: (Publication) Details Group
            $created_by = intval($item->created_by) ? intval($item->created_by) : $user->get('id');
            $formparams->set('created_by', $created_by);
            $formparams->set('created_by_alias', $item->created_by_alias);
            $formparams->set('created', JHTML::_('date', $item->created, '%Y-%m-%d %H:%M:%S'));
            $formparams->set('publish_up', JHTML::_('date', $item->publish_up, '%Y-%m-%d %H:%M:%S'));
            if (JHTML::_('date', $item->publish_down, '%Y') <= 1969 || $item->publish_down == $nullDate || empty($item->publish_down)) {
                $formparams->set('publish_down', JText::_('FLEXI_NEVER'));
            } else {
                $formparams->set('publish_down', JHTML::_('date', $item->publish_down, '%Y-%m-%d %H:%M:%S'));
            }
            // Set:  Attributes (parameters) Group, (these are retrieved from the item table column 'attribs')
            // (also contains templates parameters, but we will use these individual for every template ... see below)
            $formparams->loadINI($item->attribs);
            //echo "<pre>"; print_r($formparams->_xml['themes']->_children[0]);  echo "<pre>"; print_r($formparams->_xml['themes']->param[0]); exit;
            foreach ($formparams->_xml['themes']->_children as $i => $child) {
                if (isset($child->_attributes['enableparam']) && !$params->get($child->_attributes['enableparam'])) {
                    unset($formparams->_xml['themes']->_children[$i]);
                    unset($formparams->_xml['themes']->param[$i]);
                }
            }
            // Set: Metadata (parameters) Group
            // NOTE: (2 params from 2 item table columns, and then multiple params from item table column 'metadata')
            $formparams->set('description', $item->metadesc);
            $formparams->set('keywords', $item->metakey);
            if (!empty($item->metadata)) {
                $formparams->loadINI($item->metadata->toString());
            }
            // Now create the sliders object,
            // And also push the Form Parameters object into the template (Template Parameters object is seperate)
            jimport('joomla.html.pane');
            $pane = JPane::getInstance('Sliders');
            //$tabs_pane = JPane::getInstance('Tabs');
            $this->assignRef('pane', $pane);
            //$this->assignRef('tabs_pane'	, $tabs_pane);
            $this->assignRef('formparams', $formparams);
        } else {
            if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $nullDate) {
                $item->publish_down = JText::_('FLEXI_NEVER');
            }
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        } else {
            if (!is_array($allowed_tmpls)) {
                $allowed_tmpls = !FLEXI_J16GE ? array($allowed_tmpls) : explode("|", $allowed_tmpls);
            }
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            if (FLEXI_J16GE) {
                $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
                $jform->load($tmpl->params);
                $tmpl->params = $jform;
                foreach ($tmpl->params->getGroup('attribs') as $field) {
                    $fieldname = $field->__get('fieldname');
                    $value = $item->itemparams->get($fieldname);
                    if (strlen($value)) {
                        $tmpl->params->setValue($fieldname, 'attribs', $value);
                    }
                }
            } else {
                $tmpl->params->loadINI($item->attribs);
            }
        }
        $this->assignRef('tmpls', $tmpls);
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        parent::display($tpl);
        if ($print_logging_info) {
            $fc_run_times['form_rendering'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
    }
Exemplo n.º 8
0
 /**
  * Method to get the active filter result
  * 
  * @access private
  * @return string
  * @since 1.5
  */
 function _getFiltered(&$filter, $value, $return_sql = true)
 {
     $field_type = $filter->field_type;
     // Sanitize filter values as integers for field that use integer values
     if (in_array($field_type, array('createdby', 'modifiedby', 'type', 'categories', 'tags'))) {
         $values = is_array($value) ? $value : array($value);
         foreach ($values as $i => $v) {
             $values[$i] = (int) $v;
         }
     }
     switch ($field_type) {
         case 'createdby':
             $filter_query = ' AND i.created_by IN (' . implode(",", $values) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'modifiedby':
             $filter_query = ' AND i.modified_by IN (' . implode(",", $values) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'type':
             //$filter_query = ' AND ie.type_id IN ('. implode(",", $values) .')';   // no db quoting needed since these were typecasted to ints
             $query = 'SELECT item_id' . ' FROM #__flexicontent_items_ext' . ' WHERE type_id IN (' . implode(",", $values) . ')';
             //$filter_query = ' AND i.id IN (' . $query . ')';
             break;
         case 'state':
             $stateids = array('PE' => -3, 'OQ' => -4, 'IP' => -5, 'P' => 1, 'U' => 0, 'A' => FLEXI_J16GE ? 2 : -1, 'T' => -2);
             $values = is_array($value) ? $value : array($value);
             $filt_states = array();
             foreach ($values as $i => $v) {
                 if (isset($stateids[$v])) {
                     $filt_states[] = $stateids[$v];
                 }
             }
             $filter_query = !count($values) ? ' AND 0 ' : ' AND i.state IN (' . implode(",", $filt_states) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'categories':
             //$filter_query = ' AND rel.catid IN ('. implode(",", $values) .')';
             global $globalcats;
             $cparams = $this->_params;
             $display_subcats = $cparams->get('display_subcategories_items', 2);
             // include subcategory items
             $query_catids = array();
             foreach ($values as $id) {
                 $query_catids[$id] = 1;
                 if ($display_subcats == 2 && !empty($globalcats[$id]->descendantsarray)) {
                     foreach ($globalcats[$id]->descendantsarray as $subcatid) {
                         $query_catids[$subcatid] = 1;
                     }
                 }
             }
             $query_catids = array_keys($query_catids);
             $query = 'SELECT itemid' . ' FROM #__flexicontent_cats_item_relations' . ' WHERE catid IN (' . implode(",", $query_catids) . ')';
             //$filter_query = ' AND i.id IN (' . $query . ')';
             break;
         case 'tags':
             $query = 'SELECT itemid' . ' FROM #__flexicontent_tags_item_relations' . ' WHERE tid IN (' . implode(",", $values) . ')';
             //$filter_query = ' AND i.id IN (' . $query . ')';
             break;
         default:
             // Make sure plugin file of current file is loaded and then check if custom filtering function exists
             $field_type_file = $filter->iscore ? 'core' : $field_type;
             $path = JPATH_ROOT . DS . 'plugins' . DS . 'flexicontent_fields' . DS . strtolower($field_type_file) . (FLEXI_J16GE ? DS . strtolower($field_type_file) : "") . '.php';
             if (file_exists($path)) {
                 require_once $path;
                 $method_exists = method_exists("plgFlexicontent_fields{$field_type_file}", "getFiltered");
             }
             // Use custom field filtering if 'getFiltered' plugin method exists, otherwise try to use our default filtering function
             $filtered = !@$method_exists ? FlexicontentFields::getFiltered($filter, $value, $return_sql) : FLEXIUtilities::call_FC_Field_Func($field_type_file, 'getFiltered', array(&$filter, &$value, &$return_sql));
             break;
     }
     if (!isset($filter_query)) {
         if (isset($filtered)) {
             // nothing to do
         } else {
             if (!isset($query)) {
                 $filtered = '';
                 echo "Unhandled case for filter: " . $field->name . " in 'FlexicontentModelCategory::getFiltered()', query variable not set<br/>\n";
             } else {
                 if (!$return_sql) {
                     //echo "<br>GET FILTERED Items (cat model) -- [".$filter->name."] using in-query ids :<br>". $query."<br>\n";
                     $db = JFactory::getDBO();
                     $db->setQuery($query);
                     $filtered = $db->loadColumn();
                     if ($db->getErrorNum()) {
                         JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($db->getErrorMsg()), 'error');
                     }
                 } else {
                     if ($return_sql === 2) {
                         $db = JFactory::getDBO();
                         static $iids_tblname = array();
                         if (!isset($iids_tblname[$filter->id])) {
                             $iids_tblname[$filter->id] = 'fc_filter_iids_' . $filter->id;
                         }
                         $tmp_tbl = $iids_tblname[$filter->id];
                         try {
                             // Use sub-query on temporary table
                             $db->setQuery('CREATE TEMPORARY TABLE IF NOT EXISTS ' . $tmp_tbl . ' (id INT, KEY(`id`))');
                             $db->query();
                             $db->setQuery('TRUNCATE TABLE ' . $tmp_tbl);
                             $db->query();
                             $db->setQuery('INSERT INTO ' . $tmp_tbl . ' ' . $query);
                             $db->query();
                             $_query = $query;
                             $query = 'SELECT id FROM ' . $tmp_tbl;
                             //echo "<br/><br/>GET FILTERED Items (cat model) -- [".$filter->name."] using temporary table: ".$query." for :".$_query ." <br/><br/>";
                             /*$db->setQuery($query);
                             		$data = $db->loadObjectList();
                             		echo "<pre>";
                             		print_r($data);
                             		exit;*/
                         } catch (Exception $e) {
                             // Ignore table creation error
                             //if ($db->getErrorNum())  echo 'SQL QUERY ERROR:<br/>'.nl2br($db->getErrorMsg());
                             //echo "<br/><br/>GET FILTERED Items (cat model) -- [".$filter->name."] using subquery: ".$query." <br/><br/>";
                         }
                     } else {
                         //echo "<br/><br/>GET FILTERED Items (cat model) -- [".$filter->name."] using subquery: ".$query." <br/><br/>";
                     }
                 }
             }
         }
         if (!isset($filtered) && isset($query)) {
             $filtered = ' AND i.id IN (' . $query . ')';
         }
         // An empty return value means no matching values were found
         $filtered = empty($filtered) ? ' AND 0 ' : $filtered;
         // A string mean a subquery was returned, while an array means that item ids we returned
         $filter_query = is_array($filtered) ? ' AND i.id IN (' . implode(',', $filtered) . ')' : $filtered;
     }
     //echo "<br/>".$filter_query."<br/>";
     return $filter_query;
 }
 /**
  * Search method
  *
  * The sql must return the following fields that are used in a common display routine:
  *
  *   href, title, section, created, text, browsernav
  *
  * @param string Target search string
  * @param string matching option, natural|natural_expanded|exact|any|all
  * @param string ordering option, newest|oldest|popular|alpha|category
  * @param mixed An array if restricted to areas, null if search all
  */
 function onContentSearch($text, $phrase = '', $ordering = '', $areas = null)
 {
     $app = JFactory::getApplication();
     $view = JRequest::getCMD('view');
     $app->setUserState('fc_view_total_' . $view, 0);
     $app->setUserState('fc_view_limit_max_' . $view, 0);
     // Check if not requested search areas, inside this search areas of this plugin
     if (is_array($areas) && !array_intersect($areas, array_keys($this->onContentSearchAreas()))) {
         return array();
     }
     // Initialize some variables
     $db = JFactory::getDBO();
     $user = JFactory::getUser();
     $menu = $app->getMenu()->getActive();
     // Get the COMPONENT only parameters and merge current menu item parameters
     $params = clone JComponentHelper::getParams('com_flexicontent');
     if ($menu) {
         $params->merge($menu->params);
     }
     // some parameter shortcuts for SQL query
     $show_noauth = $params->get('show_noauth', 0);
     $orderby_override = $params->get('orderby_override', 1);
     // Compatibility text search (LIKE %word%) for language without spaces
     $filter_word_like_any = $params->get('filter_word_like_any', 0);
     // ************************************************
     // some parameter shortcuts common with search view
     // ************************************************
     $canseltypes = $params->get('canseltypes', 1);
     $txtmode = $params->get('txtmode', 0);
     // 0: BASIC Index, 1: ADVANCED Index without search fields user selection, 2: ADVANCED Index with search fields user selection
     // Get if text searching according to specific (single) content type
     $show_txtfields = $params->get('show_txtfields', 1);
     //0:hide, 1:according to content, 2:use custom configuration
     $show_txtfields = $txtmode ? 0 : $show_txtfields;
     // disable this flag if using BASIC index for text search
     // Get if filtering according to specific (single) content type
     $show_filters = $params->get('show_filters', 1);
     //0:hide, 1:according to content, 2:use custom configuration
     // Force single type selection and showing the content type selector
     $type_based_search = $show_filters == 1 || $show_txtfields == 1;
     $canseltypes = $type_based_search ? 1 : $canseltypes;
     // ********************************************************************
     // Get Content Types allowed for user selection in the Search Form
     // Also retrieve their configuration, plus the currently selected types
     // ********************************************************************
     // Get them from configuration
     $contenttypes = $params->get('contenttypes', array());
     // Sanitize them
     $contenttypes = !is_array($contenttypes) ? array($contenttypes) : $contenttypes;
     $contenttypes = array_unique(array_map('intval', $contenttypes));
     // Make sure these are integers since we will be using them UNQUOTED
     // Force hidden content type selection if only 1 content type was initially configured
     $canseltypes = count($contenttypes) == 1 ? 0 : $canseltypes;
     // Type data and configuration (parameters), if no content types specified then all will be retrieved
     $typeData = flexicontent_db::getTypeData(implode(",", $contenttypes));
     $contenttypes = array();
     foreach ($typeData as $tdata) {
         $contenttypes[] = $tdata->id;
     }
     // Get Content Types to use either those currently selected in the Search Form, or those hard-configured in the search menu item
     if ($canseltypes) {
         $form_contenttypes = JRequest::getVar('contenttypes', array());
         // Sanitize them
         $form_contenttypes = !is_array($form_contenttypes) ? array($form_contenttypes) : $form_contenttypes;
         $form_contenttypes = array_unique(array_map('intval', $form_contenttypes));
         // Make sure these are integers since we will be using them UNQUOTED
         $_contenttypes = array_intersect($contenttypes, $form_contenttypes);
         if (!empty($_contenttypes)) {
             $contenttypes = $_contenttypes;
         }
         // catch empty case: no content types were given or not-allowed content types were passed
     }
     // Check for zero content type (can occur during sanitizing content ids to integers)
     if (!empty($contenttypes)) {
         foreach ($contenttypes as $i => $v) {
             if (!strlen($contenttypes[$i])) {
                 unset($contenttypes[$i]);
             }
         }
     }
     // Type based seach, get a single content type (first one, if more than 1 were given ...)
     if ($type_based_search && !empty($contenttypes)) {
         $single_contenttype = reset($contenttypes);
         $contenttypes = array($single_contenttype);
     } else {
         $single_contenttype = false;
     }
     // *************************************
     // Text Search Fields of the search form
     // *************************************
     if (!$txtmode) {
         $txtflds = array();
         $fields_text = array();
     } else {
         $txtflds = '';
         if ($show_txtfields) {
             if ($show_txtfields == 1) {
                 $txtflds = $single_contenttype ? $typeData[$single_contenttype]->params->get('searchable', '') : '';
             } else {
                 $txtflds = $params->get('txtflds', '');
             }
         }
         // Sanitize them
         $txtflds = preg_replace("/[\"'\\\\]/u", "", $txtflds);
         $txtflds = array_unique(preg_split("/\\s*,\\s*/u", $txtflds));
         if (!strlen($txtflds[0])) {
             unset($txtflds[0]);
         }
         // Create a comma list of them
         $txtflds_list = count($txtflds) ? "'" . implode("','", $txtflds) . "'" : '';
         // Retrieve field properties/parameters, verifying the support to be used as Text Search Fields
         // This will return all supported fields if field limiting list is empty
         $fields_text = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', $txtflds_list, $contenttypes, $load_params = true, 0, 'search');
         if (empty($fields_text)) {
             // all entries of field limiting list were invalid , get ALL
             if (!empty($contenttypes)) {
                 $fields_text = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', null, $contenttypes, $load_params = true, 0, 'search');
             } else {
                 $fields_text = array();
             }
         }
     }
     // ********************************
     // Filter Fields of the search form
     // ********************************
     // Get them from type configuration or from search menu item
     $filtflds = '';
     if ($show_filters) {
         if ($show_filters == 1) {
             $filtflds = $single_contenttype ? $typeData[$single_contenttype]->params->get('filters', '') : '';
         } else {
             $filtflds = $params->get('filtflds', '');
         }
     }
     // Sanitize them
     $filtflds = preg_replace("/[\"'\\\\]/u", "", $filtflds);
     $filtflds = array_unique(preg_split("/\\s*,\\s*/u", $filtflds));
     if (!strlen($filtflds[0])) {
         unset($filtflds[0]);
     }
     // Create a comma list of them
     $filtflds_list = count($filtflds) ? "'" . implode("','", $filtflds) . "'" : '';
     // Retrieve field properties/parameters, verifying the support to be used as Filter Fields
     // This will return all supported fields if field limiting list is empty
     if (count($filtflds)) {
         $filters_tmp = FlexicontentFields::getSearchFields($key = 'name', $indexer = 'advanced', $filtflds_list, $contenttypes, $load_params = true, 0, 'filter');
         // Use custom order
         $filters = array();
         if ($canseltypes && $show_filters) {
             foreach ($filtflds as $field_name) {
                 if (empty($filters_tmp[$field_name])) {
                     continue;
                 }
                 $filter_id = $filters_tmp[$field_name]->id;
                 $filters[$filter_id] = $filters_tmp[$field_name];
             }
         } else {
             foreach ($filters_tmp as $filter) {
                 $filters[$filter->id] = $filter;
                 // index by filter_id in this case too (for consistency, although we do not use the array index ?)
             }
         }
         unset($filters_tmp);
     }
     // If configured filters were not found/invalid for the current content type(s)
     // then retrieve all fields marked as filterable for the give content type(s) this is useful to list per content type filters automatically, even when not set or misconfigured
     if (empty($filters)) {
         if (!empty($contenttypes)) {
             $filters = FlexicontentFields::getSearchFields($key = 'id', $indexer = 'advanced', null, $contenttypes, $load_params = true, 0, 'filter');
         } else {
             $filters = array();
         }
     }
     // **********************
     // Load Plugin parameters
     // **********************
     $plugin = JPluginHelper::getPlugin('search', 'flexiadvsearch');
     $pluginParams = new JRegistry($plugin->params);
     // Shortcuts for plugin parameters
     $search_limit = $params->get('search_limit', $pluginParams->get('search_limit', 20));
     // Limits the returned results of this seach plugin
     $filter_lang = $params->get('filter_lang', $pluginParams->get('filter_lang', 1));
     // Language filtering enabled
     $search_archived = $params->get('search_archived', $pluginParams->get('search_archived', 1));
     // Include archive items into the search
     $browsernav = $params->get('browsernav', $pluginParams->get('browsernav', 2));
     // Open search in window (for value 1)
     // ***************************************************************************************************************
     // Varous other variable USED in the SQL query like (a) current frontend language and (b) -this- plugin specific ordering, (c) null / now dates, (d) etc
     // ***************************************************************************************************************
     // Get current frontend language (fronted user selected)
     $lang = flexicontent_html::getUserCurrentLang();
     // NULL and CURRENT dates,
     // NOTE: the current date needs to use built-in MYSQL function, otherwise filter caching can not work because the CURRENT DATETIME is continuously different !!!
     //$now = JFactory::getDate()->toSql();
     $_nowDate = 'UTC_TIMESTAMP()';
     //$db->Quote($now);
     $nullDate = $db->getNullDate();
     // Section name
     $searchFlexicontent = JText::_('FLEXICONTENT');
     // REMOVED / COMMENTED OUT this feature:
     // Require any OR all Filters ... this can be user selectable
     //$show_filtersop = $params->get('show_filtersop', 1);
     //$default_filtersop = $params->get('default_filtersop', 'all');
     //$FILTERSOP = !$show_filtersop ? $default_filtersop : JRequest::getVar('filtersop', $default_filtersop);
     // ****************************************
     // Create WHERE clause part for Text Search
     // ****************************************
     $si_tbl = !$txtmode ? 'flexicontent_items_ext' : 'flexicontent_advsearch_index';
     $search_prefix = JComponentHelper::getParams('com_flexicontent')->get('add_search_prefix') ? 'vvv' : '';
     // SEARCH WORD Prefix
     $text = preg_replace('/(\\b[^\\s,\\.]+\\b)/u', $search_prefix . '$0', trim($text));
     if (strlen($text)) {
         $ts = !$txtmode ? 'ie' : 'ts';
         $escaped_text = $db->escape($text, true);
         $quoted_text = $db->Quote($escaped_text, false);
         switch ($phrase) {
             case 'natural':
                 if ($filter_word_like_any) {
                     $_text_match = ' LOWER (' . $ts . '.search_index) LIKE ' . $db->Quote('%' . $escaped_text . '%', false);
                 } else {
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ') ';
                 }
                 break;
             case 'natural_expanded':
                 $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' WITH QUERY EXPANSION) ';
                 break;
             case 'exact':
                 $words = preg_split('/\\s\\s*/u', $text);
                 $stopwords = array();
                 $shortwords = array();
                 if (!$search_prefix) {
                     $words = flexicontent_db::removeInvalidWords($words, $stopwords, $shortwords, $si_tbl, 'search_index', $isprefix = 0);
                 }
                 if (empty($words)) {
                     // All words are stop-words or too short, we could try to execute a query that only contains a LIKE %...% , but it would be too slow
                     JRequest::setVar('ignoredwords', implode(' ', $stopwords));
                     JRequest::setVar('shortwords', implode(' ', $shortwords));
                     $_text_match = ' 0=1 ';
                 } else {
                     // speed optimization ... 2-level searching: first require ALL words, then require exact text
                     $newtext = '+' . implode(' +', $words);
                     $quoted_text = $db->escape($newtext, true);
                     $quoted_text = $db->Quote($quoted_text, false);
                     $exact_text = $db->Quote('%' . $escaped_text . '%', false);
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) AND ' . $ts . '.search_index LIKE ' . $exact_text;
                 }
                 break;
             case 'all':
                 $words = preg_split('/\\s\\s*/u', $text);
                 $stopwords = array();
                 $shortwords = array();
                 if (!$search_prefix) {
                     $words = flexicontent_db::removeInvalidWords($words, $stopwords, $shortwords, $si_tbl, 'search_index', $isprefix = 1);
                 }
                 JRequest::setVar('ignoredwords', implode(' ', $stopwords));
                 JRequest::setVar('shortwords', implode(' ', $shortwords));
                 $newtext = '+' . implode('* +', $words) . '*';
                 $quoted_text = $db->escape($newtext, true);
                 $quoted_text = $db->Quote($quoted_text, false);
                 $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) ';
                 break;
             case 'any':
             default:
                 if ($filter_word_like_any) {
                     $_text_match = ' LOWER (' . $ts . '.search_index) LIKE ' . $db->Quote('%' . $escaped_text . '%', false);
                 } else {
                     $words = preg_split('/\\s\\s*/u', $text);
                     $stopwords = array();
                     $shortwords = array();
                     if (!$search_prefix) {
                         $words = flexicontent_db::removeInvalidWords($words, $stopwords, $shortwords, $si_tbl, 'search_index', $isprefix = 1);
                     }
                     JRequest::setVar('ignoredwords', implode(' ', $stopwords));
                     JRequest::setVar('shortwords', implode(' ', $shortwords));
                     $newtext = implode('* ', $words) . '*';
                     $quoted_text = $db->escape($newtext, true);
                     $quoted_text = $db->Quote($quoted_text, false);
                     $_text_match = ' MATCH (' . $ts . '.search_index) AGAINST (' . $quoted_text . ' IN BOOLEAN MODE) ';
                 }
                 break;
         }
         // Construct TEXT SEARCH limitation SUB-QUERY (contained in a AND-WHERE clause)
         $text_where = ' AND ' . $_text_match;
     } else {
         $text_where = '';
     }
     // *******************
     // Create ORDER clause
     // *******************
     // FLEXIcontent search view, use FLEXIcontent ordering
     $orderby_join = '';
     $orderby_col = '';
     if (JRequest::getVar('option') == 'com_flexicontent') {
         $order = '';
         $orderby = flexicontent_db::buildItemOrderBy($params, $order, $_request_var = 'orderby', $_config_param = 'orderby', $_item_tbl_alias = 'i', $_relcat_tbl_alias = 'rel', $_default_order = '', $_default_order_dir = '', $sfx = '', $support_2nd_lvl = false);
         // Create JOIN for ordering items by a custom field (Level 1)
         if ('field' == $order[1]) {
             $orderbycustomfieldid = (int) $params->get('orderbycustomfieldid', 0);
             $orderby_join .= ' LEFT JOIN #__flexicontent_fields_item_relations AS f ON f.item_id = i.id AND f.field_id=' . $orderbycustomfieldid;
         }
         // Create JOIN for ordering items by a custom field (Level 2)
         if ('field' == $order[2]) {
             $orderbycustomfieldid_2nd = (int) $params->get('orderbycustomfieldid' . '_2nd', 0);
             $orderby_join .= ' LEFT JOIN #__flexicontent_fields_item_relations AS f2 ON f2.item_id = i.id AND f2.field_id=' . $orderbycustomfieldid_2nd;
         }
         // Create JOIN for ordering items by author's name
         if (in_array('author', $order) || in_array('rauthor', $order)) {
             $orderby_col = '';
             $orderby_join .= ' LEFT JOIN #__users AS u ON u.id = i.created_by';
         }
         // Create JOIN for ordering items by a most commented
         if (in_array('commented', $order)) {
             $orderby_col = ', count(com.object_id) AS comments_total';
             $orderby_join .= ' LEFT JOIN #__jcomments AS com ON com.object_id = i.id';
         }
         // Create JOIN for ordering items by a most rated
         if (in_array('rated', $order)) {
             $orderby_col = ', (cr.rating_sum / cr.rating_count) * 20 AS votes';
             $orderby_join .= ' LEFT JOIN #__content_rating AS cr ON cr.content_id = i.id';
         }
         // Create JOIN for ordering items by their ordering attribute (in item's main category)
         if (in_array('order', $order)) {
             $orderby_join .= ' LEFT JOIN #__flexicontent_cats_item_relations AS rel ON rel.itemid = i.id AND rel.catid = i.catid';
         }
     } else {
         switch ($ordering) {
             //case 'relevance': $orderby = ' ORDER BY score DESC, i.title ASC'; break;
             case 'oldest':
                 $orderby = 'i.created ASC';
                 break;
             case 'popular':
                 $orderby = 'i.hits DESC';
                 break;
             case 'alpha':
                 $orderby = 'i.title ASC';
                 break;
             case 'category':
                 $orderby = 'c.title ASC, i.title ASC';
                 break;
             case 'newest':
                 $orderby = 'i.created DESC';
                 break;
             default:
                 $orderby = 'i.created DESC';
                 break;
         }
         $orderby = ' ORDER BY ' . $orderby;
     }
     // ****************************************************************************************
     // Create JOIN clause and WHERE clause part for filtering by current (viewing) access level
     // ****************************************************************************************
     $joinaccess = '';
     $andaccess = '';
     $select_access = '';
     // Extra access columns for main category and content type (item access will be added as 'access')
     $select_access .= ',  c.access as category_access, ty.access as type_access';
     if (!$show_noauth) {
         // User not allowed to LIST unauthorized items
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $andaccess .= ' AND ty.access IN (0,' . $aid_list . ')';
         $andaccess .= ' AND  c.access IN (0,' . $aid_list . ')';
         $andaccess .= ' AND  i.access IN (0,' . $aid_list . ')';
         $select_access .= ', 1 AS has_access';
     } else {
         // Access Flags for: content type, main category, item
         $aid_arr = JAccess::getAuthorisedViewLevels($user->id);
         $aid_list = implode(",", $aid_arr);
         $select_access .= ', ' . ' CASE WHEN ' . '  ty.access IN (' . $aid_list . ') AND ' . '   c.access IN (' . $aid_list . ') AND ' . '   i.access IN (' . $aid_list . ') ' . ' THEN 1 ELSE 0 END AS has_access';
     }
     // **********************************************************************************************************************************************************
     // Create WHERE clause part for filtering by current active language, and current selected contend types ( !! although this is possible via a filter too ...)
     // **********************************************************************************************************************************************************
     $andlang = '';
     if ($app->isSite() && (FLEXI_FISH || FLEXI_J16GE && $app->getLanguageFilter()) && $filter_lang) {
         $andlang .= ' AND ( ie.language LIKE ' . $db->Quote($lang . '%') . (FLEXI_J16GE ? ' OR ie.language="*" ' : '') . ' ) ';
     }
     // Filter by currently selected content types
     $andcontenttypes = count($contenttypes) ? ' AND ie.type_id IN (' . implode(",", $contenttypes) . ') ' : '';
     // ***********************************************************************
     // Create the AND-WHERE clause parts for the currentl active Field Filters
     // ***********************************************************************
     $return_sql = 2;
     $filters_where = array();
     foreach ($filters as $field) {
         // Get value of current filter, and SKIP it if value is EMPTY
         $filtervalue = JRequest::getVar('filter_' . $field->id, '');
         $empty_filtervalue_array = is_array($filtervalue) && !strlen(trim(implode('', $filtervalue)));
         $empty_filtervalue_string = !is_array($filtervalue) && !strlen(trim($filtervalue));
         if ($empty_filtervalue_array || $empty_filtervalue_string) {
             continue;
         }
         // Call field filtering of advanced search to find items matching the field filter (an SQL SUB-QUERY is returned)
         $field_filename = $field->iscore ? 'core' : $field->field_type;
         $filtered = FLEXIUtilities::call_FC_Field_Func($field_filename, 'getFilteredSearch', array(&$field, &$filtervalue, &$return_sql));
         // An empty return value means no matching values were found
         $filtered = empty($filtered) ? ' AND 0 ' : $filtered;
         // A string mean a subquery was returned, while an array means that item ids we returned
         $filters_where[$field->id] = is_array($filtered) ? ' AND i.id IN (' . implode(',', $filtered) . ')' : $filtered;
         /*if ($filters_where[$field->id]) {
         			echo "\n<br/>Filter:". $field->name ." : ";   print_r($filtervalue);
         			echo "<br>".$filters_where[$field->id]."<br/>";
         		}*/
     }
     //echo "\n<br/><br/>Filters Active: ". count($filters_where)."<br/>";
     //echo "<pre>"; print_r($filters_where);
     //exit;
     // ******************************************************
     // Create Filters JOIN clauses and AND-WHERE clause parts
     // ******************************************************
     // JOIN clause - USED - to limit returned 'text' to the text of TEXT-SEARCHABLE only fields ... (NOT shared with filters)
     if (!$txtmode) {
         $onBasic_textsearch = $text_where;
         $onAdvanced_textsearch = '';
         $join_textsearch = '';
         $join_textfields = '';
     } else {
         $onBasic_textsearch = '';
         $onAdvanced_textsearch = $text_where;
         $join_textsearch = ' JOIN #__flexicontent_advsearch_index as ts ON ts.item_id = i.id ' . (count($fields_text) ? 'AND ts.field_id IN (' . implode(',', array_keys($fields_text)) . ')' : '');
         $join_textfields = ' JOIN #__flexicontent_fields as f ON f.id=ts.field_id';
     }
     // JOIN clauses ... (shared with filters)
     $join_clauses = '' . ' JOIN #__categories AS c ON c.id = i.catid' . ' JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . ' JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id';
     $join_clauses_with_text = '' . ' JOIN #__categories AS c ON c.id = i.catid' . ' JOIN #__flexicontent_items_ext AS ie ON ie.item_id = i.id' . $onBasic_textsearch . ' JOIN #__flexicontent_types AS ty ON ie.type_id = ty.id' . ($text_where ? $join_textsearch . $onAdvanced_textsearch . $join_textfields : '');
     // AND-WHERE sub-clauses ... (shared with filters)
     $where_conf = ' WHERE 1 ' . ' AND i.state IN (1,-5' . ($search_archived ? ',' . (FLEXI_J16GE ? 2 : -1) : '') . ') ' . ' AND c.published = 1 ' . ' AND ( i.publish_up = ' . $db->Quote($nullDate) . ' OR i.publish_up <= ' . $_nowDate . ' )' . ' AND ( i.publish_down = ' . $db->Quote($nullDate) . ' OR i.publish_down >= ' . $_nowDate . ' )' . $andaccess . $andlang . $andcontenttypes;
     // AND-WHERE sub-clauses for text search ... (shared with filters)
     $and_where_filters = count($filters_where) ? implode(" ", $filters_where) : '';
     // ************************************************
     // Set variables used by filters creation mechanism
     // ************************************************
     global $fc_searchview;
     $fc_searchview['join_clauses'] = $join_clauses;
     $fc_searchview['join_clauses_with_text'] = $join_clauses_with_text;
     $fc_searchview['where_conf_only'] = $where_conf;
     // WHERE of the view (mainly configuration dependent)
     $fc_searchview['filters_where'] = $filters_where;
     // WHERE of the filters
     $fc_searchview['search'] = $text_where;
     // WHERE for text search
     $fc_searchview['params'] = $params;
     // view's parameters
     // *****************************************************************************************************
     // Execute search query.  NOTE this is skipped it if (a) no text-search and no (b) no filters are active
     // *****************************************************************************************************
     // Do not check for 'contentypes' this are based on configuration and not on form submitted data,
     // considering contenttypes or other configuration based parameters, will return all items on initial search view display !
     if (!count($filters_where) && !strlen($text)) {
         return array();
     }
     $print_logging_info = $params->get('print_logging_info');
     if ($print_logging_info) {
         global $fc_run_times;
         $start_microtime = microtime(true);
     }
     // *****************************************
     // Overcome possible group concat limitation
     // *****************************************
     $query = "SET SESSION group_concat_max_len = 9999999";
     $db->setQuery($query);
     $db->execute();
     // *************
     // Get the items
     // *************
     $query = 'SELECT SQL_CALC_FOUND_ROWS i.id' . $orderby_col . ' FROM #__content AS i' . $join_clauses_with_text . $orderby_join . $joinaccess . $where_conf . $and_where_filters . ' GROUP BY i.id ' . $orderby;
     //echo "Adv search plugin main SQL query: ".nl2br($query)."<br/><br/>";
     // NOTE: The plugin will return a PRECONFIGURED limited number of results, the SEARCH VIEW to do the pagination, splicing (appropriately) the data returned by all search plugins
     try {
         // Get items, we use direct query because some extensions break the SQL_CALC_FOUND_ROWS, so let's bypass them (at this point it is OK)
         // *** Usage of FOUND_ROWS() will fail when (e.g.) Joom!Fish or Falang are installed, in this case we will be forced to re-execute the query ...
         // PLUS, we don't need Joom!Fish or Falang layer at --this-- STEP which may slow down the query considerably in large sites
         $query_limited = $query . ' LIMIT ' . $search_limit . ' OFFSET 0';
         $rows = flexicontent_db::directQuery($query_limited);
         $item_ids = array();
         foreach ($rows as $row) {
             $item_ids[] = $row->id;
         }
         // Get current items total for pagination
         $db->setQuery("SELECT FOUND_ROWS()");
         $fc_searchview['view_total'] = $db->loadResult();
         $app->setUserState('fc_view_total_' . $view, $fc_searchview['view_total']);
     } catch (Exception $e) {
         // Get items via normal joomla SQL layer
         $db->setQuery(str_replace('SQL_CALC_FOUND_ROWS', '', $query), 0, $search_limit);
         $item_ids = $db->loadColumn(0);
     }
     if (!count($item_ids)) {
         return array();
     }
     // No items found
     // *****************
     // Get the item data
     // *****************
     $query_data = 'SELECT i.id, i.title AS title, i.created, i.id AS fc_item_id, i.access, ie.type_id, i.language' . (!$txtmode ? ', ie.search_index AS text' : ', GROUP_CONCAT(ts.search_index ORDER BY f.ordering ASC SEPARATOR \' \') AS text') . ', CASE WHEN CHAR_LENGTH(i.alias) THEN CONCAT_WS(\':\', i.id, i.alias) ELSE i.id END as slug' . ', CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(\':\', c.id, c.alias) ELSE c.id END as categoryslug' . ', CONCAT_WS( " / ", ' . $db->Quote($searchFlexicontent) . ', c.title, i.title ) AS section' . $select_access . ' FROM #__content AS i' . $join_clauses . $join_textsearch . $join_textfields . ' WHERE i.id IN (' . implode(',', $item_ids) . ') ' . ' GROUP BY i.id ' . ' ORDER BY FIELD(i.id, ' . implode(',', $item_ids) . ')';
     //echo nl2br($query)."<br/><br/>";
     $db->setQuery($query_data);
     $list = $db->loadObjectList();
     if ($db->getErrorNum()) {
         echo $db->getErrorMsg();
     }
     if ($print_logging_info) {
         @($fc_run_times['search_query_runtime'] += round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // *************************************
     // Create item links and other variables
     // *************************************
     //echo "<pre>"; print_r($list); echo "</pre>";
     if ($list) {
         if (count($list) >= $search_limit) {
             $app->setUserState('fc_view_limit_max_' . $view, $search_limit);
         }
         $item_cats = FlexicontentFields::_getCategories($list);
         foreach ($list as $key => $item) {
             $item->text = preg_replace('/\\b' . $search_prefix . '/', '', $item->text);
             $item->categories = isset($item_cats[$item->id]) ? $item_cats[$item->id] : array();
             // in case of item categories missing
             // If joomla article view is allowed allowed and then search view may optional create Joomla article links
             if ($typeData[$item->type_id]->params->get('allow_jview', 0) && $typeData[$item->type_id]->params->get('search_jlinks', 1)) {
                 $item->href = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->categoryslug, $item->language));
             } else {
                 $item->href = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->slug, $item->categoryslug, 0, $item));
             }
             $item->browsernav = $browsernav;
         }
     }
     return $list;
 }
Exemplo n.º 10
0
    /**
     * Method to save field values of the item in field versioning DB table or in ..._fields_item_relations DB table 
     *
     * @access	public
     * @return	boolean	True on success
     * @since	1.0
     */
    function saveFields($isnew, &$item, &$data, &$files, &$old_item = null, &$core_data_via_events = null)
    {
        if (!$old_item) {
            $old_item =& $item;
        }
        $app = JFactory::getApplication();
        $user = JFactory::getUser();
        $dispatcher = JDispatcher::getInstance();
        $cparams = $this->_cparams;
        $use_versioning = $cparams->get('use_versioning', 1);
        $print_logging_info = $cparams->get('print_logging_info');
        $last_version = (int) FLEXIUtilities::getLastVersions($item->id, true);
        $mval_query = true;
        if ($print_logging_info) {
            global $fc_run_times;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        // ********************************
        // Checks for untranslatable fields
        // ********************************
        // CASE 1. Check if saving an item that translates an original content in site's default language
        // ... Decide whether to retrieve field values of untranslatable fields from the original content item
        $enable_translation_groups = flexicontent_db::useAssociations();
        //$cparams->get('enable_translation_groups');
        $site_default = substr(flexicontent_html::getSiteDefaultLang(), 0, 2);
        $is_content_default_lang = $site_default == substr($item->language, 0, 2);
        $get_untraslatable_values = $enable_translation_groups && !$is_content_default_lang;
        if ($enable_translation_groups) {
            $langAssocs = $this->getLangAssocs();
            //}
            //if ($enable_translation_groups /*&& $is_content_default_lang*/)
            //{
            // ... Get item ids of the associated items, so that we save into the untranslatable fields
            $_langAssocs = $langAssocs;
            unset($_langAssocs[$this->_id]);
            $assoc_item_ids = array_keys($_langAssocs);
        }
        if (empty($assoc_item_ids)) {
            $assoc_item_ids = array();
        }
        // ***************************************************************************************************************************
        // Get item's fields ... and their values (for untranslatable fields the field values from original content item are retrieved
        // ***************************************************************************************************************************
        $original_content_id = 0;
        if ($get_untraslatable_values) {
            foreach ($langAssocs as $content_id => $_assoc) {
                if ($site_default == substr($_assoc->language, 0, 2)) {
                    $original_content_id = $content_id;
                    break;
                }
            }
        }
        //JFactory::getApplication()->enqueueMessage(__FUNCTION__.'(): '.$original_content_id.' '.print_r($assoc_item_ids, true),'message');
        $fields = $this->getExtrafields($force = true, $original_content_id, $old_item);
        // ******************************************************************************************************************
        // Loop through Fields triggering onBeforeSaveField Event handlers, this was seperated from the rest of the process
        // to give chance to ALL fields to check their DATA and cancel item saving process before saving any new field values
        // ******************************************************************************************************************
        $searchindex = array();
        //$qindex = array();
        $core_data_via_events = array();
        // Extra validation for some core fields via onBeforeSaveField
        if ($fields) {
            $core_via_post = array('title' => 1, 'text' => 1);
            foreach ($fields as $field) {
                // Set vstate property into the field object to allow this to be changed be the before saving  field event handler
                $field->item_vstate = $data['vstate'];
                $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                $maintain_dbval = false;
                // FORM HIDDEN FIELDS (FRONTEND/BACKEND) AND (ACL) UNEDITABLE FIELDS: maintain their DB value ...
                if ($app->isSite() && ($field->formhidden == 1 || $field->formhidden == 3 || $field->parameters->get('frontend_hidden')) || $app->isAdmin() && ($field->formhidden == 2 || $field->formhidden == 3 || $field->parameters->get('backend_hidden')) || !$is_editable) {
                    $postdata[$field->name] = $field->value;
                    $maintain_dbval = true;
                    // UNTRANSLATABLE (CUSTOM) FIELDS: maintain their DB value ...
                    /*} else if ( $get_untraslatable_values && $field->untranslatable ) {
                    		$postdata[$field->name] = $field->value;
                    		$maintain_dbval = true;*/
                } else {
                    if ($field->iscore) {
                        // (posted) CORE FIELDS: if not set maintain their DB value ...
                        if (isset($core_via_post[$field->name])) {
                            if (isset($data[$field->name])) {
                                $postdata[$field->name] = $data[$field->name];
                            } else {
                                $postdata[$field->name] = $field->value;
                                $maintain_dbval = true;
                            }
                            // (not posted) CORE FIELDS: get current value
                        } else {
                            // Get value from the updated item instead of old data
                            $postdata[$field->name] = $this->getCoreFieldValue($field, 0);
                        }
                        // OTHER CUSTOM FIELDS (not hidden and not untranslatable)
                    } else {
                        $postdata[$field->name] = @$data['custom'][$field->name];
                    }
                }
                // Unserialize values already serialized values, e.g. (a) if current values used are from DB or (b) are being imported from CSV file
                if (!is_array($postdata[$field->name])) {
                    $postdata[$field->name] = strlen($postdata[$field->name]) ? array($postdata[$field->name]) : array();
                }
                foreach ($postdata[$field->name] as $i => $postdata_val) {
                    if (@unserialize($postdata_val) !== false || $postdata_val === 'b:0;') {
                        $postdata[$field->name][$i] = unserialize($postdata_val);
                    }
                }
                // Trigger plugin Event 'onBeforeSaveField'
                if (!$field->iscore || isset($core_via_post[$field->name])) {
                    $field_type = $field->iscore ? 'core' : $field->field_type;
                    $result = FLEXIUtilities::call_FC_Field_Func($field_type, 'onBeforeSaveField', array(&$field, &$postdata[$field->name], &$files[$field->name], &$item));
                    if ($result === false) {
                        // Field requested to abort item saving
                        $this->setError(JText::sprintf('FLEXI_FIELD_VALUE_IS_INVALID', $field->label));
                        return 'abort';
                    }
                    // For CORE field get the modified data, which will be used for storing in DB (these will be re-bind later)
                    if (isset($core_via_post[$field->name])) {
                        $core_data_via_events[$field->name] = isset($postdata[$field->name][0]) ? $postdata[$field->name][0] : '';
                        // The validation may have skipped it !!
                    }
                } else {
                    // Currently other CORE fields, these are skipped we will not call onBeforeSaveField() on them, neither rebind them
                }
                //$qindex[$field->name] = NULL;
                //$result = FLEXIUtilities::call_FC_Field_Func($field_type, 'onBeforeSaveField', array( &$field, &$postdata[$field->name], &$files[$field->name], &$item, &$qindex[$field->name] ));
                //if ($result===false) { ... }
                // Get vstate property from the field object back to the data array ... in case it was modified, since some field may decide to prevent approval !
                $data['vstate'] = $field->item_vstate;
            }
            //echo "<pre>"; print_r($postdata); echo "</pre>"; exit;
        }
        if ($print_logging_info) {
            @($fc_run_times['fields_value_preparation'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
        }
        // **********************
        // Empty per field TABLES
        // **********************
        $filterables = FlexicontentFields::getSearchFields('id', $indexer = 'advanced', null, null, $_load_params = true, 0, $search_type = 'filter');
        $filterables = array_keys($filterables);
        $filterables = array_flip($filterables);
        $tbl_prefix = $app->getCfg('dbprefix') . 'flexicontent_advsearch_index_field_';
        $query = "SELECT TABLE_NAME\n\t\t\tFROM INFORMATION_SCHEMA.TABLES\n\t\t\tWHERE TABLE_NAME LIKE '" . $tbl_prefix . "%'\n\t\t\t";
        $this->_db->setQuery($query);
        $tbl_names = $this->_db->loadColumn();
        foreach ($tbl_names as $tbl_name) {
            $_field_id = str_replace($tbl_prefix, '', $tbl_name);
            // Drop the table of no longer filterable field
            if (!isset($filterables[$_field_id])) {
                $this->_db->setQuery('DROP TABLE IF EXISTS ' . $tbl_name);
            } else {
                // Remove item's old advanced search index entries
                $query = "DELETE FROM " . $tbl_name . " WHERE item_id=" . $item->id;
                $this->_db->setQuery($query);
                $this->_db->query();
            }
        }
        // VERIFY all search tables exist
        $tbl_names_flipped = array_flip($tbl_names);
        foreach ($filterables as $_field_id => $_ignored) {
            $tbl_name = $app->getCfg('dbprefix') . 'flexicontent_advsearch_index_field_' . $_field_id;
            if (isset($tbl_names_flipped[$tbl_name])) {
                continue;
            }
            $query = '
			CREATE TABLE IF NOT EXISTS `' . $tbl_name . '` (
			  `sid` int(11) NOT NULL auto_increment,
			  `field_id` int(11) NOT NULL,
			  `item_id` int(11) NOT NULL,
			  `extraid` int(11) NOT NULL,
			  `search_index` longtext NOT NULL,
			  `value_id` varchar(255) NULL,
			  PRIMARY KEY (`field_id`,`item_id`,`extraid`),
			  KEY `sid` (`sid`),
			  KEY `field_id` (`field_id`),
			  KEY `item_id` (`item_id`),
			  FULLTEXT `search_index` (`search_index`),
			  KEY `value_id` (`value_id`)
			) ENGINE=MyISAM CHARACTER SET `utf8` COLLATE `utf8_general_ci`
			';
            $this->_db->setQuery($query);
            $this->_db->query();
        }
        // ****************************************************************************************************************************
        // Loop through Fields triggering onIndexAdvSearch, onIndexSearch Event handlers, this was seperated from the before save field
        //  event, so that we will update search indexes only if the above has not canceled saving OR has not canceled version approval
        // ****************************************************************************************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $ai_query_vals = array();
        $ai_query_vals_f = array();
        if ($fields) {
            foreach ($fields as $field) {
                $field_type = $field->iscore ? 'core' : $field->field_type;
                if ($data['vstate'] == 2 || $isnew) {
                    // Trigger plugin Event 'onIndexAdvSearch' to update field-item pair records in advanced search index
                    FLEXIUtilities::call_FC_Field_Func($field_type, 'onIndexAdvSearch', array(&$field, &$postdata[$field->name], &$item));
                    if (isset($field->ai_query_vals)) {
                        foreach ($field->ai_query_vals as $query_val) {
                            $ai_query_vals[] = $query_val;
                        }
                        if (isset($filterables[$field->id])) {
                            // Current for advanced index only
                            foreach ($field->ai_query_vals as $query_val) {
                                $ai_query_vals_f[$field->id][] = $query_val;
                            }
                        }
                    }
                    //echo $field->name .":".implode(",", @$field->ai_query_vals ? $field->ai_query_vals : array() )."<br/>";
                    // Trigger plugin Event 'onIndexSearch' to update item 's (basic) search index record
                    FLEXIUtilities::call_FC_Field_Func($field_type, 'onIndexSearch', array(&$field, &$postdata[$field->name], &$item));
                    if (strlen(@$field->search[$item->id])) {
                        $searchindex[] = $field->search[$item->id];
                    }
                    //echo $field->name .":".@$field->search[$item->id]."<br/>";
                }
            }
        }
        // Remove item's old advanced search index entries
        $query = "DELETE FROM #__flexicontent_advsearch_index WHERE item_id=" . $item->id;
        $this->_db->setQuery($query);
        $this->_db->query();
        // Store item's advanced search index entries
        $queries = array();
        if (count($ai_query_vals)) {
            $queries[] = "INSERT INTO #__flexicontent_advsearch_index " . " (field_id,item_id,extraid,search_index,value_id) VALUES " . implode(",", $ai_query_vals);
            $this->_db->setQuery($query);
            $this->_db->query();
            if ($this->_db->getErrorNum()) {
                JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($this->_db->getErrorMsg()), 'error');
            }
        }
        foreach ($ai_query_vals_f as $_field_id => $_query_vals) {
            // Current for advanced index only
            $queries[] = "INSERT INTO #__flexicontent_advsearch_index_field_" . $_field_id . " (field_id,item_id,extraid,search_index,value_id) VALUES " . implode(",", $_query_vals);
        }
        foreach ($queries as $query) {
            $this->_db->setQuery($query);
            $this->_db->query();
        }
        // Assigned created basic search index into item object
        $search_prefix = $cparams->get('add_search_prefix') ? 'vvv' : '';
        // SEARCH WORD Prefix
        $item->search_index = implode(' | ', $searchindex);
        if ($search_prefix && $item->search_index) {
            $item->search_index = preg_replace('/(\\b[^\\s]+\\b)/', $search_prefix . '$0', trim($item->search_index));
        }
        // Check if vstate was set to 1 (no approve new version) while versioning is disabled
        if (!$use_versioning && $data['vstate'] != 2) {
            $data['vstate'] = 2;
            $app->enqueueMessage('vstate cannot be set to 1 (=no approve new version) when versioning is disabled', 'notice');
        }
        if ($print_logging_info) {
            @($fc_run_times['fields_value_indexing'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        // **************************************************************************
        // IF new version is approved, remove old version values from the field table
        // **************************************************************************
        if ($data['vstate'] == 2) {
            //echo "delete __flexicontent_fields_item_relations, item_id: " .$item->id;
            $query = 'DELETE FROM #__flexicontent_fields_item_relations WHERE item_id = ' . $item->id;
            $this->_db->setQuery($query);
            $this->_db->query();
            $query = 'DELETE FROM #__flexicontent_items_versions WHERE item_id=' . $item->id . ' AND version=' . ((int) $last_version + 1);
            $this->_db->setQuery($query);
            $this->_db->query();
            $untranslatable_fields = array();
            if ($fields) {
                foreach ($fields as $field) {
                    if ($field->iscore) {
                        continue;
                    }
                    if (count($assoc_item_ids) && $field->untranslatable) {
                        // Delete field values in all translating items, if current field is untranslatable and current item version is approved
                        // NOTE: item itself is not include in associated translations, no need to check for it and skip itit
                        if (!$mval_query) {
                            $query = 'DELETE FROM #__flexicontent_fields_item_relations WHERE item_id IN (' . implode(',', $assoc_item_ids) . ') AND field_id=' . $field->id;
                            $this->_db->setQuery($query);
                            $this->_db->query();
                        } else {
                            $untranslatable_fields[] = $field->id;
                        }
                    }
                }
            }
            if (count($untranslatable_fields)) {
                $query = 'DELETE FROM #__flexicontent_fields_item_relations WHERE item_id IN (' . implode(',', $assoc_item_ids) . ') AND field_id IN (' . implode(',', $untranslatable_fields) . ')';
                $this->_db->setQuery($query);
                $this->_db->query();
            }
        }
        // *******************************************
        // Loop through Fields saving the field values
        // *******************************************
        if ($fields) {
            // Do not save if versioning disabled or item has no type (version 0)
            $record_versioned_data = $use_versioning && $item->version;
            $ver_query_vals = array();
            $rel_query_vals = array();
            foreach ($fields as $field) {
                // -- Add the new values to the database
                $postvalues = $this->formatToArray($postdata[$field->name]);
                //$qindex_values = $qindex[$field->name];
                $i = 1;
                foreach ($postvalues as $postvalue) {
                    // Create field obj for DB insertion
                    $obj = new stdClass();
                    $obj->field_id = $field->id;
                    $obj->item_id = $item->id;
                    $obj->valueorder = $i;
                    $obj->suborder = 1;
                    $obj->version = (int) $last_version + 1;
                    $use_ingroup = $field->parameters->get('use_ingroup', 0);
                    // Serialize the properties of the value, normally this is redudant, since the field must have had serialized the parameters of each value already
                    if (!empty($field->use_suborder) && is_array($postvalue)) {
                        $obj->value = null;
                    } else {
                        $obj->value = is_array($postvalue) ? serialize($postvalue) : $postvalue;
                    }
                    //$obj->qindex01 = isset($qindex_values['qindex01']) ? $qindex_values['qindex01'] : NULL;
                    //$obj->qindex02 = isset($qindex_values['qindex02']) ? $qindex_values['qindex02'] : NULL;
                    //$obj->qindex03 = isset($qindex_values['qindex03']) ? $qindex_values['qindex03'] : NULL;
                    // -- a. Add versioning values, but do not version the 'hits' or 'state' or 'voting' fields
                    if ($record_versioned_data && $field->field_type != 'hits' && $field->field_type != 'state' && $field->field_type != 'voting') {
                        // Insert only if value non-empty
                        if (!empty($field->use_suborder) && is_array($postvalue)) {
                            $obj->suborder = 1;
                            foreach ($postvalue as $v) {
                                $obj->value = $v;
                                if (!$mval_query) {
                                    $this->_db->insertObject('#__flexicontent_items_versions', $obj);
                                } else {
                                    $ver_query_vals[] = "(" . $obj->field_id . "," . $obj->item_id . "," . $obj->valueorder . "," . $obj->suborder . "," . $obj->version . "," . $this->_db->Quote($obj->value) . ")";
                                }
                                $obj->suborder++;
                            }
                            unset($v);
                        } else {
                            if (isset($obj->value) && ($use_ingroup || strlen(trim($obj->value)))) {
                                if (!$mval_query) {
                                    $this->_db->insertObject('#__flexicontent_items_versions', $obj);
                                } else {
                                    $ver_query_vals[] = "(" . $obj->field_id . "," . $obj->item_id . "," . $obj->valueorder . "," . $obj->suborder . "," . $obj->version . "," . $this->_db->Quote($obj->value) . ")";
                                }
                            }
                        }
                    }
                    //echo $field->field_type." - ".$field->name." - ".strlen(trim($obj->value))." ".$field->iscore."<br/>";
                    // -- b. If item is new OR version is approved, AND field is not core (aka stored in the content table or in special table), then add field value to field values table
                    if (($isnew || $data['vstate'] == 2) && !$field->iscore) {
                        // UNSET version it it used only verion data table, and insert only if value non-empty
                        unset($obj->version);
                        if (!empty($field->use_suborder) && is_array($postvalue)) {
                            $obj->suborder = 1;
                            foreach ($postvalue as $v) {
                                $obj->value = $v;
                                if (!$mval_query) {
                                    $this->_db->insertObject('#__flexicontent_fields_item_relations', $obj);
                                } else {
                                    $rel_query_vals[] = "(" . $obj->field_id . "," . $obj->item_id . "," . $obj->valueorder . "," . $obj->suborder . "," . $this->_db->Quote($obj->value) . ")";
                                }
                                $obj->suborder++;
                            }
                            unset($v);
                        } else {
                            if (isset($obj->value) && ($use_ingroup || strlen(trim($obj->value)))) {
                                if (!$mval_query) {
                                    $this->_db->insertObject('#__flexicontent_fields_item_relations', $obj);
                                } else {
                                    $rel_query_vals[] = "(" . $obj->field_id . "," . $obj->item_id . "," . $obj->valueorder . "," . $obj->suborder . "," . $this->_db->Quote($obj->value) . ")";
                                }
                                // Save field value in all translating items, if current field is untranslatable
                                // NOTE: item itself is not include in associated translations, no need to check for it and skip it
                                if (count($assoc_item_ids) && $field->untranslatable) {
                                    foreach ($assoc_item_ids as $t_item_id) {
                                        //echo "setting Untranslatable value for item_id: ".$t_item_id ." field_id: ".$field->id."<br/>";
                                        $obj->item_id = $t_item_id;
                                        if (!$mval_query) {
                                            $this->_db->insertObject('#__flexicontent_fields_item_relations', $obj);
                                        } else {
                                            $rel_query_vals[] = "(" . $obj->field_id . "," . $obj->item_id . "," . $obj->valueorder . "," . $obj->suborder . "," . $this->_db->Quote($obj->value) . ")";
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $i++;
                }
            }
            // *********************************************
            // Insert values in item fields versioning table
            // *********************************************
            if (count($ver_query_vals)) {
                $query = "INSERT INTO #__flexicontent_items_versions " . " (field_id,item_id,valueorder,suborder,version,value" . ") VALUES " . "\n" . implode(",\n", $ver_query_vals);
                $this->_db->setQuery($query);
                $this->_db->query();
                if ($this->_db->getErrorNum()) {
                    JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($this->_db->getErrorMsg()), 'error');
                }
            }
            // *******************************************
            // Insert values in item fields relation table
            // *******************************************
            if (count($rel_query_vals)) {
                $query = "INSERT INTO #__flexicontent_fields_item_relations " . " (field_id,item_id,valueorder,suborder,value" . ") VALUES " . "\n" . implode(",\n", $rel_query_vals);
                $this->_db->setQuery($query);
                $this->_db->query();
                if ($this->_db->getErrorNum()) {
                    JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($this->_db->getErrorMsg()), 'error');
                }
            }
            // **************************************************************
            // Save other versioned item data into the field versioning table
            // **************************************************************
            // a. Save a version of item properties that do not have a corresponding CORE Field
            if ($record_versioned_data) {
                $obj = new stdClass();
                $obj->field_id = -2;
                // ID of Fake Field used to contain item properties not having a corresponding CORE field
                $obj->item_id = $item->id;
                $obj->valueorder = 1;
                $obj->suborder = 1;
                $obj->version = (int) $last_version + 1;
                $item_data = array();
                $iproperties = array('alias', 'catid', 'metadesc', 'metakey', 'metadata', 'attribs', 'urls', 'images');
                foreach ($iproperties as $iproperty) {
                    $item_data[$iproperty] = $item->{$iproperty};
                }
                $obj->value = serialize($item_data);
                $this->_db->insertObject('#__flexicontent_items_versions', $obj);
            }
            // b. Finally save a version of the posted JoomFish translated data for J1.5, if such data are editted inside the item edit form
            /*if ( FLEXI_FISH && !empty($data['jfdata']) && $record_versioned_data )
            		{
            			$obj = new stdClass();
            			$obj->field_id 		= -1;  // ID of Fake Field used to contain the Joomfish translated item data
            			$obj->item_id 		= $item->id;
            			$obj->valueorder	= 1;
            			$obj->suborder    = 1;
            			$obj->version			= (int)$last_version+1;
            			
            			$item_lang = substr($item->language ,0,2);
            			$data['jfdata'][$item_lang]['title'] = $item->title;
            			$data['jfdata'][$item_lang]['alias'] = $item->alias;
            			$data['jfdata'][$item_lang]['text'] = $item->text;
            			$data['jfdata'][$item_lang]['metadesc'] = $item->metadesc;
            			$data['jfdata'][$item_lang]['metakey'] = $item->metakey;
            			$obj->value = serialize($data['jfdata']);
            			$this->_db->insertObject('#__flexicontent_items_versions', $obj);
            		}*/
        }
        if ($print_logging_info) {
            @($fc_run_times['fields_value_saving'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
        }
        // ******************************
        // Trigger onAfterSaveField Event
        // ******************************
        if ($fields) {
            if ($print_logging_info) {
                $start_microtime = microtime(true);
            }
            foreach ($fields as $field) {
                $field_type = $field->iscore ? 'core' : $field->field_type;
                $result = FLEXIUtilities::call_FC_Field_Func($field_type, 'onAfterSaveField', array(&$field, &$postdata[$field->name], &$files[$field->name], &$item));
                // *** $result is ignored
            }
            if ($print_logging_info) {
                @($fc_run_times['onAfterSaveField_event'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
            }
        }
        return true;
    }
Exemplo n.º 11
0
	function onIndexSearch(&$field, &$post, &$item)
	{
		if ( !in_array($field->field_type, self::$field_types) ) return;
		if ( !$field->issearch ) return;
		
		FLEXIUtilities::call_FC_Field_Func('text', 'onIndexSearch', array(&$field, &$post, &$item));
		return true;
	}
Exemplo n.º 12
0
 function index()
 {
     $start_microtime = microtime(true);
     $session = JFactory::getSession();
     $db = JFactory::getDBO();
     // Test indexing with limited memory
     //ini_set("memory_limit", "20M");
     @ob_end_clean();
     $search_prefix = JComponentHelper::getParams('com_flexicontent')->get('add_search_prefix') ? 'vvv' : '';
     // SEARCH WORD Prefix
     $indexer = JRequest::getVar('indexer', 'advanced');
     $rebuildmode = JRequest::getVar('rebuildmode', '');
     $items_per_call = JRequest::getVar('items_per_call', 20);
     // Number of item to index per HTTP request
     $itemcnt = JRequest::getVar('itemcnt', 0);
     // Counter of items indexed so far, this is given via HTTP request
     // TAKE CARE: this code depends on countrows() to set session variables
     // Retrieve fields, that are assigned as (advanced/basic) searchable/filterable
     if ($rebuildmode == 'quick' && $indexer == 'advanced') {
         $nse_fields = $session->get($indexer . '_nse_fields', array(), 'flexicontent');
         $nsp_fields = $session->get($indexer . '_nsp_fields', array(), 'flexicontent');
         $fields = $session->get($indexer . '_fields', array(), 'flexicontent');
         //echo 'fail|'; print_r(array_keys($fields)); exit;
         // Get the field ids of the fields removed from searching
         $del_fieldids = array_unique(array_merge(array_keys($nse_fields), array_keys($nsp_fields), array_keys($fields)));
     } else {
         $fields = $session->get($indexer . '_fields', array(), 'flexicontent');
         //echo 'fail|'; print_r(array_keys($fields)); exit;
     }
     // Get the field ids of the searchable fields
     $fieldids = array_keys($fields);
     // Get fields that will have atomic search tables, (current for advanced index only)
     if ($indexer == 'advanced') {
         $filterables = FlexicontentFields::getSearchFields('id', $indexer, null, null, $_load_params = false, 0, $search_type = 'filter');
         $filterables = array_keys($filterables);
         $filterables = array_flip($filterables);
     } else {
         $filterables = array();
     }
     // Get items ids that have value for any of the searchable fields, but use session to avoid recalculation
     $itemids = $session->get($indexer . '_items_to_index', array(), 'flexicontent');
     $_fields = array();
     foreach ($fields as $field_id => $field) {
         // Clone field to avoid problems
         $_fields[$field_id] = clone $field;
         // Create field parameters if not already created
         if (empty($_fields[$field_id]->parameters)) {
             $_fields[$field_id]->parameters = new JRegistry($_fields[$field_id]->attribs);
         }
     }
     $fields = $_fields;
     // Get query size limit
     $query = "SHOW VARIABLES LIKE 'max_allowed_packet'";
     $db->setQuery($query);
     $_dbvariable = $db->loadObject();
     $max_allowed_packet = flexicontent_upload::parseByteLimit(@$_dbvariable->Value);
     $max_allowed_packet = $max_allowed_packet ? $max_allowed_packet : 256 * 1024;
     $query_lim = (int) (3 * $max_allowed_packet / 4);
     //echo 'fail|'.$query_lim; exit;
     // Get script max
     $max_execution_time = ini_get("max_execution_time");
     //echo 'fail|'.$max_execution_time; exit;
     $query_count = 0;
     $max_items_per_query = 100;
     $max_items_per_query = $max_items_per_query > $items_per_call ? $items_per_call : $max_items_per_query;
     $cnt = $itemcnt;
     while ($cnt < count($itemids) && $cnt < $itemcnt + $items_per_call) {
         $query_itemids = array_slice($itemids, $cnt, $max_items_per_query);
         $cnt += $max_items_per_query;
         // Item is not needed, later and only if field uses item replacements then it will be loaded
         $item = null;
         // Items language is needed to do (if needed) special per language handling
         $lang_query = "SELECT id, language" . " FROM #__content AS i " . " WHERE id IN (" . implode(', ', $query_itemids) . ")";
         $db->setQuery($lang_query);
         $items_data = $db->loadObjectList('id');
         if ($indexer == 'basic') {
             $searchindex = array();
             // Add all query itemids to searchindex array so that it will be cleared even if zero fields are indexed
             foreach ($query_itemids as $query_itemid) {
                 $searchindex[$query_itemid] = array();
             }
         } else {
             // This will hold the SQL inserting new advanced search records for multiple item/values
             $ai_query_vals = array();
             $ai_query_vals_f = array();
             // Current for advanced index only
         }
         // For current item: Loop though all searchable fields according to their type
         foreach ($fieldids as $fieldid) {
             // Must SHALLOW clone because we will be setting some properties , e.g. 'ai_query_vals', that we do not
             $field = clone $fields[$fieldid];
             // Indicate multiple items per query
             $field->item_id = 0;
             $field->query_itemids = $query_itemids;
             $field->items_data = $items_data;
             // Includes item langyage, which may be used for special per language handling
             // Indicate that the indexing fuction should retrieve the values
             $values = null;
             // Add values to advanced search index
             $fieldname = $field->iscore ? 'core' : $field->field_type;
             if ($indexer == 'advanced') {
                 FLEXIUtilities::call_FC_Field_Func($fieldname, 'onIndexAdvSearch', array(&$field, &$values, &$item));
                 //print_r($field->ai_query_vals);
                 if (isset($field->ai_query_vals)) {
                     foreach ($field->ai_query_vals as $query_val) {
                         $ai_query_vals[] = $query_val;
                     }
                     if (isset($filterables[$field->id])) {
                         // Current for advanced index only
                         foreach ($field->ai_query_vals as $query_val) {
                             $ai_query_vals_f[$field->id][] = $query_val;
                         }
                     }
                 }
                 //else echo "Not set for : ". $field->name;
             } else {
                 if ($indexer == 'basic') {
                     FLEXIUtilities::call_FC_Field_Func($fieldname, 'onIndexSearch', array(&$field, &$values, &$item));
                     foreach ($query_itemids as $query_itemid) {
                         if (@$field->search[$query_itemid]) {
                             $searchindex[$query_itemid][] = $field->search[$query_itemid];
                         }
                     }
                 }
             }
         }
         // Create query that will update/insert data into the DB
         unset($queries);
         // make sure it is not set above
         $queries = array();
         if ($indexer == 'basic') {
             if (count($searchindex)) {
                 // check for zero search index records
                 $query_vals = '';
                 $query_ids = array();
                 // Start new query
                 foreach ($searchindex as $query_itemid => $search_text) {
                     if (strlen($query_vals) > $query_lim) {
                         $query = "UPDATE #__flexicontent_items_ext SET search_index = CASE item_id " . $query_vals . " END " . " WHERE item_id IN (" . implode(',', $query_ids) . ")";
                         $queries[] = $query;
                         $query_vals = '';
                         $query_ids = array();
                         // Start new query
                     }
                     $query_ids[] = $query_itemid;
                     $_search_text = implode(' | ', $search_text);
                     if ($search_prefix && $_search_text) {
                         $_search_text = preg_replace('/(\\b[^\\s,\\.]+\\b)/u', $search_prefix . '$0', trim($_search_text));
                     }
                     $query_vals .= " WHEN {$query_itemid} THEN " . $db->Quote($_search_text);
                 }
                 if (count($query_ids)) {
                     $query = "UPDATE #__flexicontent_items_ext SET search_index = CASE item_id " . $query_vals . " END " . " WHERE item_id IN (" . implode(',', $query_ids) . ")";
                     $queries[] = $query;
                 }
             }
         } else {
             if (count($ai_query_vals)) {
                 // check for zero search index records
                 $query_vals = '';
                 // Start new query
                 foreach ($ai_query_vals as &$query_value) {
                     $query_vals .= ($query_vals ? ',' : '') . $query_value;
                     if (strlen($query_vals) > $query_lim) {
                         $queries[] = "INSERT INTO #__flexicontent_advsearch_index " . " (field_id,item_id,extraid,search_index,value_id) VALUES " . $query_vals;
                         $query_vals = '';
                         // Start new query
                     }
                 }
                 unset($query_value);
                 if (strlen($query_vals)) {
                     $queries[] = "INSERT INTO #__flexicontent_advsearch_index " . " (field_id,item_id,extraid,search_index,value_id) VALUES " . $query_vals;
                 }
             }
             foreach ($ai_query_vals_f as $_field_id => $_query_vals) {
                 $query_vals = '';
                 // Start new query
                 foreach ($_query_vals as &$query_value) {
                     $query_vals .= ($query_vals ? ',' : '') . $query_value;
                     if (strlen($query_vals) > $query_lim) {
                         $queries[] = "INSERT INTO #__flexicontent_advsearch_index_field_" . $_field_id . " (field_id,item_id,extraid,search_index,value_id) VALUES " . $query_vals;
                         $query_vals = '';
                         // Start new query
                     }
                 }
                 if (strlen($query_vals)) {
                     $queries[] = "INSERT INTO #__flexicontent_advsearch_index_field_" . $_field_id . " (field_id,item_id,extraid,search_index,value_id) VALUES " . $query_vals;
                     $query_vals = '';
                     // Start new query
                 }
             }
         }
         foreach ($queries as $query) {
             $db->setQuery($query);
             try {
                 $db->execute();
             } catch (RuntimeException $e) {
                 echo "fail|" . $e->getMessage();
                 exit;
             }
         }
         $query_count += count($queries);
         $elapsed_microseconds = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
         $elapsed_seconds = $elapsed_microseconds / 1000000.0;
         if ($elapsed_seconds > $max_execution_time / 3 || $elapsed_seconds > 5) {
             break;
         }
     }
     // Check if items have finished, otherwise continue with -next- group of item ids
     if ($cnt >= count($itemids)) {
         // Reset dirty SEARCH properties of published fields to be: normal ON/OFF
         $set_clause = ' SET' . ($indexer == 'basic' ? ' issearch = CASE issearch WHEN 2 THEN 1   WHEN -1 THEN 0   ELSE issearch   END' : ' isadvsearch = CASE isadvsearch WHEN 2 THEN 1   WHEN -1 THEN 0   ELSE isadvsearch   END,' . ' isadvfilter = CASE isadvfilter WHEN 2 THEN 1   WHEN -1 THEN 0   ELSE isadvfilter   END');
         $query = 'UPDATE #__flexicontent_fields' . $set_clause . " WHERE published=1";
         $db->setQuery($query);
         $db->execute();
         // Force SEARCH properties of unpublished fields to be: normal OFF
         if ($indexer == 'basic') {
             $query = 'UPDATE #__flexicontent_fields SET issearch = 0 WHERE published=0';
             $db->setQuery($query);
             $db->execute();
         } else {
             $query = 'UPDATE #__flexicontent_fields SET isadvsearch = 0, isadvfilter = 0  WHERE published=0';
             $db->setQuery($query);
             $db->execute();
         }
     }
     if (!count($fieldids)) {
         echo 'fail|Index was only cleaned-up, <br/>since no <b>fields</b> were marked as: ' . '<br> -- ' . ($indexer == 'basic' ? 'Text Searchable (CONTENT LISTS)' : 'Text Searchable OR filterable (SEARCH VIEW)');
         exit;
     }
     if (!count($itemids)) {
         echo 'fail|Index was only cleaned-up, <br/>since no <b>items</b> were found to have value for fields marked as: ' . '<br> -- ' . ($indexer == 'basic' ? 'Text Searchable (CONTENT LISTS)' : 'Text Searchable OR filterable (SEARCH VIEW)');
         exit;
     }
     $elapsed_microseconds = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
     if ($session->has($indexer . '_total_runtime', 'flexicontent')) {
         $_total_runtime = $session->get($indexer . '_total_runtime', 0, 'flexicontent');
     } else {
         $_total_runtime = 0;
     }
     $_total_runtime += $elapsed_microseconds;
     $session->set($indexer . '_total_runtime', $_total_runtime, 'flexicontent');
     if ($session->has($indexer . '_total_queries', 'flexicontent')) {
         $_total_queries = $session->get($indexer . '_total_queries', 0, 'flexicontent');
     } else {
         $_total_queries = 0;
     }
     $_total_queries += $query_count;
     $session->set($indexer . '_total_queries', $_total_queries, 'flexicontent');
     echo sprintf($cnt . ' | Server execution time: %.2f secs ', $_total_runtime / 1000000) . ' | Total DB updates: ' . $_total_queries;
     exit;
 }
Exemplo n.º 13
0
	function onIndexAdvSearch(&$field, &$post, &$item) {
		// execute the code only if the field type match the plugin type
		if ( !in_array($field->field_type, self::$field_types) ) return;
		if ( !$field->isadvsearch && !$field->isadvfilter ) return;
		
		FLEXIUtilities::call_FC_Field_Func('text', 'onIndexAdvSearch', array(&$field, &$post, &$item));
		return true;
	}
Exemplo n.º 14
0
    /**
     * Creates the item page
     *
     * @since 1.0
     */
    function display($tpl = null)
    {
        // ********************************
        // Initialize variables, flags, etc
        // ********************************
        global $globalcats;
        $categories = $globalcats;
        $app = JFactory::getApplication();
        $dispatcher = JDispatcher::getInstance();
        $document = JFactory::getDocument();
        $session = JFactory::getSession();
        $user = JFactory::getUser();
        $db = JFactory::getDBO();
        $option = JRequest::getVar('option');
        $nullDate = $db->getNullDate();
        // Get the COMPONENT only parameters
        $params = clone JComponentHelper::getParams('com_flexicontent');
        if (!FLEXI_J16GE) {
            jimport('joomla.html.pane');
            $pane = JPane::getInstance('sliders');
            $editor = JFactory::getEditor();
        }
        // Some flags
        $enable_translation_groups = $params->get("enable_translation_groups") && (FLEXI_J16GE || FLEXI_FISH);
        $print_logging_info = $params->get('print_logging_info');
        if ($print_logging_info) {
            global $fc_run_times;
        }
        // *****************
        // Load JS/CSS files
        // *****************
        FLEXI_J30GE ? JHtml::_('behavior.framework', true) : JHTML::_('behavior.mootools');
        flexicontent_html::loadFramework('jQuery');
        flexicontent_html::loadFramework('select2');
        $prettycheckable_added = flexicontent_html::loadFramework('prettyCheckable');
        // Load custom behaviours: form validation, popup tooltips
        //JHTML::_('behavior.formvalidation');
        JHTML::_('behavior.tooltip');
        // Add css to document
        $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/flexicontentbackend.css');
        if (FLEXI_J30GE) {
            $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j3x.css');
        } else {
            if (FLEXI_J16GE) {
                $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j25.css');
            } else {
                $document->addStyleSheet(JURI::base() . 'components/com_flexicontent/assets/css/j15.css');
            }
        }
        // Add js function to overload the joomla submitform
        $document->addScript(JURI::root() . 'components/com_flexicontent/assets/js/admin.js');
        $document->addScript(JURI::root() . 'components/com_flexicontent/assets/js/validate.js');
        // Add js function for custom code used by FLEXIcontent item form
        $document->addScript(JURI::root() . 'components/com_flexicontent/assets/js/itemscreen.js');
        // ***********************
        // Get data from the model
        // ***********************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $model = $this->getModel();
        $item = $this->get('Item');
        if (FLEXI_J16GE) {
            $form = $this->get('Form');
        }
        if ($print_logging_info) {
            $fc_run_times['get_item_data'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // ***************************
        // Get Associated Translations
        // ***************************
        if ($enable_translation_groups) {
            $langAssocs = $this->get('LangAssocs');
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $langs = FLEXIUtilities::getLanguages('code');
        }
        // Get item id and new flag
        $cid = $model->getId();
        $isnew = !$cid;
        // Create and set a unique item id for plugins that needed it
        JRequest::setVar('unique_tmp_itemid', $cid ? $cid : date('_Y_m_d_h_i_s_', time()) . uniqid(true));
        // Get number of subscribers
        $subscribers = $model->getSubscribersCount();
        // ******************
        // Version Panel data
        // ******************
        // Get / calculate some version related variables
        $versioncount = $model->getVersionCount();
        $versionsperpage = $params->get('versionsperpage', 10);
        $pagecount = (int) ceil($versioncount / $versionsperpage);
        // Data need by version panel: (a) current version page, (b) currently active version
        $current_page = 1;
        $k = 1;
        $allversions = $model->getVersionList();
        foreach ($allversions as $v) {
            if ($k > 1 && ($k - 1) % $versionsperpage == 0) {
                $current_page++;
            }
            if ($v->nr == $item->version) {
                break;
            }
            $k++;
        }
        // Finally fetch the version data for versions in current page
        $versions = $model->getVersionList(($current_page - 1) * $versionsperpage, $versionsperpage);
        // *****************
        // Type related data
        // *****************
        // Get available types and the currently selected/requested type
        $types = $model->getTypeslist();
        $typesselected = $model->getTypesselected();
        // Get and merge type parameters
        $tparams = $this->get('Typeparams');
        $tparams = FLEXI_J16GE ? new JRegistry($tparams) : new JParameter($tparams);
        $params->merge($tparams);
        // Apply type configuration if it type is set
        // Get user allowed permissions on the item ... to be used by the form rendering
        // Also hide parameters panel if user can not edit parameters
        $perms = $this->_getItemPerms($item, $typesselected);
        if (!$perms['canparams']) {
            $document->addStyleDeclaration((FLEXI_J16GE ? '#details-options' : '#det-pane') . '{display:none;}');
        }
        // ******************
        // Create the toolbar
        // ******************
        $toolbar = JToolBar::getInstance('toolbar');
        // SET toolbar title
        if ($cid) {
            JToolBarHelper::title(JText::_('FLEXI_EDIT_ITEM'), 'itemedit');
            // Editing existing item
        } else {
            JToolBarHelper::title(JText::_('FLEXI_NEW_ITEM'), 'itemadd');
            // Creating new item
        }
        // Add a preview button for LATEST version of the item
        if ($cid) {
            // Domain URL and autologin vars
            $server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
            $autologin = '';
            //$params->get('autoflogin', 1) ? '&fcu='.$user->username . '&fcp='.$user->password : '';
            // Check if we are in the backend, in the back end we need to set the application to the site app instead
            $isAdmin = JFactory::getApplication()->isAdmin();
            if ($isAdmin && FLEXI_J16GE) {
                JFactory::$application = JApplication::getInstance('site');
            }
            // Create the URL
            $item_url = JRoute::_(FlexicontentHelperRoute::getItemRoute($item->id . ':' . $item->alias, $categories[$item->catid]->slug) . $autologin);
            // Check if we are in the backend again
            // In backend we need to remove administrator from URL as it is added even though we've set the application to the site app
            if ($isAdmin) {
                if (FLEXI_J16GE) {
                    $admin_folder = str_replace(JURI::root(true), '', JURI::base(true));
                    $item_url = str_replace($admin_folder, '', $item_url);
                    // Restore application
                    JFactory::$application = JApplication::getInstance('administrator');
                } else {
                    $item_url = JURI::root(true) . '/' . $item_url;
                }
            }
            $previewlink = $item_url . (strstr($item_url, '?') ? '&' : '?') . 'preview=1';
            //$previewlink     = str_replace('&amp;', '&', $previewlink);
            //$previewlink = JRoute::_(JURI::root() . FlexicontentHelperRoute::getItemRoute($item->id.':'.$item->alias, $categories[$item->catid]->slug)) .$autologin;
            if (!$params->get('use_versioning', 1) || $item->version == $item->current_version && $item->version == $item->last_version) {
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('Preview') . '</a>', 'preview');
            } else {
                // Add a preview button for (currently) LOADED version of the item
                $previewlink_loaded_ver = $previewlink . '&version=' . $item->version;
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink_loaded_ver . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('FLEXI_PREVIEW_FORM_LOADED_VERSION') . ' [' . $item->version . ']</a>', 'preview');
                // Add a preview button for currently ACTIVE version of the item
                $previewlink_active_ver = $previewlink . '&version=' . $item->current_version;
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink_active_ver . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('FLEXI_PREVIEW_FRONTEND_ACTIVE_VERSION') . ' [' . $item->current_version . ']</a>', 'preview');
                // Add a preview button for currently LATEST version of the item
                $previewlink_last_ver = $previewlink;
                //'&version='.$item->last_version;
                $toolbar->appendButton('Custom', '<a class="preview btn btn-small" href="' . $previewlink_last_ver . '" target="_blank"><span title="' . JText::_('Preview') . '" class="icon-32-preview"></span>' . JText::_('FLEXI_PREVIEW_LATEST_SAVED_VERSION') . ' [' . $item->last_version . ']</a>', 'preview');
            }
            JToolBarHelper::spacer();
            JToolBarHelper::divider();
            JToolBarHelper::spacer();
        }
        // Common Buttons
        if (FLEXI_J16GE) {
            JToolBarHelper::apply('items.apply');
            if (!$isnew || $item->version) {
                JToolBarHelper::save('items.save');
            }
            if (!$isnew || $item->version) {
                JToolBarHelper::custom('items.saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
            }
            JToolBarHelper::cancel('items.cancel');
        } else {
            JToolBarHelper::apply();
            if (!$isnew || $item->version) {
                JToolBarHelper::save();
            }
            if (!$isnew || $item->version) {
                JToolBarHelper::custom('saveandnew', 'savenew.png', 'savenew.png', 'FLEXI_SAVE_AND_NEW', false);
            }
            JToolBarHelper::cancel();
        }
        // Check if saving an item that translates an original content in site's default language
        $is_content_default_lang = substr(flexicontent_html::getSiteDefaultLang(), 0, 2) == substr($item->language, 0, 2);
        $modify_untraslatable_values = $enable_translation_groups && !$is_content_default_lang && $item->lang_parent_id && $item->lang_parent_id != $item->id;
        // *****************************************************************************
        // Get (CORE & CUSTOM) fields and their VERSIONED values and then
        // (a) Apply Content Type Customization to CORE fields (label, description, etc)
        // (b) Create the edit html of the CUSTOM fields by triggering 'onDisplayField'
        // *****************************************************************************
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        $fields = $this->get('Extrafields');
        if ($print_logging_info) {
            $fc_run_times['get_field_vals'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        foreach ($fields as $field) {
            // a. Apply CONTENT TYPE customizations to CORE FIELDS, e.g a type specific label & description
            // NOTE: the field parameters are already created so there is not need to call this for CUSTOM fields, which do not have CONTENT TYPE customizations
            if ($field->iscore) {
                FlexicontentFields::loadFieldConfig($field, $item);
            }
            // b. Create field 's editing HTML (the form field)
            // NOTE: this is DONE only for CUSTOM fields, since form field html is created by the form for all CORE fields, EXCEPTION is the 'text' field (see bellow)
            if (!$field->iscore) {
                if (FLEXI_J16GE) {
                    $is_editable = !$field->valueseditable || $user->authorise('flexicontent.editfieldvalues', 'com_flexicontent.field.' . $field->id);
                } else {
                    if (FLEXI_ACCESS && $user->gid < 25) {
                        $is_editable = !$field->valueseditable || FAccess::checkAllContentAccess('com_content', 'submit', 'users', $user->gmid, 'field', $field->id);
                    } else {
                        $is_editable = 1;
                    }
                }
                if (!$is_editable) {
                    $field->html = '<div class="fc-mssg fc-warning">' . JText::_('FLEXI_NO_ACCESS_LEVEL_TO_EDIT_FIELD') . '</div>';
                } else {
                    if ($modify_untraslatable_values && $field->untranslatable) {
                        $field->html = '<div class="fc-mssg fc-note">' . JText::_('FLEXI_FIELD_VALUE_IS_UNTRANSLATABLE') . '</div>';
                    } else {
                        FLEXIUtilities::call_FC_Field_Func($field->field_type, 'onDisplayField', array(&$field, &$item));
                    }
                }
            }
            // c. Create main text field, via calling the display function of the textarea field (will also check for tabs)
            if ($field->field_type == 'maintext') {
                if (isset($item->item_translations)) {
                    $shortcode = substr($item->language, 0, 2);
                    foreach ($item->item_translations as $lang_id => $t) {
                        if ($shortcode == $t->shortcode) {
                            continue;
                        }
                        $field->name = array('jfdata', $t->shortcode, 'text');
                        $field->value[0] = html_entity_decode($t->fields->text->value, ENT_QUOTES, 'UTF-8');
                        FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
                        $t->fields->text->tab_labels = $field->tab_labels;
                        $t->fields->text->html = $field->html;
                        unset($field->tab_labels);
                        unset($field->html);
                    }
                }
                $field->name = 'text';
                // NOTE: We use the text created by the model and not the text retrieved by the CORE plugin code, which maybe overwritten with JoomFish/Falang data
                $field->value[0] = $item->text;
                // do not decode special characters this was handled during saving !
                // Render the field's (form) HTML
                FLEXIUtilities::call_FC_Field_Func('textarea', 'onDisplayField', array(&$field, &$item));
            }
        }
        if ($print_logging_info) {
            $fc_run_times['render_field_html'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
        // *************************
        // Get tags used by the item
        // *************************
        $usedtagsIds = $this->get('UsedtagsIds');
        // NOTE: This will normally return the already set versioned value of tags ($item->tags)
        $usedtags = $model->getUsedtagsData($usedtagsIds);
        // *******************************
        // Get categories used by the item
        // *******************************
        if ($isnew) {
            // Case for preselected main category for new items
            $maincat = $item->catid ? $item->catid : JRequest::getInt('maincat', 0);
            if (!$maincat) {
                $maincat = $app->getUserStateFromRequest($option . '.items.filter_cats', 'filter_cats', '', 'int');
            }
            if ($maincat) {
                $selectedcats = array($maincat);
                $item->catid = $maincat;
            } else {
                $selectedcats = array();
            }
            if ($tparams->get('cid_default')) {
                $selectedcats = $tparams->get('cid_default');
            }
            if ($tparams->get('catid_default')) {
                $item->catid = $tparams->get('catid_default');
            }
        } else {
            // NOTE: This will normally return the already set versioned value of categories ($item->categories)
            $selectedcats = $this->get('Catsselected');
        }
        //$selectedcats 	= $isnew ? array() : $fields['categories']->value;
        //echo "<br/>row->tags: "; print_r($item->tags);
        //echo "<br/>usedtagsIds: "; print_r($usedtagsIds);
        //echo "<br/>usedtags (data): "; print_r($usedtags);
        //echo "<br/>row->categories: "; print_r($item->categories);
        //echo "<br/>selectedcats: "; print_r($selectedcats);
        // *********************************************************************************************
        // Build select lists for the form field. Only few of them are used in J1.6+, since we will use:
        // (a) form XML file to declare them and then (b) getInput() method form field to create them
        // *********************************************************************************************
        // First clean form data, we do this after creating the description field which may contain HTML
        JFilterOutput::objectHTMLSafe($item, ENT_QUOTES);
        $lists = array();
        // build granular access list
        if (!FLEXI_J16GE) {
            if (FLEXI_ACCESS) {
                if (isset($user->level)) {
                    $lists['access'] = FAccess::TabGmaccess($item, 'item', 1, 0, 0, 1, 0, 1, 0, 1, 1);
                } else {
                    $lists['access'] = JText::_('Your profile has been changed, please logout to access to the permissions');
                }
            } else {
                $lists['access'] = JHTML::_('list.accesslevel', $item);
                // created but not used in J1.5 backend form
            }
        }
        // build state list
        $_arc_ = FLEXI_J16GE ? 2 : -1;
        $non_publishers_stategrp = $perms['isSuperAdmin'] || $item->state == -3 || $item->state == -4;
        $special_privelege_stategrp = $item->state == $_arc_ || $perms['canarchive'] || ($item->state == -2 || $perms['candelete']);
        $state = array();
        // Using <select> groups
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_PUBLISHERS_WORKFLOW_STATES'));
        }
        $state[] = JHTML::_('select.option', 1, JText::_('FLEXI_PUBLISHED'));
        $state[] = JHTML::_('select.option', 0, JText::_('FLEXI_UNPUBLISHED'));
        $state[] = JHTML::_('select.option', -5, JText::_('FLEXI_IN_PROGRESS'));
        // States reserved for workflow
        if ($non_publishers_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_NON_PUBLISHERS_WORKFLOW_STATES'));
        }
        if ($item->state == -3 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -3, JText::_('FLEXI_PENDING'));
        }
        if ($item->state == -4 || $perms['isSuperAdmin']) {
            $state[] = JHTML::_('select.option', -4, JText::_('FLEXI_TO_WRITE'));
        }
        // Special access states
        if ($special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
            $state[] = JHTML::_('select.optgroup', JText::_('FLEXI_SPECIAL_ACTION_STATES'));
        }
        if ($item->state == $_arc_ || $perms['canarchive']) {
            $state[] = JHTML::_('select.option', $_arc_, JText::_('FLEXI_ARCHIVED'));
        }
        if ($item->state == -2 || $perms['candelete']) {
            $state[] = JHTML::_('select.option', -2, JText::_('FLEXI_TRASHED'));
        }
        // Close last <select> group
        if ($non_publishers_stategrp || $special_privelege_stategrp) {
            $state[] = JHTML::_('select.optgroup', '');
        }
        $fieldname = FLEXI_J16GE ? 'jform[state]' : 'state';
        $elementid = FLEXI_J16GE ? 'jform_state' : 'state';
        $class = 'use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $lists['state'] = JHTML::_('select.genericlist', $state, $fieldname, $attribs, 'value', 'text', $item->state, $elementid);
        if (!FLEXI_J16GE) {
            $lists['state'] = str_replace('<optgroup label="">', '</optgroup>', $lists['state']);
        }
        // *** BOF: J2.5 SPECIFIC SELECT LISTS
        if (FLEXI_J16GE) {
            // build featured flag
            $fieldname = 'jform[featured]';
            $elementid = 'jform_featured';
            /*
            $options = array();
            $options[] = JHTML::_('select.option',  0, JText::_( 'FLEXI_NO' ) );
            $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_YES' ) );
            $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
            $lists['featured'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', $item->featured, $elementid);
            */
            $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
            $attribs = ' class="' . $classes . '" ';
            $i = 1;
            $options = array(0 => JText::_('FLEXI_NO'), 1 => JText::_('FLEXI_YES'));
            $lists['featured'] = '';
            foreach ($options as $option_id => $option_label) {
                $checked = $option_id == $item->featured ? ' checked="checked"' : '';
                $elementid_no = $elementid . '_' . $i;
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-label="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['featured'] .= ' <input type="radio" id="' . $elementid_no . '" element_group_id="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
                if (!$prettycheckable_added) {
                    $lists['featured'] .= '&nbsp;' . JText::_($option_label) . '</label>';
                }
                $i++;
            }
        }
        // *** EOF: J1.5 SPECIFIC SELECT LISTS
        // build version approval list
        $fieldname = FLEXI_J16GE ? 'jform[vstate]' : 'vstate';
        $elementid = FLEXI_J16GE ? 'jform_vstate' : 'vstate';
        /*
        $options = array();
        $options[] = JHTML::_('select.option',  1, JText::_( 'FLEXI_NO' ) );
        $options[] = JHTML::_('select.option',  2, JText::_( 'FLEXI_YES' ) );
        $attribs = FLEXI_J16GE ? ' style ="float:left!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
        $lists['vstate'] = JHTML::_('select.radiolist', $options, $fieldname, $attribs, 'value', 'text', 2, $elementid);
        */
        $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
        $attribs = ' class="' . $classes . '" ';
        $i = 1;
        $options = array(1 => JText::_('FLEXI_NO'), 2 => JText::_('FLEXI_YES'));
        $lists['vstate'] = '';
        foreach ($options as $option_id => $option_label) {
            $checked = $option_id == 2 ? ' checked="checked"' : '';
            $elementid_no = $elementid . '_' . $i;
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '<label class="fccheckradio_lbl" for="' . $elementid_no . '">';
            }
            $extra_params = !$prettycheckable_added ? '' : ' data-label="' . JText::_($option_label) . '" data-labelPosition="right" data-customClass="fcradiocheck"';
            $lists['vstate'] .= ' <input type="radio" id="' . $elementid_no . '" element_group_id="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="' . $option_id . '" ' . $checked . $extra_params . ' />';
            if (!$prettycheckable_added) {
                $lists['vstate'] .= '&nbsp;' . JText::_($option_label) . '</label>';
            }
            $i++;
        }
        // build field for notifying subscribers
        if (!$subscribers) {
            $lists['notify'] = !$isnew ? JText::_('FLEXI_NO_SUBSCRIBERS_EXIST') : '';
        } else {
            // b. Check if notification emails to subscribers , were already sent during current session
            $subscribers_notified = $session->get('subscribers_notified', array(), 'flexicontent');
            if (!empty($subscribers_notified[$item->id])) {
                $lists['notify'] = JText::_('FLEXI_SUBSCRIBERS_ALREADY_NOTIFIED');
            } else {
                // build favs notify field
                $fieldname = FLEXI_J16GE ? 'jform[notify]' : 'notify';
                $elementid = FLEXI_J16GE ? 'jform_notify' : 'notify';
                /*
                $attribs = FLEXI_J16GE ? ' style ="float:none!important;" '  :  '';   // this is not right for J1.5' style ="float:left!important;" ';
                $lists['notify'] = '<input type="checkbox" name="jform[notify]" id="jform_notify" '.$attribs.' /> '. $lbltxt;
                */
                $classes = !$prettycheckable_added ? '' : ' use_prettycheckable ';
                $attribs = ' class="' . $classes . '" ';
                $lbltxt = $subscribers . ' ' . JText::_($subscribers > 1 ? 'FLEXI_SUBSCRIBERS' : 'FLEXI_SUBSCRIBER');
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '<label class="fccheckradio_lbl" for="' . $elementid . '">';
                }
                $extra_params = !$prettycheckable_added ? '' : ' data-label="' . $lbltxt . '" data-labelPosition="right" data-customClass="fcradiocheck"';
                $lists['notify'] = ' <input type="checkbox" id="' . $elementid . '" element_group_id="' . $elementid . '" name="' . $fieldname . '" ' . $attribs . ' value="1" ' . $extra_params . ' checked="checked" />';
                if (!$prettycheckable_added) {
                    $lists['notify'] .= '&nbsp;' . $lbltxt . '</label>';
                }
            }
        }
        // Retrieve author configuration
        $db->setQuery('SELECT author_basicparams FROM #__flexicontent_authors_ext WHERE user_id = ' . $user->id);
        if ($authorparams = $db->loadResult()) {
            $authorparams = FLEXI_J16GE ? new JRegistry($authorparams) : new JParameter($authorparams);
        }
        // Get author's maximum allowed categories per item and set js limitation
        $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
        $document->addScriptDeclaration('
			max_cat_assign_fc = ' . $max_cat_assign . ';
			existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
			max_cat_overlimit_msg_fc = "' . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES', true) . '";
		');
        // Creating categorories tree for item assignment, we use the 'create' privelege
        $actions_allowed = array('core.create');
        // Featured categories form field
        $featured_cats_parent = $params->get('featured_cats_parent', 0);
        $featured_cats = array();
        $enable_featured_cid_selector = $perms['multicat'] && $perms['canchange_featcat'];
        if ($featured_cats_parent) {
            $featured_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $featured_cats_parent, $depth_limit = 0);
            $featured_sel = array();
            foreach ($selectedcats as $item_cat) {
                if (isset($featured_tree[$item_cat])) {
                    $featured_sel[] = $item_cat;
                }
            }
            $class = "use_select2_lib select2_list_selected";
            $attribs = 'class="' . $class . '" multiple="multiple" size="8"';
            $attribs .= $enable_featured_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = FLEXI_J16GE ? 'jform[featured_cid][]' : 'featured_cid[]';
            $lists['featured_cid'] = ($enable_featured_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($featured_tree, $fieldname, $featured_sel, 3, $attribs, true, true, $actions_allowed);
        } else {
            // Do not display, if not configured or not allowed to the user
            $lists['featured_cid'] = false;
        }
        // Multi-category form field, for user allowed to use multiple categories
        $lists['cid'] = '';
        $enable_cid_selector = $perms['multicat'] && $perms['canchange_seccat'];
        if (1) {
            if ($tparams->get('cid_allowed_parent')) {
                $cid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('cid_allowed_parent'), $depth_limit = 0);
            } else {
                $cid_tree =& $categories;
            }
            // Get author's maximum allowed categories per item and set js limitation
            $max_cat_assign = !$authorparams ? 0 : intval($authorparams->get('max_cat_assign', 0));
            $document->addScriptDeclaration('
				max_cat_assign_fc = ' . $max_cat_assign . ';
				existing_cats_fc  = ["' . implode('","', $selectedcats) . '"];
				max_cat_overlimit_msg_fc = "' . JText::_('FLEXI_TOO_MANY_ITEM_CATEGORIES', true) . '";
			');
            $class = "mcat use_select2_lib select2_list_selected";
            $class .= $max_cat_assign ? " validate-fccats" : " validate";
            $attribs = 'class="' . $class . '" multiple="multiple" size="20"';
            $attribs .= $enable_cid_selector ? '' : ' disabled="disabled"';
            $fieldname = FLEXI_J16GE ? 'jform[cid][]' : 'cid[]';
            $skip_subtrees = $featured_cats_parent ? array($featured_cats_parent) : array();
            $lists['cid'] = ($enable_cid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($cid_tree, $fieldname, $selectedcats, false, $attribs, true, true, $actions_allowed, $require_all = true, $skip_subtrees, $disable_subtrees = array());
        } else {
            if (count($selectedcats) > 1) {
                foreach ($selectedcats as $catid) {
                    $cat_titles[$catid] = $globalcats[$catid]->title;
                }
                $lists['cid'] .= implode(', ', $cat_titles);
            } else {
                $lists['cid'] = false;
            }
        }
        // Main category form field
        $class = 'scat use_select2_lib';
        if ($perms['multicat']) {
            $class .= ' validate-catid';
        } else {
            $class .= ' required';
        }
        $attribs = 'class="' . $class . '"';
        $fieldname = FLEXI_J16GE ? 'jform[catid]' : 'catid';
        $enable_catid_selector = $isnew && !$tparams->get('catid_default') || !$isnew && empty($item->catid) || $perms['canchange_cat'];
        if ($tparams->get('catid_allowed_parent')) {
            $catid_tree = flexicontent_cats::getCategoriesTree($published_only = 1, $parent_id = $tparams->get('catid_allowed_parent'), $depth_limit = 0);
        } else {
            $catid_tree =& $categories;
        }
        $lists['catid'] = false;
        if (!empty($catid_tree)) {
            $disabled = $enable_catid_selector ? '' : ' disabled="disabled"';
            $attribs .= $disabled;
            $lists['catid'] = ($enable_catid_selector ? '' : '<label class="label" style="float:none; margin:0 6px 0 0 !important;">locked</label>') . flexicontent_cats::buildcatselect($catid_tree, $fieldname, $item->catid, 2, $attribs, true, true, $actions_allowed);
        } else {
            if (!$isnew && $item->catid) {
                $lists['catid'] = $globalcats[$item->catid]->title;
            }
        }
        //buid types selectlist
        $class = 'required use_select2_lib';
        $attribs = 'class="' . $class . '"';
        $fieldname = FLEXI_J16GE ? 'jform[type_id]' : 'type_id';
        $elementid = FLEXI_J16GE ? 'jform_type_id' : 'type_id';
        $lists['type'] = flexicontent_html::buildtypesselect($types, $fieldname, $typesselected->id, 1, $attribs, $elementid, $check_perms = true);
        //build languages list
        $allowed_langs = !$authorparams ? null : $authorparams->get('langs_allowed', null);
        $allowed_langs = !$allowed_langs ? null : FLEXIUtilities::paramToArray($allowed_langs);
        if (!$isnew && $allowed_langs) {
            $allowed_langs[] = $item->language;
        }
        // We will not use the default getInput() function of J1.6+ since we want to create a radio selection field with flags
        // we could also create a new class and override getInput() method but maybe this is an overkill, we may do it in the future
        $language_fieldname = FLEXI_J16GE ? 'jform[language]' : 'language';
        if (FLEXI_FISH || FLEXI_J16GE) {
            $lists['languages'] = flexicontent_html::buildlanguageslist($language_fieldname, '', $item->language, 3, $allowed_langs);
        }
        // Label for current item state: published, unpublished, archived etc
        switch ($item->state) {
            case 0:
                $published = JText::_('FLEXI_UNPUBLISHED');
                break;
            case 1:
                $published = JText::_('FLEXI_PUBLISHED');
                break;
            case -1:
                $published = JText::_('FLEXI_ARCHIVED');
                break;
            case -3:
                $published = JText::_('FLEXI_PENDING');
                break;
            case -5:
                $published = JText::_('FLEXI_IN_PROGRESS');
                break;
            case -4:
            default:
                $published = JText::_('FLEXI_TO_WRITE');
                break;
        }
        // **************************************************************
        // Handle Item Parameters Creation and Load their values for J1.5
        // In J1.6+ we declare them in the item form XML file
        // **************************************************************
        if (!FLEXI_J16GE) {
            // Create the form parameters object
            if (FLEXI_ACCESS) {
                $formparams = new JParameter('', JPATH_COMPONENT . DS . 'models' . DS . 'item2.xml');
            } else {
                $formparams = new JParameter('', JPATH_COMPONENT . DS . 'models' . DS . 'item.xml');
            }
            // Details Group
            $active = intval($item->created_by) ? intval($item->created_by) : $user->get('id');
            if (!FLEXI_ACCESS) {
                $formparams->set('access', $item->access);
            }
            $formparams->set('created_by', $active);
            $formparams->set('created_by_alias', $item->created_by_alias);
            $formparams->set('created', JHTML::_('date', $item->created, '%Y-%m-%d %H:%M:%S'));
            $formparams->set('publish_up', JHTML::_('date', $item->publish_up, '%Y-%m-%d %H:%M:%S'));
            if (JHTML::_('date', $item->publish_down, '%Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
                $formparams->set('publish_down', JText::_('FLEXI_NEVER'));
            } else {
                $formparams->set('publish_down', JHTML::_('date', $item->publish_down, '%Y-%m-%d %H:%M:%S'));
            }
            // Advanced Group
            $formparams->loadINI($item->attribs);
            //echo "<pre>"; print_r($formparams->_xml['themes']->_children[0]);  echo "<pre>"; print_r($formparams->_xml['themes']->param[0]); exit;
            foreach ($formparams->_xml['themes']->_children as $i => $child) {
                if (isset($child->_attributes['enableparam']) && !$params->get($child->_attributes['enableparam'])) {
                    unset($formparams->_xml['themes']->_children[$i]);
                    unset($formparams->_xml['themes']->param[$i]);
                }
            }
            // Metadata Group
            $formparams->set('description', $item->metadesc);
            $formparams->set('keywords', $item->metakey);
            $formparams->loadINI($item->metadata);
        } else {
            if (JHTML::_('date', $item->publish_down, 'Y') <= 1969 || $item->publish_down == $db->getNullDate() || empty($item->publish_down)) {
                $form->setValue('publish_down', null, JText::_('FLEXI_NEVER'));
            }
        }
        // ****************************
        // Handle Template related work
        // ****************************
        // (a) Get the templates structures used to create form fields for template parameters
        $themes = flexicontent_tmpl::getTemplates();
        $tmpls_all = $themes->items;
        // (b) Get Content Type allowed templates
        $allowed_tmpls = $tparams->get('allowed_ilayouts');
        $type_default_layout = $tparams->get('ilayout', 'default');
        if (empty($allowed_tmpls)) {
            $allowed_tmpls = array();
        } else {
            if (!is_array($allowed_tmpls)) {
                $allowed_tmpls = !FLEXI_J16GE ? array($allowed_tmpls) : explode("|", $allowed_tmpls);
            }
        }
        // (c) Add default layout, unless all templates allowed (=array is empty)
        if (count($allowed_tmpls) && !in_array($type_default_layout, $allowed_tmpls)) {
            $allowed_tmpls[] = $type_default_layout;
        }
        // (d) Create array of template data according to the allowed templates for current content type
        if (count($allowed_tmpls)) {
            foreach ($tmpls_all as $tmpl) {
                if (in_array($tmpl->name, $allowed_tmpls)) {
                    $tmpls[] = $tmpl;
                }
            }
        } else {
            $tmpls = $tmpls_all;
        }
        // (e) Apply Template Parameters values into the form fields structures
        foreach ($tmpls as $tmpl) {
            if (FLEXI_J16GE) {
                $jform = new JForm('com_flexicontent.template.item', array('control' => 'jform', 'load_data' => true));
                $jform->load($tmpl->params);
                $tmpl->params = $jform;
                foreach ($tmpl->params->getGroup('attribs') as $field) {
                    $fieldname = $field->__get('fieldname');
                    $value = $item->itemparams->get($fieldname);
                    if (strlen($value)) {
                        $tmpl->params->setValue($fieldname, 'attribs', $value);
                    }
                }
            } else {
                $tmpl->params->loadINI($item->attribs);
            }
        }
        // ******************************
        // Assign data to VIEW's template
        // ******************************
        $this->assignRef('document', $document);
        $this->assignRef('lists', $lists);
        $this->assignRef('row', $item);
        if (FLEXI_J16GE) {
            $this->assignRef('form', $form);
        } else {
            $this->assignRef('editor', $editor);
            $this->assignRef('pane', $pane);
            $this->assignRef('formparams', $formparams);
        }
        if ($enable_translation_groups) {
            $this->assignRef('lang_assocs', $langAssocs);
        }
        if (FLEXI_FISH || FLEXI_J16GE) {
            $this->assignRef('langs', $langs);
        }
        $this->assignRef('typesselected', $typesselected);
        $this->assignRef('published', $published);
        $this->assignRef('nullDate', $nullDate);
        $this->assignRef('subscribers', $subscribers);
        $this->assignRef('fields', $fields);
        $this->assignRef('versions', $versions);
        $this->assignRef('pagecount', $pagecount);
        $this->assignRef('params', $params);
        $this->assignRef('tparams', $tparams);
        $this->assignRef('tmpls', $tmpls);
        $this->assignRef('usedtags', $usedtags);
        $this->assignRef('perms', $perms);
        $this->assignRef('current_page', $current_page);
        if ($print_logging_info) {
            $start_microtime = microtime(true);
        }
        parent::display($tpl);
        if ($print_logging_info) {
            $fc_run_times['form_rendering'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
        }
    }
Exemplo n.º 15
0
 function onBeforeSaveField(&$field, &$post, &$file, &$item)
 {
     if ($field->iscore != 1) {
         return;
     }
     if (!is_array($post) && !strlen($post)) {
         return;
     }
     if ($field->field_type == 'maintext') {
         // field_type is not changed textarea so that field can handle this field type
         FLEXIUtilities::call_FC_Field_Func('textarea', 'onBeforeSaveField', array(&$field, &$post, &$file, &$item));
     }
 }
Exemplo n.º 16
0
 /**
  * Method to get the active filter result
  * 
  * @access private
  * @return string
  * @since 1.5
  */
 function _getFiltered(&$filter, $value)
 {
     $field_type = $filter->field_type;
     // Sanitize filter values as integers for field that use integer values
     if (in_array($field_type, array('createdby', 'modifiedby', 'type', 'categories', 'tags'))) {
         $values = is_array($value) ? $value : array($value);
         foreach ($values as $i => $v) {
             $values[$i] = (int) $v;
         }
     }
     switch ($field_type) {
         case 'createdby':
             $filter_query = ' AND i.created_by IN (' . implode(",", $values) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'modifiedby':
             $filter_query = ' AND i.modified_by IN (' . implode(",", $values) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'type':
             //$filter_query = ' AND ie.type_id IN ('. implode(",", $values) .')';   // no db quoting needed since these were typecasted to ints
             $query = 'SELECT item_id' . ' FROM #__flexicontent_items_ext' . ' WHERE type_id IN (' . implode(",", $values) . ')';
             $filter_query = ' AND i.id IN (' . $query . ')';
             break;
         case 'state':
             $stateids = array('PE' => -3, 'OQ' => -4, 'IP' => -5, 'P' => 1, 'U' => 0, 'A' => FLEXI_J16GE ? 2 : -1, 'T' => -2);
             $values = is_array($value) ? $value : array($value);
             $filt_states = array();
             foreach ($values as $i => $v) {
                 if (isset($stateids[$v])) {
                     $filt_states[] = $stateids[$v];
                 }
             }
             $filter_query = !count($values) ? ' AND 1=0 ' : ' AND i.state IN (' . implode(",", $filt_states) . ')';
             // no db quoting needed since these were typecasted to ints
             break;
         case 'categories':
             //$filter_query = ' AND rel.catid IN ('. implode(",", $values) .')';
             $query = 'SELECT itemid' . ' FROM #__flexicontent_cats_item_relations' . ' WHERE catid IN (' . implode(",", $values) . ')';
             $filter_query = ' AND i.id IN (' . $query . ')';
             break;
         case 'tags':
             $query = 'SELECT itemid' . ' FROM #__flexicontent_tags_item_relations' . ' WHERE tid IN (' . implode(",", $values) . ')';
             $filter_query = ' AND i.id IN (' . $query . ')';
             break;
         default:
             // Make sure plugin file of current file is loaded and then check if custom filtering function exists
             $field_type_file = $filter->iscore ? 'core' : $field_type;
             $path = JPATH_ROOT . DS . 'plugins' . DS . 'flexicontent_fields' . DS . strtolower($field_type_file) . (FLEXI_J16GE ? DS . strtolower($field_type_file) : "") . '.php';
             if (file_exists($path)) {
                 require_once $path;
                 $method_exists = method_exists("plgFlexicontent_fields{$field_type_file}", "getFiltered");
             }
             // Use custom field filtering if 'getFiltered' plugin method exists, otherwise try to use our default filtering function
             $filtered = !@$method_exists ? FlexicontentFields::getFiltered($filter, $value, $return_sql = true) : FLEXIUtilities::call_FC_Field_Func($field_type_file, 'getFiltered', array(&$filter, &$value));
             // An empty return value means no matching values we found
             $filtered = empty($filtered) ? ' AND 1=0' : $filtered;
             // A string mean a subquery was returned, while an array means that item ids we returned
             $filter_query = is_array($filtered) ? ' AND i.id IN (' . implode(',', $filtered) . ')' : $filtered;
             break;
     }
     //echo "<br/>".$filter_query."<br/>";
     return $filter_query;
 }
Exemplo n.º 17
0
 /**
  * Method to save field values of the item in field versioning DB table or in ..._fields_item_relations DB table 
  *
  * @access	public
  * @return	boolean	True on success
  * @since	1.0
  */
 function saveFields($isnew, &$item, &$data, &$files)
 {
     $app = JFactory::getApplication();
     $user = JFactory::getUser();
     $dispatcher = JDispatcher::getInstance();
     $cparams = $this->_cparams;
     $use_versioning = $cparams->get('use_versioning', 1);
     $print_logging_info = $cparams->get('print_logging_info');
     $last_version = FLEXIUtilities::getLastVersions($item->id, true);
     $mval_query = true;
     if ($print_logging_info) {
         global $fc_run_times;
     }
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     //*********************************
     // Checks for untranslatable fields
     //*********************************
     // CASE 1. Check if saving an item that translates an original content in site's default language
     // ... Decide whether to retrieve field values of untranslatable fields from the original content item
     $enable_translation_groups = $cparams->get('enable_translation_groups');
     $is_content_default_lang = substr(flexicontent_html::getSiteDefaultLang(), 0, 2) == substr($item->language, 0, 2);
     $get_untraslatable_values = $enable_translation_groups && !$is_content_default_lang && $item->lang_parent_id && $item->lang_parent_id != $item->id;
     // CASE 2. Check if saving an original content item (item's language is site default language)
     // ... Get item ids of translating items
     if ($is_content_default_lang && $this->_id) {
         $query = 'SELECT ie.item_id' . ' FROM #__flexicontent_items_ext as ie' . ' WHERE ie.lang_parent_id = ' . (int) $this->_id . '  AND ie.item_id <> ' . (int) $this->_id;
         // DO NOT include the item itself in associated translations !!
         $this->_db->setQuery($query);
         $assoc_item_ids = FLEXI_J16GE ? $this->_db->loadColumn() : $this->_db->loadResultArray();
     }
     if (empty($assoc_item_ids)) {
         $assoc_item_ids = array();
     }
     // ***************************************************************************************************************************
     // Get item's fields ... and their values (for untranslatable fields the field values from original content item are retrieved
     // ***************************************************************************************************************************
     $fields = $this->getExtrafields($force = true, $get_untraslatable_values ? $item->lang_parent_id : 0);
     // ******************************************************************************************************************
     // Loop through Fields triggering onBeforeSaveField Event handlers, this was seperated from the rest of the process
     // to give chance to ALL fields to check their DATA and cancel item saving process before saving any new field values
     // ******************************************************************************************************************
     $searchindex = array();
     //$qindex = array();
     if ($fields) {
         foreach ($fields as $field) {
             // Set vstate property into the field object to allow this to be changed be the before saving  field event handler
             $field->item_vstate = $data['vstate'];
             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;
                 }
             }
             // FORM HIDDEN FIELDS (FRONTEND/BACKEND) AND (ACL) UNEDITABLE FIELDS: maintain their DB value ...
             if ($app->isSite() && ($field->formhidden == 1 || $field->formhidden == 3 || $field->parameters->get('frontend_hidden')) || $app->isAdmin() && ($field->formhidden == 2 || $field->formhidden == 3 || $field->parameters->get('backend_hidden')) || !$is_editable) {
                 $postdata[$field->name] = $field->value;
                 // UNTRANSLATABLE (CUSTOM) FIELDS: maintain their DB value ...
             } else {
                 if ($get_untraslatable_values && $field->untranslatable) {
                     $postdata[$field->name] = $field->value;
                     // CORE FIELDS: if not set maintain their DB value ...
                 } else {
                     if ($field->iscore) {
                         $postdata[$field->name] = @$data[$field->name];
                         if (is_array($postdata[$field->name]) && !count($postdata[$field->name]) || !is_array($postdata[$field->name]) && !strlen(trim($postdata[$field->name]))) {
                             $postdata[$field->name] = $field->value;
                         }
                         // OTHER CUSTOM FIELDS (not hidden and not untranslatable)
                     } else {
                         $postdata[$field->name] = !FLEXI_J16GE ? @$data[$field->name] : @$data['custom'][$field->name];
                     }
                 }
             }
             // Unserialize values already serialized values, e.g. (a) if current values used are from DB or (b) are being imported from CSV file
             if (!is_array($postdata[$field->name])) {
                 $postdata[$field->name] = strlen($postdata[$field->name]) ? array($postdata[$field->name]) : array();
             }
             //echo "<b>{$field->field_type}</b>: <br/> <pre>".print_r($postdata[$field->name], true)."</pre>\n";
             foreach ($postdata[$field->name] as $i => $postdata_val) {
                 if (@unserialize($postdata_val) !== false || $postdata_val === 'b:0;') {
                     $postdata[$field->name][$i] = unserialize($postdata_val);
                 }
             }
             // Trigger plugin Event 'onBeforeSaveField'
             $fieldname = $field->iscore ? 'core' : $field->field_type;
             $result = FLEXIUtilities::call_FC_Field_Func($fieldname, 'onBeforeSaveField', array(&$field, &$postdata[$field->name], &$files[$field->name], &$item));
             //$qindex[$field->name] = NULL;
             //$result = FLEXIUtilities::call_FC_Field_Func($fieldname, 'onBeforeSaveField', array( &$field, &$postdata[$field->name], &$files[$field->name], &$item, &$qindex[$field->name] ));
             if ($result === false) {
                 // Field requested to abort item saving
                 $this->setError(JText::sprintf('FLEXI_FIELD_VALUE_IS_INVALID', $field->label));
                 return 'abort';
             }
             // Get vstate property from the field object back to the data array
             $data['vstate'] = $field->item_vstate;
         }
         //echo "<pre>"; print_r($postdata); echo "</pre>"; exit;
     }
     if ($print_logging_info) {
         @($fc_run_times['fields_value_preparation'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // ****************************************************************************************************************************
     // Loop through Fields triggering onIndexAdvSearch, onIndexSearch Event handlers, this was seperated from the before save field
     //  event, so that we will update search indexes only if the above has not canceled saving OR has not canceled version approval
     // ****************************************************************************************************************************
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     if ($fields) {
         $ai_query_vals = array();
         foreach ($fields as $field) {
             $fieldname = $field->iscore ? 'core' : $field->field_type;
             if ($data['vstate'] == 2 || $isnew) {
                 // Trigger plugin Event 'onIndexAdvSearch' to update field-item pair records in advanced search index
                 FLEXIUtilities::call_FC_Field_Func($fieldname, 'onIndexAdvSearch', array(&$field, &$postdata[$field->name], &$item));
                 if (isset($field->ai_query_vals)) {
                     foreach ($field->ai_query_vals as $query_val) {
                         $ai_query_vals[] = $query_val;
                     }
                 }
                 //echo $field->name .":".implode(",", @$field->ai_query_vals ? $field->ai_query_vals : array() )."<br/>";
                 // Trigger plugin Event 'onIndexSearch' to update item 's (basic) search index record
                 FLEXIUtilities::call_FC_Field_Func($fieldname, 'onIndexSearch', array(&$field, &$postdata[$field->name], &$item));
                 if (strlen(@$field->search[$item->id])) {
                     $searchindex[] = $field->search[$item->id];
                 }
                 //echo $field->name .":".@$field->search[$item->id]."<br/>";
             }
         }
     }
     // Remove item's old advanced search index entries
     $query = "DELETE FROM #__flexicontent_advsearch_index WHERE item_id=" . $item->id;
     $this->_db->setQuery($query);
     $this->_db->query();
     // Store item's advanced search index entries
     if (!empty($ai_query_vals)) {
         $query = "INSERT INTO #__flexicontent_advsearch_index " . " (field_id,item_id,extraid,search_index,value_id) VALUES " . implode(",", $ai_query_vals);
         $this->_db->setQuery($query);
         $this->_db->query();
         if ($this->_db->getErrorNum()) {
             JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($this->_db->getErrorMsg()), 'error');
         }
     }
     // Assigned created basic search index into item object
     $item->search_index = implode(' | ', $searchindex);
     // Check if vstate was set to 1 (no approve new version) while versioning is disabled
     if (!$use_versioning && $data['vstate'] != 2) {
         $data['vstate'] = 2;
         $app->enqueueMessage('vstate cannot be set to 1 (=no approve new version) when versioning is disabled', 'notice');
     }
     if ($print_logging_info) {
         @($fc_run_times['fields_value_indexing'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     if ($print_logging_info) {
         $start_microtime = microtime(true);
     }
     // **************************************************************************
     // IF new version is approved, remove old version values from the field table
     // **************************************************************************
     if ($data['vstate'] == 2) {
         //echo "delete __flexicontent_fields_item_relations, item_id: " .$item->id;
         $query = 'DELETE FROM #__flexicontent_fields_item_relations WHERE item_id = ' . $item->id;
         $this->_db->setQuery($query);
         $this->_db->query();
         $query = 'DELETE FROM #__flexicontent_items_versions WHERE item_id=' . $item->id . ' AND version=' . ((int) $last_version + 1);
         $this->_db->setQuery($query);
         $this->_db->query();
         $untranslatable_fields = array();
         if ($fields) {
             foreach ($fields as $field) {
                 if ($field->iscore) {
                     continue;
                 }
                 if (count($assoc_item_ids) && $field->untranslatable) {
                     // Delete field values in all translating items, if current field is untranslatable and current item version is approved
                     // NOTE: item itself is not include in associated translations, no need to check for it and skip itit
                     if (!$mval_query) {
                         $query = 'DELETE FROM #__flexicontent_fields_item_relations WHERE item_id IN (' . implode(',', $assoc_item_ids) . ') AND field_id=' . $field->id;
                         $this->_db->setQuery($query);
                         $this->_db->query();
                     } else {
                         $untranslatable_fields[] = $field->id;
                     }
                 }
             }
         }
         if (count($untranslatable_fields)) {
             $query = 'DELETE FROM #__flexicontent_fields_item_relations WHERE item_id IN (' . implode(',', $assoc_item_ids) . ') AND field_id IN (' . implode(',', $untranslatable_fields) . ')';
             $this->_db->setQuery($query);
             $this->_db->query();
         }
     }
     // *******************************************
     // Loop through Fields saving the field values
     // *******************************************
     if ($fields) {
         // Do not save if versioning disabled or item has no type (version 0)
         $record_versioned_data = $use_versioning && $item->version;
         $ver_query_vals = array();
         $rel_query_vals = array();
         foreach ($fields as $field) {
             // -- Add the new values to the database
             $postvalues = $this->formatToArray($postdata[$field->name]);
             //$qindex_values = $qindex[$field->name];
             $i = 1;
             foreach ($postvalues as $postvalue) {
                 // Create field obj for DB insertion
                 $obj = new stdClass();
                 $obj->field_id = $field->id;
                 $obj->item_id = $item->id;
                 $obj->valueorder = $i;
                 $obj->version = (int) $last_version + 1;
                 // Serialize the properties of the value, normally this is redudant, since the field must have had serialized the parameters of each value already
                 $obj->value = is_array($postvalue) ? serialize($postvalue) : $postvalue;
                 //$obj->qindex01 = isset($qindex_values['qindex01']) ? $qindex_values['qindex01'] : NULL;
                 //$obj->qindex02 = isset($qindex_values['qindex02']) ? $qindex_values['qindex02'] : NULL;
                 //$obj->qindex03 = isset($qindex_values['qindex03']) ? $qindex_values['qindex03'] : NULL;
                 // -- a. Add versioning values, but do not version the 'hits' or 'state' or 'voting' fields
                 if ($record_versioned_data && $field->field_type != 'hits' && $field->field_type != 'state' && $field->field_type != 'voting') {
                     // Insert only if value non-empty
                     if (isset($obj->value) && JString::strlen(trim($obj->value))) {
                         if (!$mval_query) {
                             $this->_db->insertObject('#__flexicontent_items_versions', $obj);
                         } else {
                             $ver_query_vals[] = "(" . $obj->field_id . "," . $obj->item_id . "," . $obj->valueorder . "," . $obj->version . "," . $this->_db->Quote($obj->value) . ")";
                         }
                     }
                 }
                 //echo $field->field_type." - ".$field->name." - ".JString::strlen(trim($obj->value))." ".$field->iscore."<br/>";
                 // -- b. If item is new OR version is approved, AND field is not core (aka stored in the content table or in special table), then add field value to field values table
                 if (($isnew || $data['vstate'] == 2) && !$field->iscore) {
                     // UNSET version it it used only verion data table, and insert only if value non-empty
                     unset($obj->version);
                     if (isset($obj->value) && JString::strlen(trim($obj->value))) {
                         if (!$mval_query) {
                             $this->_db->insertObject('#__flexicontent_fields_item_relations', $obj);
                         } else {
                             $rel_query_vals[] = "(" . $obj->field_id . "," . $obj->item_id . "," . $obj->valueorder . "," . $this->_db->Quote($obj->value) . ")";
                         }
                         // Save field value in all translating items, if current field is untranslatable
                         // NOTE: item itself is not include in associated translations, no need to check for it and skip it
                         if (count($assoc_item_ids) && $field->untranslatable) {
                             foreach ($assoc_item_ids as $t_item_id) {
                                 $obj->item_id = $t_item_id;
                                 if (!$mval_query) {
                                     $this->_db->insertObject('#__flexicontent_fields_item_relations', $obj);
                                 } else {
                                     $rel_query_vals[] = "(" . $obj->field_id . "," . $obj->item_id . "," . $obj->valueorder . "," . $this->_db->Quote($obj->value) . ")";
                                 }
                             }
                         }
                     }
                 }
                 $i++;
             }
         }
         // *********************************************
         // Insert values in item fields versioning table
         // *********************************************
         if (count($ver_query_vals)) {
             $query = "INSERT INTO #__flexicontent_items_versions " . " (field_id,item_id,valueorder,version,value" . ") VALUES " . "\n" . implode(",\n", $ver_query_vals);
             $this->_db->setQuery($query);
             $this->_db->query();
             if ($this->_db->getErrorNum()) {
                 JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($this->_db->getErrorMsg()), 'error');
             }
         }
         // *******************************************
         // Insert values in item fields relation table
         // *******************************************
         if (count($rel_query_vals)) {
             $query = "INSERT INTO #__flexicontent_fields_item_relations " . " (field_id,item_id,valueorder,value" . ") VALUES " . "\n" . implode(",\n", $rel_query_vals);
             $this->_db->setQuery($query);
             $this->_db->query();
             if ($this->_db->getErrorNum()) {
                 JFactory::getApplication()->enqueueMessage(__FUNCTION__ . '(): SQL QUERY ERROR:<br/>' . nl2br($this->_db->getErrorMsg()), 'error');
             }
         }
         // **************************************************************
         // Save other versioned item data into the field versioning table
         // **************************************************************
         // a. Save a version of item properties that do not have a corresponding CORE Field
         if ($record_versioned_data) {
             $obj = new stdClass();
             $obj->field_id = -2;
             // ID of Fake Field used to contain item properties not having a corresponding CORE field
             $obj->item_id = $item->id;
             $obj->valueorder = 1;
             $obj->version = (int) $last_version + 1;
             $item_data = array();
             $iproperties = array('alias', 'catid', 'metadesc', 'metakey', 'metadata', 'attribs');
             if (FLEXI_J16GE) {
                 $j16ge_iproperties = array('urls', 'images');
                 $iproperties = array_merge($iproperties, $j16ge_iproperties);
             }
             foreach ($iproperties as $iproperty) {
                 $item_data[$iproperty] = $item->{$iproperty};
             }
             $obj->value = serialize($item_data);
             $this->_db->insertObject('#__flexicontent_items_versions', $obj);
         }
         // b. Finally save a version of the posted JoomFish translated data for J1.5, if such data are editted inside the item edit form
         if (FLEXI_FISH && !empty($data['jfdata']) && $record_versioned_data) {
             $obj = new stdClass();
             $obj->field_id = -1;
             // ID of Fake Field used to contain the Joomfish translated item data
             $obj->item_id = $item->id;
             $obj->valueorder = 1;
             $obj->version = (int) $last_version + 1;
             $item_lang = substr($item->language, 0, 2);
             $data['jfdata'][$item_lang]['alias'] = $item->alias;
             $data['jfdata'][$item_lang]['metadesc'] = $item->metadesc;
             $data['jfdata'][$item_lang]['metakey'] = $item->metakey;
             $obj->value = serialize($data['jfdata']);
             $this->_db->insertObject('#__flexicontent_items_versions', $obj);
         }
     }
     if ($print_logging_info) {
         @($fc_run_times['fields_value_saving'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
     }
     // ******************************
     // Trigger onAfterSaveField Event
     // ******************************
     if ($fields) {
         if ($print_logging_info) {
             $start_microtime = microtime(true);
         }
         foreach ($fields as $field) {
             $fieldname = $field->iscore ? 'core' : $field->field_type;
             $result = FLEXIUtilities::call_FC_Field_Func($fieldname, 'onAfterSaveField', array(&$field, &$postdata[$field->name], &$files[$field->name], &$item));
             // *** $result is ignored
         }
         if ($print_logging_info) {
             @($fc_run_times['onAfterSaveField_event'] = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10);
         }
     }
     return true;
 }
Exemplo n.º 18
0
    function onDisplayField(&$field, &$item)
    {
        if (!in_array($field->field_type, self::$field_types)) {
            return;
        }
        // Check max allowed version
        $manifest_path = JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'manifest.xml';
        $com_xml = JApplicationHelper::parseXMLInstallFile($manifest_path);
        if (version_compare(str_replace(' ', '.', $com_xml['version']), str_replace(' ', '.', self::$prior_to_version), '>=')) {
            echo '
			<span class="fc-note fc-nobgimage fc-mssg">
				Warning: installed version of Field: \'<b>' . $field->field_type . '</b>\' was meant for FLEXIcontent versions prior to: v' . self::$prior_to_version . ' <br/> It may or may not work properly in later versions<br/>
			</span>';
        }
        $field->label = JText::_($field->label);
        $use_ingroup = 0;
        // Field grouped should not be recursively grouped
        if ($use_ingroup) {
            $field->formhidden = 3;
        }
        if ($use_ingroup && empty($field->ingroup)) {
            return;
        }
        $compact_edit = $field->parameters->get('compact_edit', 0);
        // initialize framework objects and other variables
        $document = JFactory::getDocument();
        $db = JFactory::getDBO();
        $tooltip_class = FLEXI_J30GE ? 'hasTooltip' : 'hasTip';
        // ****************
        // Number of values
        // ****************
        $multiple = $use_ingroup || (int) $field->parameters->get('allow_multiple', 0);
        $max_values = $use_ingroup ? 0 : (int) $field->parameters->get('max_values', 0);
        $required = $field->parameters->get('required', 0);
        $required = $required ? ' required' : '';
        $add_position = (int) $field->parameters->get('add_position', 3);
        // **************
        // Value handling
        // **************
        // Get fields belonging to this field group
        $grouped_fields = $this->getGroupFields($field);
        // Get values of fields making sure that also empty values are created too
        $max_count = 1;
        $this->getGroupFieldsValues($grouped_fields, $item, $max_count);
        // Render Form HTML of the field
        foreach ($grouped_fields as $field_id => $grouped_field) {
            for ($n = count($grouped_field->value); $n < $max_count; $n++) {
                $grouped_field->value[$n] = null;
            }
            $grouped_field->ingroup = 1;
            $grouped_field->item_id = $item->id;
            FLEXIUtilities::call_FC_Field_Func($grouped_field->field_type, 'onDisplayField', array(&$grouped_field, &$item));
            unset($grouped_field->ingroup);
        }
        $js = "";
        $css = "";
        if ($multiple) {
            // Add the drag and drop sorting feature
            if (!$use_ingroup) {
                $js .= "\n\t\t\tjQuery(document).ready(function(){\n\t\t\t\tjQuery('#sortables_" . $field->id . "').sortable({\n\t\t\t\t\thandle: '.fcfield-drag-handle',\n\t\t\t\t\tcontainment: 'parent',\n\t\t\t\t\ttolerance: 'pointer'\n\t\t\t\t});\n\t\t\t});\n\t\t\t";
            }
            $js .= "\n\t\t\tjQuery(document).ready(function(){" . ($compact_edit == 2 ? "jQuery('#sortables_" . $field->id . "').find('.toggle_group_down').trigger('click');" : "") . ($compact_edit == 1 ? "jQuery('#sortables_" . $field->id . "').find('.toggle_group_up').trigger('click');" : "") . "});\n\t\t\t";
            if ($max_values) {
                FLEXI_J16GE ? JText::script("FLEXI_FIELD_MAX_ALLOWED_VALUES_REACHED", true) : fcjsJText::script("FLEXI_FIELD_MAX_ALLOWED_VALUES_REACHED", true);
            }
            $js .= "\n\t\t\tvar uniqueRowNum" . $field->id . "\t= " . $max_count . ";  // Unique row number incremented only\n\t\t\tvar rowCount" . $field->id . "\t= " . $max_count . ";      // Counts existing rows to be able to limit a max number of values\n\t\t\tvar maxValues" . $field->id . " = " . $max_values . ";\n\t\t\t";
            // Create function call for add/deleting Field values
            $addField_pattern = "\n\t\t\t\tvar fieldval_box = groupval_box.find('.fcfieldval_container__GRP_FID_');\n\t\t\t\tfieldval_box.find('.invalid').removeClass('invalid').attr('aria-invalid', 'false');\n\t\t\t\tvar newSubLabel = fieldval_box.prev('label.sub_label');\n\t\t\t\tvar newLabelFor = 'custom_%s_'+uniqueRowNum" . $field->id . ";\n\t\t\t\tnewSubLabel.attr('for', newLabelFor);\n\t\t\t\tnewSubLabel.attr('for_bck', newLabelFor);\n\t\t\t\tfcflabels[ newLabelFor ] = newSubLabel;\n\t\t\t\taddField_GRP_FID_(null, groupval_box, groupval_box.find('.fcfieldval_container__GRP_FID_'), add_params);";
            $delField_pattern = "\n\t\t\t\tif(rowCount" . $field->id . " == 1)\n\t\t\t\t{\n\t\t\t\t\t// We need to update the current grouped label of the field if this was the last element being re-added\n\t\t\t\t\tvar fieldval_box = groupval_box.find('.fcfieldval_container__GRP_FID_');\n\t\t\t\t\tfieldval_box.find('.invalid').removeClass('invalid').attr('aria-invalid', 'false');\n\t\t\t\t\tvar newSubLabel = fieldval_box.prev('label.sub_label');\n\t\t\t\t\tvar newLabelFor = 'custom_%s_'+uniqueRowNum" . $field->id . ";\n\t\t\t\t\tnewSubLabel.attr('for', newLabelFor);\n\t\t\t\t\tnewSubLabel.attr('for_bck', newLabelFor);\n\t\t\t\t\tfcflabels[ newLabelFor ] = newSubLabel;\n\t\t\t\t}\n\t\t\t\tdeleteField_GRP_FID_(null, groupval_box, groupval_box.find('.fcfieldval_container__GRP_FID_'));\n\t\t\t\t";
            $addField_funcs = $delField_funcs = '';
            foreach ($grouped_fields as $field_id => $grouped_field) {
                $addField_funcs .= str_replace("_GRP_FID_", $grouped_field->id, sprintf($addField_pattern, $grouped_field->name));
                $delField_funcs .= str_replace("_GRP_FID_", $grouped_field->id, sprintf($delField_pattern, $grouped_field->name));
            }
            $js .= "\n\t\t\tfunction addField" . $field->id . "(el, groupval_box, fieldval_box, params)\n\t\t\t{\n\t\t\t\tvar insert_before   = (typeof params!== 'undefined' && typeof params.insert_before   !== 'undefined') ? params.insert_before   : 0;\n\t\t\t\tvar remove_previous = (typeof params!== 'undefined' && typeof params.remove_previous !== 'undefined') ? params.remove_previous : 0;\n\t\t\t\tvar scroll_visible  = (typeof params!== 'undefined' && typeof params.scroll_visible  !== 'undefined') ? params.scroll_visible  : 1;\n\t\t\t\tvar animate_visible = (typeof params!== 'undefined' && typeof params.animate_visible !== 'undefined') ? params.animate_visible : 1;\n\t\t\t\t\n\t\t\t\tif((rowCount" . $field->id . " >= maxValues" . $field->id . ") && (maxValues" . $field->id . " != 0)) {\n\t\t\t\t\talert(Joomla.JText._('FLEXI_FIELD_MAX_ALLOWED_VALUES_REACHED') + maxValues" . $field->id . ");\n\t\t\t\t\treturn 'cancel';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Find last container of fields and clone it to create a new container of fields\n\t\t\t\tvar lastField = fieldval_box ? fieldval_box : jQuery(el).prev().children().last();\n\t\t\t\tvar newField  = lastField.clone();\n\t\t\t\t\n\t\t\t\t// Need to at least change FORM field names and HTML tag IDs before adding the container to the DOM\n\t\t\t\tvar theSet = newField.find('input, select');\n\t\t\t\tvar nr = 0;\n\t\t\t\ttheSet.each(function() {\n\t\t\t\t\tvar elem = jQuery(this);\n\t\t\t\t\telem.attr('name', '_duplicated_" . $field->id . "_'+uniqueRowNum" . $field->id . "+'_'+nr);\n\t\t\t\t\telem.attr('id', '_duplicated_" . $field->id . "_'+uniqueRowNum" . $field->id . "+'_'+nr);\n\t\t\t\t\tnr++;\n\t\t\t\t});\n\t\t\t\t";
            // Add new field to DOM
            $js .= "\n\t\t\t\tlastField ?\n\t\t\t\t\t(insert_before ? newField.insertBefore( lastField ) : newField.insertAfter( lastField ) ) :\n\t\t\t\t\tnewField.appendTo( jQuery('#sortables_" . $field->id . "') ) ;\n\t\t\t\t";
            // Add new element to sortable objects (if field not in group)
            if (!$use_ingroup) {
                $js .= "\n\t\t\t\tjQuery('#sortables_" . $field->id . "').sortable({\n\t\t\t\t\thandle: '.fcfield-drag-handle',\n\t\t\t\t\tcontainment: 'parent',\n\t\t\t\t\ttolerance: 'pointer'\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\t// Add new values for each field\n\t\t\t\tvar groupval_box = newField;\n\t\t\t\tvar add_params = {remove_previous: 1, scroll_visible: 0, animate_visible: 0};\n\t\t\t\t" . $addField_funcs . "\n\t\t\t\t";
            }
            // Readd prettyCheckable and remove previous if so requested
            $js .= "\n\t\t\t\tif (remove_previous) lastField.remove();\n\t\t\t\t";
            // Show new field, increment counters
            $js .= "\n\t\t\t\t//newField.fadeOut({ duration: 400, easing: 'swing' }).fadeIn({ duration: 200, easing: 'swing' });\n\t\t\t\tif (scroll_visible) fc_scrollIntoView(newField, 1);\n\t\t\t\tif (animate_visible) newField.css({opacity: 0.1}).animate({ opacity: 1 }, 800);\n\t\t\t\t\n\t\t\t\t// Enable tooltips on new element\n\t\t\t\tnewField.find('.hasTooltip').tooltip({'html': true,'container': newField});\n\t\t\t\t\n\t\t\t\trowCount" . $field->id . "++;       // incremented / decremented\n\t\t\t\tuniqueRowNum" . $field->id . "++;   // incremented only\n\t\t\t}\n\n\t\t\tfunction deleteField" . $field->id . "(el)\n\t\t\t{\n\t\t\t\tvar row = jQuery(el).closest('li');\n\t\t\t\t\n\t\t\t\t// Do cleanup by calling the deleteField of each individual field, these functions will re-add last element as empty if needed\n\t\t\t\tvar groupval_box = jQuery(el).closest('li');\n\t\t\t\t" . $delField_funcs . "\n\t\t\t\tif(rowCount" . $field->id . " == 1)\n\t\t\t\t{\n\t\t\t\t\tuniqueRowNum" . $field->id . "++;   // increment unique row id, since last group was re-added\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Also remove the group field values container if not last one\n\t\t\t\tif(rowCount" . $field->id . " > 1) {\n\t\t\t\t\t// Destroy the remove/add/etc buttons, so that they are not reclicked, while we do the hide effect (before DOM removal of field value)\n\t\t\t\t\trow.find('.fcfield-delvalue').remove();\n\t\t\t\t\trow.find('.fcfield-insertvalue').remove();\n\t\t\t\t\trow.find('.fcfield-drag-handle').remove();\n\t\t\t\t\t// Do hide effect then remove from DOM\n\t\t\t\t\trow.fadeOut(420, function(){ this.remove(); });\n\t\t\t\t\trowCount" . $field->id . "--;\n\t\t\t\t}\n\t\t\t}\n\t\t\t";
            $css .= '';
            $remove_button = '<span class="fcfield-delvalue" title="' . JText::_('FLEXI_REMOVE_VALUE') . '" onclick="deleteField' . $field->id . '(this);"></span>';
            $move2 = '<span class="fcfield-drag-handle" title="' . JText::_('FLEXI_CLICK_TO_DRAG') . '"></span>';
            $add_here = '';
            $add_here .= $add_position == 2 || $add_position == 3 ? '<span class="fcfield-insertvalue fc_before" onclick="addField' . $field->id . '(null, jQuery(this).closest(\'ul\'), jQuery(this).closest(\'li\'), {insert_before: 1});" title="' . JText::_('FLEXI_ADD_BEFORE') . '"></span> ' : '';
            $add_here .= $add_position == 1 || $add_position == 3 ? '<span class="fcfield-insertvalue fc_after"  onclick="addField' . $field->id . '(null, jQuery(this).closest(\'ul\'), jQuery(this).closest(\'li\'), {insert_before: 0});" title="' . JText::_('FLEXI_ADD_AFTER') . '"></span> ' : '';
            if ($compact_edit) {
                $add_here .= '
				<button class="toggle_group_down btn btn-small btn-success" style="' . ($compact_edit == 2 ? 'display:none;' : '') . ' min-width: 120px;" onclick="fc_toggle_box_via_btn(jQuery(this).closest(\'li\').find(\'.fcfieldval_container_outer:not(.fcAlwaysVisibleField)\'), this, \'\', jQuery(this).next(), 1); return false;">
					<i class="icon-downarrow"></i>' . JText::_('FLEXI_FIELD_GROUP_EDIT_DETAILS') . '
				</button>
				<button class="toggle_group_up   btn btn-small" style="' . ($compact_edit == 1 ? 'display:none;' : '') . ' min-width: 120px;" onclick="fc_toggle_box_via_btn(jQuery(this).closest(\'li\').find(\'.fcfieldval_container_outer:not(.fcAlwaysVisibleField)\'), this, \'\', jQuery(this).prev(), 0); return false;">
					<i class="icon-uparrow"></i>' . JText::_('FLEXI_FIELD_GROUP_HIDE_DETAILS') . '
				</button>
			';
            }
        } else {
            $remove_button = '';
            $move2 = '';
            $add_here = '';
            $js .= '';
            $css .= '';
        }
        if ($js) {
            $document->addScriptDeclaration($js);
        }
        if ($css) {
            $document->addStyleDeclaration($css);
        }
        $close_btn = FLEXI_J30GE ? '<a class="close" data-dismiss="alert">&#215;</a>' : '<a class="fc-close" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">&#215;</a>';
        $alert_box = FLEXI_J30GE ? '<div %s class="alert alert-%s %s">' . $close_btn . '%s</div>' : '<div %s class="fc-mssg fc-%s %s">' . $close_btn . '%s</div>';
        if ($compact_edit) {
            $compact_edit_excluded = $field->parameters->get('compact_edit_excluded', array());
            if (empty($compact_edit_excluded)) {
                $compact_edit_excluded = array();
            }
            if (!is_array($compact_edit_excluded)) {
                $compact_edit_excluded = preg_split("/[\\|,]/", $compact_edit_excluded);
            }
            $compact_edit_excluded = array_flip($compact_edit_excluded);
        }
        $field->html = array();
        for ($n = 0; $n < $max_count; $n++) {
            $field->html[$n] = '
				' . ($use_ingroup ? '' : $move2) . '
				' . ($use_ingroup ? '' : $remove_button) . '
				' . ($use_ingroup || !$add_position ? '' : $add_here) . '
				';
            // Append item-form display HTML of the every field in the group
            $i = 0;
            foreach ($grouped_fields as $field_id => $grouped_field) {
                $lbl_class = 'flexi label sub_label';
                $lbl_title = '';
                // field has tooltip
                $edithelp = $grouped_field->edithelp ? $grouped_field->edithelp : 1;
                if ($grouped_field->description && ($edithelp == 1 || $edithelp == 2)) {
                    $lbl_class .= ($edithelp == 2 ? ' fc_tooltip_icon ' : ' ') . $tooltip_class;
                    $lbl_title = flexicontent_html::getToolTip(trim($field->label, ':'), $grouped_field->description, 0, 1);
                }
                $field->html[$n] .= '<div class="fcclear"></div>
				<div class="fcfieldval_container_outer' . ($compact_edit && isset($compact_edit_excluded[$field_id]) ? ' fcAlwaysVisibleField' : '') . '">
					<label class="' . $lbl_class . '" title="' . $lbl_title . '" for="custom_' . $grouped_field->name . '_' . $n . '" for_bck="custom_' . $grouped_field->name . '_' . $n . '">' . $grouped_field->label . '</label>
					<div class="fcfieldval_container valuebox fcfieldval_container_' . $grouped_field->id . ' container_fcfield_name_' . $grouped_field->name . '" >
						' . ($grouped_field->description && $edithelp == 3 ? sprintf($alert_box, '', 'info', 'fc-nobgimage', $grouped_field->description) : '') . '
						' . @$grouped_field->html[$n] . '
					</div>
				</div>
				';
                $i++;
            }
            if (!$multiple) {
                break;
            }
            // multiple values disabled, break out of the loop, not adding further values even if the exist
        }
        // Non value HTML
        $non_value_html = '';
        foreach ($grouped_fields as $field_id => $grouped_field) {
            $non_value_html .= @$grouped_field->html[-1];
        }
        // Implode form HTML as a list
        $list_classes = "fcfield-sortables";
        $list_classes .= " fcfield-group";
        if (count($field->html)) {
            $field->html = '<li class="fcfieldval_container valuebox fcfieldval_container_' . $field->id . ' container_fcfield_name_' . $field->name . '">' . implode('</li><li class="fcfieldval_container valuebox fcfieldval_container_' . $field->id . ' container_fcfield_name_' . $field->name . '">', $field->html) . '</li>';
            $field->html = '<div id="sortables_outer_' . $field->id . '"><ul class="' . $list_classes . '" id="sortables_' . $field->id . '">' . $field->html . '</ul></div>';
        } else {
            $field->html = '';
        }
        if (!$add_position) {
            $field->html .= '<span class="fcfield-addvalue fccleared" onclick="addField' . $field->id . '(this);" title="' . JText::_('FLEXI_ADD_TO_BOTTOM') . '"></span>';
        }
        // Append non value html of fields
        $field->html = ($field->parameters->get('compact_edit_global', 0) ? '
			<div class="toggle_all_values_buttons_box">
				<span id="sortables_' . $field->id . '_btn" class="btn" onclick="fc_toggle_box_via_btn(jQuery(\'#sortables_outer_' . $field->id . '\'), this, \'\', jQuery(this).next(), 0); return false;">
					<i class="icon-uparrow"></i>' . JText::_('FLEXI_FIELD_GROUP_HIDE_VALUES') . '
				</span>
				<span id="sortables_' . $field->id . '_btn" class="btn btn-success" onclick="fc_toggle_box_via_btn(jQuery(\'#sortables_outer_' . $field->id . '\'), this, \'\', jQuery(this).prev(), 1); return false;" style="display:none;">
					<i class="icon-downarrow"></i>' . JText::_('FLEXI_FIELD_GROUP_SHOW_VALUES') . '
				</span>
			</div>
				' : '') . '
			' . $field->html . ($non_value_html ? '
				<div class="fcclear"></div>' . $non_value_html : '');
    }
Exemplo n.º 19
0
 /**
  * Method to remove an item
  *
  * @access	public
  * @return	boolean	True on success
  * @since	1.0
  */
 function delete($cid, &$itemmodel = null)
 {
     $dispatcher = JDispatcher::getInstance();
     // Get event dispatcher and load all content plugins for triggering their delete events
     JPluginHelper::importPlugin('content');
     // Load all content plugins for triggering their delete events
     $item_arr = array();
     // We need an array of items to use for calling the 'onContentAfterDelete' Event
     if (!count($cid)) {
         return false;
     }
     $cids = implode(',', $cid);
     if ($itemmodel) {
         foreach ($cid as $item_id) {
             $item = $itemmodel->getItem($item_id);
             // *****************************************************************
             // Trigger Event 'onContentBeforeDelete' of Joomla's Content plugins
             // *****************************************************************
             $event_before_delete = 'onContentBeforeDelete';
             // NOTE: $itemmodel->event_before_delete is protected property
             $dispatcher->trigger($event_before_delete, array('com_content.article', $item));
             $item_arr[] = clone $item;
             // store object so that we can call after delete event
             // **********************************************************************************
             // Trigger onBeforeDeleteField field event to allow fields to cleanup any custom data
             // **********************************************************************************
             $fields = $itemmodel->getExtrafields($force = true);
             foreach ($fields as $field) {
                 $field_type = $field->iscore ? 'core' : $field->field_type;
                 FLEXIUtilities::call_FC_Field_Func($field_type, 'onBeforeDeleteField', array(&$field, &$item));
             }
         }
     }
     // *********************************************
     // Retrieve J2.5 asset before deleting the items
     // *********************************************
     $query = 'SELECT asset_id FROM #__content' . ' WHERE id IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     $assetids = $this->_db->loadColumn();
     $assetidslist = implode(',', $assetids);
     // **********************
     // Remove basic item data
     // **********************
     $query = 'DELETE FROM #__content' . ' WHERE id IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // *************************
     // Remove extended item data
     // *************************
     $query = 'DELETE FROM #__flexicontent_items_ext' . ' WHERE item_id IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // **************************
     // Remove temporary item data
     // **************************
     $query = 'DELETE FROM #__flexicontent_items_tmp' . ' WHERE id IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // ******************************
     // Remove assigned tag references
     // ******************************
     $query = 'DELETE FROM #__flexicontent_tags_item_relations' . ' WHERE itemid IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // ***********************************
     // Remove assigned category references
     // ***********************************
     $query = 'DELETE FROM #__flexicontent_cats_item_relations' . ' WHERE itemid IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // ****************************************************************
     // Delete field data in flexicontent_fields_item_relations DB Table
     // ****************************************************************
     $query = 'DELETE FROM #__flexicontent_fields_item_relations' . ' WHERE item_id IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // **************************************************************************
     // Delete VERSIONED field data in flexicontent_fields_item_relations DB Table
     // **************************************************************************
     $query = 'DELETE FROM #__flexicontent_items_versions' . ' WHERE item_id IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // ****************************
     // Delete item version METADATA
     // ****************************
     $query = 'DELETE FROM #__flexicontent_versions' . ' WHERE item_id IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // **********************************
     // Delete favoured record of the item
     // **********************************
     $query = 'DELETE FROM #__flexicontent_favourites' . ' WHERE itemid IN (' . $cids . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // *****************************
     // Delete item asset/ACL records
     // *****************************
     $query = 'DELETE FROM #__assets' . ' WHERE id in (' . $assetidslist . ')';
     $this->_db->setQuery($query);
     if (!$this->_db->execute()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     // ****************************************************************
     // Trigger Event 'onContentAfterDelete' of Joomla's Content plugins
     // ****************************************************************
     $event_after_delete = 'onContentAfterDelete';
     // NOTE: $itemmodel->event_after_delete is protected property
     foreach ($item_arr as $item) {
         $dispatcher->trigger($event_after_delete, array('com_content.article', $item));
     }
     return true;
 }
Exemplo n.º 20
0
 /**
  * Method to creat the HTML of filters
  * 
  * @access public
  * @return object
  * @since 1.5
  */
 static function renderFilters(&$params, &$filters, $form_name)
 {
     // Make the filter compatible with Joomla standard cache
     $cache = JFactory::getCache('com_flexicontent');
     $cache->clean();
     $filter_prefix = ($form_name == 'item_form' ? 'iform_' : '') . 'filter_';
     $display_label_filter_override = (int) $params->get('show_filter_labels', 0);
     foreach ($filters as $filter_name => $filter) {
         $filtervalue = JRequest::getVar($filter_prefix . $filter->id, '', 'default');
         //print_r($filtervalue);
         // make sure filter HTML is cleared, and create it
         $display_label_filter_saved = $filter->parameters->get('display_label_filter');
         if ($display_label_filter_override) {
             $filter->parameters->set('display_label_filter', $display_label_filter_override);
         }
         // suppress labels inside filter's HTML (hide or show all labels externally)
         // else ... filter default label behavior
         $filter->html = '';
         // make sure filter HTML display is cleared
         $field_type = $filter->iscore ? 'core' : $filter->field_type;
         //$results 	= $dispatcher->trigger('onDisplayFilter', array( &$filter, $filtervalue ));
         FLEXIUtilities::call_FC_Field_Func($field_type, 'onDisplayFilter', array(&$filter, $filtervalue, $form_name));
         $filter->parameters->set('display_label_filter', $display_label_filter_saved);
     }
 }
Exemplo n.º 21
0
 function index()
 {
     $start_microtime = microtime(true);
     $session = JFactory::getSession();
     $db = JFactory::getDBO();
     @ob_end_clean();
     $indexer = JRequest::getVar('indexer', 'advanced');
     $rebuildmode = JRequest::getVar('rebuildmode', '');
     $items_per_call = JRequest::getVar('items_per_call', 20);
     // Number of item to index per HTTP request
     $itemcnt = JRequest::getVar('itemcnt', 0);
     // Counter of items indexed so far, this is given via HTTP request
     $itemsmodel = $this->getModel('items');
     // Get items model to call needed methods
     // TAKE CARE: this code depends on countrows() to set session variables
     // Retrieve fields, that are assigned as (advanced/basic) searchable/filterable
     if ($rebuildmode == 'quick' && $indexer == 'advanced') {
         $nse_fields = $session->get($indexer . '_nse_fields', array(), 'flexicontent');
         $nsp_fields = $session->get($indexer . '_nsp_fields', array(), 'flexicontent');
         $fields = $session->get($indexer . '_fields', array(), 'flexicontent');
         //echo 'fail|'; print_r(array_keys($fields)); exit;
         // Get the field ids of the fields removed from searching
         $del_fieldids = array_unique(array_merge(array_keys($nse_fields), array_keys($nsp_fields), array_keys($fields)));
     } else {
         $fields = $session->get($indexer . '_fields', array(), 'flexicontent');
         //echo 'fail|'; print_r(array_keys($fields)); exit;
     }
     // Get the field ids of the searchable fields
     $fieldids = array_keys($fields);
     // Get items ids that have value for any of the searchable fields, but use session to avoid recalculation
     $itemids = $session->get($indexer . '_items_to_index', array(), 'flexicontent');
     // For advanced search index Remove old search values from the DB
     if ($itemcnt == 0) {
         if ($indexer == 'advanced') {
             if ($rebuildmode != 'quick') {
                 $clear_query = "TRUNCATE TABLE #__flexicontent_advsearch_index";
             } else {
                 if (count($del_fieldids)) {
                     $del_fieldids_list = implode(',', $del_fieldids);
                     $clear_query = "DELETE FROM #__flexicontent_advsearch_index " . " WHERE field_id IN (" . $del_fieldids_list . ")";
                 }
             }
         } else {
             // INDEX: basic
             if (!count($fields)) {
                 // (all items) Clear basic index records no fields marked as text searchable
                 $clear_query = "UPDATE #__flexicontent_items_ext SET search_index = '' ";
             }
         }
         if (!empty($clear_query)) {
             $db->setQuery($clear_query);
             $db->query();
         }
     }
     $items_per_query = 50;
     $items_per_query = $items_per_query > $items_per_call ? $items_per_call : $items_per_query;
     $cnt = $itemcnt;
     while ($cnt < $itemcnt + $items_per_call) {
         $query_itemids = array_slice($itemids, $cnt, $items_per_query);
         $cnt += $items_per_query;
         // Item is not needed, later and only if field uses item replacements then it will be loaded
         $item = null;
         $lang_query = "SELECT id, language" . " FROM #__content AS i " . (!FLEXI_J16GE ? " LEFT JOIN #__flexicontent_items_ext AS ie ON i.id=ie.item_id" : "") . " WHERE id IN (" . implode(', ', $query_itemids) . ")";
         $db->setQuery($lang_query);
         $items_data = $db->loadObjectList('id');
         if ($indexer == 'basic') {
             $searchindex = array();
             // Add all query itemids to searchindex array so that it will be cleared even if zero fields are indexed
             foreach ($query_itemids as $query_itemid) {
                 $searchindex[$query_itemid] = array();
             }
         } else {
             // This will hold the SQL inserting new advanced search records for multiple item/values
             $ai_query_vals = array();
         }
         // For current item: Loop though all searchable fields according to their type
         foreach ($fieldids as $fieldid) {
             // Clone field to avoid problems
             $field = clone $fields[$fieldid];
             // Indicate multiple items per query
             $field->item_id = 0;
             $field->query_itemids = $query_itemids;
             $field->items_data = $items_data;
             // Indicate that the indexing fuction should retrieve the values
             $values = null;
             // Add values to advanced search index
             $fieldname = $field->iscore ? 'core' : $field->field_type;
             if ($indexer == 'advanced') {
                 FLEXIUtilities::call_FC_Field_Func($fieldname, 'onIndexAdvSearch', array(&$field, &$values, &$item));
                 //print_r($field->ai_query_vals);
                 if (isset($field->ai_query_vals)) {
                     foreach ($field->ai_query_vals as $query_val) {
                         $ai_query_vals[] = $query_val;
                     }
                 }
                 //else echo "Not set for : ". $field->name;
             } else {
                 if ($indexer == 'basic') {
                     FLEXIUtilities::call_FC_Field_Func($fieldname, 'onIndexSearch', array(&$field, &$values, &$item));
                     foreach ($query_itemids as $query_itemid) {
                         if (@$field->search[$query_itemid]) {
                             $searchindex[$query_itemid][] = $field->search[$query_itemid];
                         }
                     }
                 }
             }
         }
         // Create query that will update/insert data into the DB
         unset($query);
         // make sure it is not set above
         if ($indexer == 'basic') {
             if (count($searchindex)) {
                 // check for zero search index records
                 $query = "UPDATE #__flexicontent_items_ext SET search_index = CASE item_id ";
                 foreach ($searchindex as $query_itemid => $search_text) {
                     // Add new search value into the DB
                     $query .= " WHEN {$query_itemid} THEN " . $db->Quote(implode(' | ', $search_text));
                 }
                 $query .= " END ";
                 $query .= " WHERE item_id IN (" . implode(',', array_keys($searchindex)) . ")";
             }
         } else {
             if (count($ai_query_vals)) {
                 // check for zero search index records
                 $query = "INSERT INTO #__flexicontent_advsearch_index " . " (field_id,item_id,extraid,search_index,value_id) VALUES " . implode(",", $ai_query_vals);
             }
         }
         if (!empty($query)) {
             $db->setQuery($query);
             $db->query();
             if ($db->getErrorNum()) {
                 echo $db->getErrorMsg();
             }
         }
     }
     // Check if items have finished, otherwise continue with -next- group of item ids
     if ($cnt >= count($itemids)) {
         // Reset dirty SEARCH properties of published fields to be: normal ON/OFF
         $set_clause = ' SET' . ($indexer == 'basic' ? ' issearch = CASE issearch WHEN 2 THEN 1   WHEN -1 THEN 0   ELSE issearch   END' : ' isadvsearch = CASE isadvsearch WHEN 2 THEN 1   WHEN -1 THEN 0   ELSE isadvsearch   END,' . ' isadvfilter = CASE isadvfilter WHEN 2 THEN 1   WHEN -1 THEN 0   ELSE isadvfilter   END');
         $query = 'UPDATE #__flexicontent_fields' . $set_clause . " WHERE published=1";
         $db->setQuery($query);
         $db->query();
         // Force SEARCH properties of unpublished fields to be: normal OFF
         if ($indexer == 'basic') {
             $query = 'UPDATE #__flexicontent_fields SET issearch = 0 WHERE published=0';
             $db->setQuery($query);
             $db->query();
         } else {
             $query = 'UPDATE #__flexicontent_fields SET isadvsearch = 0, isadvfilter = 0  WHERE published=0';
             $db->setQuery($query);
             $db->query();
         }
     }
     if (!count($fieldids)) {
         echo 'fail|Index was only cleaned-up, since no field(s) were marked as: ' . '<br> -- ' . ($indexer == 'basic' ? 'Text Searchable (CONTENT LISTS)' : 'Text Searchable OR filterable (SEARCH VIEW)');
         exit;
     }
     if (!count($itemids)) {
         echo 'fail|Index was only cleaned-up, since no items were found to have value for fields marked as: ' . '<br> -- ' . ($indexer == 'basic' ? 'Text Searchable (CONTENT LISTS)' : 'Text Searchable OR filterable (SEARCH VIEW)');
         exit;
     }
     $elapsed_microseconds = round(1000000 * 10 * (microtime(true) - $start_microtime)) / 10;
     if ($session->has($indexer . '_total_runtime', 'flexicontent')) {
         $_total_runtime = $session->get($indexer . '_total_runtime', 0, 'flexicontent');
     } else {
         $_total_runtime = 0;
     }
     $_total_runtime += $elapsed_microseconds;
     $session->set($indexer . '_total_runtime', $_total_runtime, 'flexicontent');
     echo sprintf(' [%.2f secs] ', $_total_runtime / 1000000);
     exit;
 }