/components/com_fabrik/models/list.php
PHP | 6768 lines | 4793 code | 620 blank | 1355 comment | 1060 complexity | 1abb393149b25aa8800bebd08992558f MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * @package Joomla
- * @subpackage Fabrik
- * @copyright Copyright (C) 2005 Rob Clayburn. All rights reserved.
- * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
- */
- // Check to ensure this file is included in Joomla!
- defined('_JEXEC') or die();
- jimport('joomla.application.component.modelform');
- require_once(COM_FABRIK_FRONTEND.DS.'helpers'.DS.'pagination.php');
- require_once(COM_FABRIK_FRONTEND.DS.'helpers'.DS.'string.php');
- require_once(COM_FABRIK_FRONTEND.DS.'helpers'.DS.'joomfish.php');
- class FabrikFEModelList extends JModelForm {
- /** @var int id of table to load */
- public $id = null;
- /** @var int package id */
- public $packageId = null;
- /** @var object the tables connection object */
- protected $_oConn = null;
- /** @var object table Table */
- protected $_table = null;
- /** @var object table's form model */
- protected $_oForm = null;
- /** @var array joins */
- protected $_aJoins = null;
- /** @var array column calculations */
- protected $_aRunCalculations = array();
- /** @var string table output format - set to rss to collect correct element data within function gettData()*/
- protected $_outPutFormat = 'html';
- protected $isMambot = false;
- /** @var object to contain access rights **/
- protected $_access = null;
- /** @var int the id of the last inserted record (or if updated the last record updated) **/
- public $lastInsertId = null;
- /** @var array store data to create joined records from */
- protected $_joinsToProcess = null;
- /** @var array database fields */
- protected $_dbFields = null;
- /** @var bol force reload table calculations **/
- protected $_reloadCalculations = false;
- /** @var array data contains request data **/
- protected $_aData = null;
- /**
- * @since 3.0 replaces _postMethod
- * @var bool is ajax used */
- protected $ajax = null;
- /** @var object plugin manager */
- protected $_pluginManager = null;
- /** @var string join sql **/
- protected $_joinsSQL = null;
- /** @var array order by column names **/
- var $orderByFields = null;
- /** @var bol is the object inside a package? */
- //var $_inPackage = false;
- protected $_joinsToThisKey = null;
- protected $_real_filter_action = null;
- /** array merged request and session data used to potentially filter the table **/
- protected $_request = null;
- protected $_aRow = null;
- /** array rows to delete **/
- protected $_rowsToDelete = null;
- /** @var array original table data BEFORE form saved - used to ensure uneditable data is stored */
- protected $_origData = null;
- /** @var bol set to true to load records STARTING from a random id (used in the getPageNav func) **/
- public $randomRecords = false;
- protected $_data = null;
- var $nav = null;
- var $fields = null;
- var $prefilters = null;
- var $filters = null;
- var $aJoinsToThisKey = null;
- var $canSelectRows = null;
- var $asfields = null;
- var $_temp_db_key_addded = false;
- var $_group_by_added = false;
- var $_pluginQueryWhere = array();
- var $_pluginQueryGroupBy = array();
- /** @var bol is the table a view **/
- var $_isview = null;
- /** @var array index objects **/
- var $_indexes = null;
- /** @var array previously submitted advanced search data */
- var $advancedSearchRows = null;
- /** @var string table action url */
- var $tableAction = null;
- /** @var bool doing CSV import */
- var $_importingCSV = false;
- var $encrypt = array();
- /** @var int which record to start showing from */
- var $limitStart = null;
- /** @var int # records to show */
- var $limitLength = null;
- protected $rows = null;
- /** @var bool should a heading be added for action buttons (returns true if at least one row has buttons)*/
- protected $actionHeading = false;
- /**
- * Constructor
- *
- * @since 1.5
- */
- public function getForm($data = array(), $loadData = true)
- {
- // Get the form.
- $form = $this->loadForm('com_fabrik.list', 'view', array('control' => 'jform', 'load_data' => $loadData));
- if (empty($form)) {
- return false;
- }
- return $form;
- }
- function __construct()
- {
- parent::__construct();
- $usersConfig = JComponentHelper::getParams('com_fabrik');
- $id = JRequest::getInt('listid', $usersConfig->get('listid'));
- $this->packageId = (int)JRequest::getInt('packageid', $usersConfig->get('packageid'));
- $this->setId($id);
- $this->_access = new stdClass();
- }
- /**
- * process the table plug-ins
- * @return array of table plug-in result messages
- */
- function processPlugin()
- {
- $pluginManager =& $this->getPluginManager();
- $pluginManager->runPlugins('process', $this, 'list');
- return $pluginManager->_data;
- }
- /**
- * get the html that is outputted by table plug-in buttons
- *
- * @return array buttons
- */
- function getPluginButtons()
- {
- $pluginManager =& $this->getPluginManager();
- $pluginManager->getPlugInGroup('list');
- $pluginManager->runPlugins('button', $this, 'list');
- $buttons = $pluginManager->_data;
- $this->getPluginJsClasses();
- return $buttons;
- }
- function getPluginJsClasses()
- {
- $pluginManager =& $this->getPluginManager();
- $pluginManager->getPlugInGroup('list');
- $pluginManager->runPlugins('loadJavascriptClass', $this, 'list');
- }
- function getPluginJsObjects($container = null)
- {
- if (is_null($container)) {
- $container = "listform_".$this->getId();
- }
- $pluginManager =& $this->getPluginManager();
- $pluginManager->getPlugInGroup('list');
- $pluginManager->runPlugins('loadJavascriptInstance', $this, 'list', $container);
- return $pluginManager->_data;
- }
- /**
- * main query to build table
- *
- */
- function render()
- {
- FabrikHelperHTML::debug($_POST, 'render:post');
- global $_PROFILER;
- $id = $this->getId();
- if (is_null($id) || $id == '0') {
- return JError::raiseError(500, JText::_('COM_FABRIK_INCORRECT_LIST_ID'));
- }
- $this->_outPutFormat = JRequest::getVar('format', 'html');
- if ($this->_outPutFormat == 'fabrikfeed') {
- $this->_outPutFormat = 'feed';
- }
- $item =& $this->getTable();
- if ($item->db_table_name == '') {
- return JError::raiseError(500, JText::_('COM_FABRIK_INCORRECT_LIST_ID'));
- }
- //cant set time limit in safe mode so suppress warning
- @set_time_limit(60);
- //$this->getRequestData();
- JDEBUG ? $_PROFILER->mark('About to get table filter') : null;
- $filters =& $this->getFilterArray();
- JDEBUG ? $_PROFILER->mark('Got filters') : null;
- $this->setLimits();
- $this->setElementTmpl();
- $this->getData();
- JDEBUG ? $_PROFILER->mark('got data') : null;
- //think we really have to do these as the calc isnt updated when the table is filtered
- $this->doCalculations();
- JDEBUG ? $_PROFILER->mark('done calcs') : null;
- $this->getCalculations();
- JDEBUG ? $_PROFILER->mark('got cacls') : null;
- $item->hit();
- }
- /**
- * set the navigation limit and limitstart
- */
- function setLimits()
- {
- $app = JFactory::getApplication();
- $item = $this->getTable();
- $params = $this->getParams();
- $id = $this->getId();
- // $$$ rob dont make the key list.X as the registry doesnt seem to like keys with just '1' a
- $context = 'com_fabrik.list'.$id.'.';
- $limitStart = $this->randomRecords ? $this->getRandomLimitStart() : 0;
- // deal with the fact that you can have more than one table on a page so limitstart has to be
- // specfic per table
- //if table is rendered as a content plugin dont set the limits in the session
- if ($app->scope == 'com_content') {
- $limitLength = JRequest::getInt('limit'.$id, $item->rows_per_page);
- if (!$this->randomRecords) {
- $limitStart = JRequest::getInt('limitstart'.$id, $limitStart);
- }
- } else {
- $limitLength = $app->getUserStateFromRequest($context.'limitlength', 'limit'.$id, $item->rows_per_page);
- if (!$this->randomRecords) {
- $limitStart = $app->getUserStateFromRequest($context.'limitstart', 'limitstart'.$id, $limitStart, 'int');
- }
- }
- if ($this->_outPutFormat == 'feed') {
- $limitLength = JRequest::getVar('limit', $params->get('rsslimit',150));
- $maxLimit = $params->get('rsslimitmax', 2500);
- if ($limitLength > $maxLimit) {
- $limitLength = $maxLimit;
- }
- }
- $this->limitLength = $limitLength;
- $this->limitStart = $limitStart;
- }
- /**
- * this merges session data for the fromForm with any request data
- * allowing us to filter data results from both search forms and filters
- *
- * @return array
- */
- function getRequestData()
- {
- global $_PROFILER;
- JDEBUG ? $_PROFILER->mark('start get Request data') : null; // 0.5 sec here!
- $f = $this->getFilterModel()->getFilters();
- JDEBUG ? $_PROFILER->mark('end get Request data') : null;
- return $f;
- }
- /**
- * get the table's filter model
- * @return model filter model
- */
- function &getFilterModel()
- {
- if (!isset($this->filterModel)) {
- $this->filterModel = JModel::getInstance('Listfilter', 'FabrikFEModel');
- $this->filterModel->setListModel($this);
- }
- return $this->filterModel;
- }
- /**
- * $$$ hugh - once we have a few table joins, our select statements are
- * getting big enough to hit default select length max in MySQL. Added per-table
- * setting to enable_big_selects, 3/16/2010.
- */
- function setBigSelects()
- {
- $fabrikDb = $this->getDb();
- $params =& $this->getParams();
- if ($params->get('enable_big_selects', 0)) {
- $fabrikDb->setQuery("SET OPTION SQL_BIG_SELECTS=1");
- $fabrikDb->query();
- }
- }
- /**
- * get the table's data
- *
- * @return array of objects (rows)
- */
- function getData()
- {
- global $_PROFILER;
- $pluginManager =& $this->getPluginManager();
- $fbConfig =& JComponentHelper::getParams('com_fabrik');
- $pluginManager->runPlugins('onPreLoadData', $this, 'list');
- if (isset($this->_data) && !is_null($this->_data)) {
- return $this->_data;
- }
- $traceModel = ini_get('mysql.trace_mode');
- ini_set('mysql.trace_mode', 'off'); // needs to be off for FOUND_ROWS() to work
- $fabrikDb =& $this->getDb();
- JDEBUG ? $_PROFILER->mark('query build start') : null;
- $query = $this->_buildQuery();
- JDEBUG ? $_PROFILER->mark('query build end') : null;
- $this->setBigSelects();
- // $$$ rob - if merging joined data then we don't want to limit
- // the query as we have already done so in _buildQuery()
- if ($this->mergeJoinedData()) {
- $fabrikDb->setQuery($query);
- } else {
- $fabrikDb->setQuery($query, $this->limitStart, $this->limitLength);
- }
- FabrikHelperHTML::debug($fabrikDb->getQuery(), 'list GetData:' . $this->getTable()->label);
- JDEBUG ? $_PROFILER->mark('before query run') : null;
- //set 2nd param to false in attempt to stop joomfish db adaptor from translating the orignal query
- // fabrik3 - 2nd param in j16 is now used - guessing that joomfish now uses the third param for the false switch?
- $this->_data = $fabrikDb->loadObjectList('', 'stdClass', false);
- if ($fabrikDb->getErrorNum() != 0) {
- jexit('getData:' . $fabrikDb->getErrorMsg());
- }
- /// $$$ rob better way of getting total records
- if ($this->mergeJoinedData()) {
- $this->totalRecords = $this->getTotalRecords();
- } else {
- $fabrikDb->setQuery("SELECT FOUND_ROWS()");
- $this->totalRecords = $fabrikDb->loadResult();
- }
- if ($this->randomRecords) {
- shuffle($this->_data);
- }
- ini_set('mysql.trace_mode', $traceModel);
- $nav =& $this->getPagination($this->totalRecords, $this->limitStart, $this->limitLength);
- JDEBUG ? $_PROFILER->mark('query run and data loaded') : null;
- //@TODO test in J1.7
- // $this->translateData($this->_data);
- if ($fabrikDb->getErrorNum() != 0) {
- JError::raiseNotice(500, 'getData: ' . $fabrikDb->getErrorMsg());
- }
- JDEBUG ? $_PROFILER->mark('start format data') : null;
- $this->formatData($this->_data);
- JDEBUG ? $_PROFILER->mark('start format for joins') : null;
- $this->formatForJoins($this->_data);
- JDEBUG ? $_PROFILER->mark('data formatted') : null;
- $pluginManager->runPlugins('onLoadData', $this, 'list');
- return $this->_data;
- }
- function translateData(&$data)
- {
- $params =& $this->getParams();
- if (!JPluginHelper::isEnabled('system', 'jfdatabase')) {
- return;
- }
- if (defined('JOOMFISH_PATH') && $params->get('allow-data-translation')) {
- $table = $this->getTable();
- $db = FabrikWorker::getDbo();
- $jf =& JoomFishManager::getInstance();
- $config = JFactory::getConfig();
- $tableName = str_replace($config->getValue('dbprefix'), '', $table->db_table_name);
- $contentElement =& $jf->getContentElement($tableName);
- if (!is_object($contentElement)) {
- return;
- }
- $title = Fabrikstring::shortColName($params->get('joomfish-title'));
- $activelangs = $jf->getActiveLanguages();
- $registry = JFactory::getConfig();
- $langid = $activelangs[$registry->getValue("config.jflang")]->id;
- $db->setQuery($contentElement->createContentSQL($langid));
- if ($title == '') {
- $contentTable = $contentElement->getTable();
- foreach ($contentTable->Fields as $tableField) {
- if ($tableField->Type == 'titletext') {
- $title = $tableField->Name;
- }
- }
- }
- $longKey = FabrikString::safeColNameToArrayKey($table->db_primary_key);
- $res =& $db->loadObjectList(FabrikString::shortColName($table->db_primary_key));
- // $$$ hugh - if no JF results, bail out, otherwise we pitch warnings in the foreach loop.
- if (empty($res)) {
- return;
- }
- foreach ($data as &$row) {
- //$$$ rob if the id isnt published fall back to __pk_val
- $translateRow = array_key_exists($longKey, $row) ? $res[$row->$longKey] : $res[$row->__pk_val];
- foreach ($row as $key => $val) {
- $shortkey = array_pop(explode("___", $key));
- if ($shortkey === $title) {
- $row->$key = $translateRow->titleTranslation;
- $key = $key ."_raw";
- $row->$key = $translateRow->titleTranslation;
- } else {
- if (array_key_exists($shortkey, $translateRow)) {
- $row->$key = $translateRow->$shortkey;
- $key = $key ."_raw";
- if (array_key_exists($key, $row)) {
- $row->$key = $translateRow->$shortkey;
- }
- }
- }
- }
- }
- }
- }
- /**
- * run the table data through element filters
- *
- * @param array $data
- */
- function formatData(&$data)
- {
- global $_PROFILER;
- jimport('joomla.filesystem.file');
- $form =& $this->getFormModel();
- $tableParams =& $this->getParams();
- $table =& $this->getTable();
- $pluginManager =& $this->getPluginManager();
- $method = 'renderListData_' . $this->_outPutFormat;
- $this->_aLinkElements = array();
- // $$$ hugh - temp foreach fix
- $groups = $form->getGroupsHiarachy();
- $ec = count($data);
- foreach ($groups as $groupModel) {
- //$$$ rob pointless getting elemetsnnot shown in the table view?
- // $$$ hugh - oops, they might be using elements in group-by template not shown in table
- // http://fabrikar.com/forums/showthread.php?p=102600#post102600
- // $$$ rob in that case lets test that rather than loading blindly
- // $$$ rob 15/02/2011 or out put may be csv in which we want to format any fields not shown in the form
- if (($tableParams->get('group_by_template') !== '' && $this->getGroupBy() != '') || $this->_outPutFormat == 'csv' || $this->_outPutFormat == 'feed') {
- $elementModels =& $groupModel->getPublishedElements();
- } else {
- $elementModels =& $groupModel->getPublishedTableElements();
- }
- foreach ($elementModels as $elementModel) {
- $e =& $elementModel->getElement();
- $elementModel->setContext($groupModel, $form, $this);
- $params =& $elementModel->getParams();
- $col = $elementModel->getFullName(false, true, false);
- //check if there is a custom out put handler for the tables format
- // currently supports "renderListData_csv", "renderListData_rss", "renderListData_html", "renderListData_json"
- if (!empty($data) && array_key_exists($col, $data[0])) {
- if (method_exists($elementModel, $method)) {
- for ($i=0; $i<count($data); $i++) {
- $thisRow = $data[$i];
- $coldata = $thisRow->$col;
- $data[$i]->$col = $elementModel->$method($coldata, $col, $thisRow);
- }
- } else {
- JDEBUG ? $_PROFILER->mark('elements renderListData: ' ."($ec)". " talbeid = $table->id " . $col) : null;
- for ($i=0; $i < $ec; $i++) {
- $thisRow = $data[$i];
- $coldata = $thisRow->$col;
- $data[$i]->$col = $elementModel->renderListData($coldata, $thisRow);
- $rawCol = $col . "_raw";
- // Not sure if this works, as far as I can tell _raw will always exist, even if
- // the element model hasn't explicitly done anything with it (except mayeb unsetting it?)
- // For instance, the calc element needs to set _raw. For now, I changed $thisRow above to
- // be a =& reference to $data[$i], and in renderListData() the calc element modifies
- // the _raw entry in $thisRow. I guess it could simply unset the _raw in $thisRow and
- // then implement a renderRawTableData. Anyway, just sayin'.
- if (!array_key_exists($rawCol, $thisRow)) {
- $data[$i]->$rawCol = $elementModel->renderRawTableData($coldata, $thisRow);
- }
- }
- }
- }
- }
- }
- JDEBUG ? $_PROFILER->mark('elements rendered for table data') : null;
- $this->_aGroupInfo = array();
- $groupTitle = array();
- $this->grouptemplates = array();
- //check if the data has a group by applied to it
- $groupBy = $this->getGroupBy();
- if ($groupBy != '' && $this->_outPutFormat != 'csv') {
- $w = new FabrikWorker();
- // 3.0 if not group by template spec'd byt group by assigned in qs then use that as the group by tmpl
- $requestGroupBy = JRequest::getCmd('group_by');
- if ($requestGroupBy == '') {
- $groupTemplate = $tableParams->get('group_by_template');
- } else {
- $groupTemplate = '{'.$requestGroupBy.'}';
- }
- $groupedData = array();
- $thisGroupedData = array();
- $groupBy = FabrikString::safeColNameToArrayKey($groupBy);
- // $$$ rob commenting this out as if you group on a date then the group by value doesnt correspond
- // to the keys found in the calculation array
- //see if we can use a raw value instead
- /*if (!empty($data) && array_key_exists($groupBy . "_raw", $data[0])) {
- $groupBy = $groupBy . "_raw";
- }*/
- $groupTitle = null;
- $aGroupTitles = array();
- $groupId = 0;
- for ($i=0; $i <count($data); $i++) {
- if (!in_array($data[$i]->$groupBy , $aGroupTitles)) {
- $aGroupTitles[] = $data[$i]->$groupBy;
- $grouptemplate = $w->parseMessageForPlaceHolder($groupTemplate, JArrayHelper::fromObject($data[$i]));
- $this->grouptemplates[$data[$i]->$groupBy] = nl2br($grouptemplate);
- $groupedData[$data[$i]->$groupBy] = array();
- }
- $data[$i]->_groupId = $data[$i]->$groupBy;
- $gKey = $data[$i]->$groupBy;
- // if the group_by was added in in getAsFields remove it from the returned data set (to avoid mess in package view)
- if ($this->_group_by_added) {
- unset($data[$i]->$groupBy);
- }
- if ($this->_temp_db_key_addded) {
- $k = $table->db_primary_key;
- }
- $groupedData[$gKey][] = $data[$i];
- }
- $data = $groupedData;
- } else {
- for ($i=0; $i<count($data); $i++) {
- if ($this->_temp_db_key_addded) {
- $k = $table->db_primary_key;
- }
- }
- //make sure that the none grouped data is in the same format
- $data = array($data);
- }
- JDEBUG ? $_PROFILER->mark('table groupd by applied') : null;
- if ($this->_outPutFormat != 'pdf' && $this->_outPutFormat != 'csv' && $this->_outPutFormat != 'feed') {
- $this->addSelectBoxAndLinks($data);
- FabrikHelperHTML::debug($data, 'table:data');
- }
- JDEBUG ? $_PROFILER->mark('end format data') : null;
- }
- /**
- * add the select box and various links into the data array
- * @param array table row objects
- */
- function addSelectBoxAndLinks(&$data)
- {
- $item = $this->getTable();
- $app = JFactory::getApplication();
- $db = FabrikWorker::getDbo(true);
- $params = $this->getParams();
- $nextview = ($this->canEdit()) ? "form" : "details";
- $tmpKey = '__pk_val';
- $factedlinks = $params->get('factedlinks');
- //get a list of fabrik tables and ids for view table and form links
- $linksToForms = $this->getLinksToThisKey();
- $action = $app->isAdmin() ? "task" : "view";
- $sql = "SELECT id, label, db_table_name FROM #__{package}_lists";
- $db->setQuery($sql);
- $aTableNames = $db->loadObjectList('label');
- if ($db->getErrorNum()) {
- JError::raiseError(500, $db->getErrorMsg());
- }
- $cx = count($data);
- $viewLinkAdded = false;
- //get pk values
- $pks = array();
- foreach ($data as $groupKey=>$group) {
- $cg = count($group);
- for ($i=0; $i < $cg; $i++) {
- $pks[] = @$data[$groupKey][$i]->$tmpKey;
- }
- }
- $joins =& $this->getJoins();
- //for ($x=0; $x<$cx; $x++) { //if grouped data then the key is not numeric
- foreach ($data as $groupKey=>$group) {
- //$group =& $data[$key]; //Messed up in php 5.1 group positioning in data became ambiguous
- $cg = count($group);
- for ($i=0; $i < $cg; $i++) {
- $row =& $data[$groupKey][$i];
- $viewLinkAdded = false;
- //done each row as its result can change
- $canEdit = $this->canEdit($row);
- $canView = $this->canView($row);
- $canDelete = $this->canDelete($row);
- $nextview = $canEdit ? "form" : "details";
- $pKeyVal = array_key_exists($tmpKey, $row) ? $row->$tmpKey : '';
- $pkcheck = '<div style="display:none">';
- foreach ($joins as $join) {
- if ($join->list_id !== '0') {
- // $$$ rob 22/02/2011 was not using _raw before which was intserting html into the value for image elements
- $fkey = $join->table_join_alias.'___'.$join->table_key."_raw";
- if (isset($row->$fkey)) {
- $fKeyVal= $row->$fkey;
- $pkcheck .= '<input type="checkbox" class="fabrik_joinedkey" value="'.$fKeyVal.'" name="'.$join->table_join_alias.'['.$row->__pk_val.']" />'."\n";
- }
- }
- }
- $pkcheck .= '</div>';
- $row->fabrik_select = $this->canSelectRow($row) ? '<input type="checkbox" id="id_'.$row->__pk_val.'" name="ids['.$row->__pk_val.']" value="'.$pKeyVal.'" />'.$pkcheck : '';
- //add in some default links if no element choosen to be a link
- $link = $this->viewDetailsLink($data[$groupKey][$i]);//dont use $row as it generates a pas by ref error
- $edit_link = $this->editLink($data[$groupKey][$i]);
- $row->fabrik_view_url = $link;
- $row->fabrik_edit_url = $edit_link;
- $editLinkAttribs = $this->getCustomLink('attribs', 'edit');
- $detailsLinkAttribs = $this->getCustomLink('attribs', 'details');
- $row->fabrik_view = '';
- $row->fabrik_edit = '';
- $editLabel = $params->get('editlabel', JText::_('COM_FABRIK_EDIT'));
- $editLink = "<a class=\"fabrik__rowlink\" $editLinkAttribs href=\"$edit_link\" title=\"$editLabel\">".
- FabrikHelperHTML::image('edit.png', 'list', '', $editLabel).
- '<span>'.$editLabel.'</span></a>';
- $viewLabel = $params->get('detaillabel', JText::_('COM_FABRIK_VIEW'));
- $viewLink = "<a class=\"fabrik___rowlink\" $detailsLinkAttribs href=\"$link\" title=\"$viewLabel\">".
- FabrikHelperHTML::image('view.png', 'list', '', $viewLabel).
- '<span>'.$viewLabel.'</span></a>';
- //3.0 actions now in list in one cell
- $row->fabrik_actions = array();
- if ($canView || $canEdit) {
- if ($canEdit == 1) {
- if ($params->get('editlink')) {
- $row->fabrik_edit = $editLink;
- $row->fabrik_actions['fabrik_edit'] = '<li class="fabrik_edit">'.$row->fabrik_edit.'</li>';
- }
- $row->fabrik_edit_url = $edit_link;
- if ($this->canViewDetails() && $params->get('detaillink') == 1) {
- $row->fabrik_view = $viewLink;
- $row->fabrik_actions['fabrik_view'] = '<li class="fabrik_view">'.$row->fabrik_view.'</li>';
- }
- } else {
- if ($this->canViewDetails() && $params->get('detaillink') == '1') {
- if (empty($this->_aLinkElements)) {
- $viewLinkAdded = true;
- $row->fabrik_view = $viewLink;
- $row->fabrik_actions['fabrik_view'] = '<li class="fabrik_view">'.$row->fabrik_view.'</li>';
- }
- } else {
- $row->fabrik_edit = '';
- }
- }
- }
- if ($this->canViewDetails() && !$viewLinkAdded && $params->get('detaillink') == '1') {
- $link = $this->viewDetailsLink($row, 'details');
- $row->fabrik_view_url = $link;
- $row->fabrik_view = $viewLink;
- $row->fabrik_actions['fabrik_view'] = '<li class="fabrik_view">'.$row->fabrik_view.'</li>';
- }
- if ($this->deletePossible()) {
- $row->fabrik_actions['fabrik_delete'] = $this->deleteButton();
- }
- // create columns containing links which point to tables associated with this table
- $joinsToThisKey = $this->getJoinsToThisKey();
- $f = 0;
- $keys = isset($factedlinks->linkedlist) ? array_keys(JArrayHelper::fromObject($factedlinks->linkedlist)) : array();
- for ($ii=0; $ii <count($joinsToThisKey); $ii++) {
- if (!array_key_exists($f, $keys)) {
- continue;
- }
- $join = $joinsToThisKey[$ii];
- $linkedTable = $factedlinks->linkedlist->$keys[$f];
- $popupLink = $factedlinks->linkedlist_linktype->$keys[$f];
- $linkedListText = $factedlinks->linkedlisttext->$keys[$f];
- if ($linkedTable != '0') {
- $recordKey = $join->element_id."___".$linkedTable;
- $key = $recordKey."_list_heading";
- $val = $pKeyVal;
- $recordCounts =& $this->getRecordCounts($join, $pks);
- $count = 0;
- $linkKey = '';
- if (is_array($recordCounts)) {
- if (array_key_exists($val, $recordCounts)) {
- $count = $recordCounts[$val]->total;
- $linkKey = $recordCounts[$val]->linkKey;
- } else {
- if (array_key_exists((int)$val, $recordCounts) && (int)$val !== 0) {
- $count = $recordCounts[(int)$val]->total;
- $linkKey = $recordCounts[$val]->linkKey;
- }
- }
- }
- $join->list_id = array_key_exists($join->listlabel, $aTableNames) ? $aTableNames[$join->listlabel]->id : '';
- $linkLabel = $this->parseMessageForRowHolder($linkedListText, JArrayHelper::fromObject($row));
- $linkKey .= '_raw';
- $group[$i]->$key = $this->viewDataLink($popupLink, $join->list_id, $row, $linkKey, $val, $count, $linkLabel);
- }
- $f ++;
- }
- $f = 0;
- //create columns containing links which point to forms assosciated with this table
- foreach ($linksToForms as $join) {
- if (array_key_exists($f, $keys)) {
- $linkedForm = $factedlinks->linkedform->$keys[$f];
- $popupLink = $factedlinks->linkedform_linktype->$keys[$f];
- // $$$ hugh @TODO - rob, can you check this, I added this line,
- // but the logic applied for $val in the linked table code above seems to be needed?
- // http://fabrikar.com/forums/showthread.php?t=9535
- $val = $pKeyVal;
- if ($linkedForm !== '0') {
- if (is_object($join)) {
- //$$$rob moved these two lines here as there were giving warnings since Hugh commented out the if ($element != '') {
- $linkKey = @$join->db_table_name . "___" . @$join->name;
- $gkey = $linkKey . "_form_heading";
- $linkLabel = $this->parseMessageForRowHolder($factedlinks->linkedformtext->$keys[$f], JArrayHelper::fromObject($row));
- $group[$i]->$gkey = $this->viewFormLink($popupLink, $join->list_id, $join->form_id, $row, $linkKey, $val, false, $linkLabel);
- }
- }
- $f ++;
- }
- }
- }
- }
- $args['data'] = &$data;
- $pluginButtons = $this->getPluginButtons();
- foreach ($data as $groupKey=>$group) {
- //$group =& $data[$key]; //Messed up in php 5.1 group positioning in data became ambiguous
- $cg = count($group);
- for ($i=0; $i < $cg; $i++) {
- $row =& $data[$groupKey][$i];
- foreach ($pluginButtons as $b) {
- if (trim($b) !== '') {
- $row->fabrik_actions[] = '<li>'.$b.'</li>';
- }
- }
- if (!empty($row->fabrik_actions)) {
- $this->actionHeading = true;
- $row->fabrik_actions = '<ul class="fabrik_action">'.implode("\n", $row->fabrik_actions).'</ul>';
- } else {
- $row->fabrik_actions = '';
- }
- }
- }
- }
- /**
- * @since 3.0
- * get delete button
- */
- protected function deleteButton()
- {
- return '<li class="fabrik_delete"><a href="#" class="delete" title="'.JText::_('COM_FABRIK_DELETE').'">'.
- FabrikHelperHTML::image('delete.png', 'list', '', JText::_('COM_FABRIK_DELETE')).
- '<span>'.JText::_('COM_FABRIK_DELETE').'</span></a></li>';
- }
- /**
- *
- * get a list of possible menus
- * USED TO BUILD RELTED TABLE LNKS WITH CORRECT iTEMD AND TEMPLATE
- * @return array linked table menu items
- * @since 2.0.4
- */
- protected function getTableLinks()
- {
- if (isset($this->tableLinks)){
- return $this->tableLinks;
- }
- $db =& JFactory::getDBO();
- $joinsToThisKey = $this->getJoinsToThisKey();
- if (empty($joinsToThisKey)) {
- $this->tableLinks = array();
- } else {
- $query = "SELECT * FROM #__menu WHERE type = 'component' AND ";
- foreach ($joinsToThisKey as $element) {
- $linkWhere[] = "link LIKE 'index.php?option=com_fabrik&view=list&listid=".(int)$element->list_id."%'";
- }
- $query .= '('.implode(' OR ', $linkWhere).')';
- $db->setQuery($query);
- $this->tableLinks = $db->loadObjectList();
- }
- return $this->tableLinks;
- }
- /**
- * for releated table links get the record count for each of the table's rows
- * @param $element
- * @param array primary keys to count on
- * @return array counts key'd on element primary key
- */
- public function getRecordCounts(&$element, $pks = array())
- {
- if (!isset($this->recordCounts)) {
- $this->recordCounts = array();
- }
- $k = $element->element_id;
- if (array_key_exists($k, $this->recordCounts)) {
- return $this->recordCounts[$k];
- }
- $listModel = JModel::getInstance('List', 'FabrikFEModel');
- $listModel->setId($element->list_id);
- $db =& $listModel->getDb();
- $elementModel =& $listModel->getFormModel()->getElement($element->element_id, true);
- $key = $elementModel->getFullName(false, false, false);
- $linkKey = FabrikString::safeColName($key);
- $fparams =& $listModel->getParams();
- //ensure that the facte table's require filters option is set to false
- $fparams->set('require-filter', false);
- //ignore facted tables session filters
- $origIncSesssionFilters = JRequest::getVar('fabrik_incsessionfilters', true);
- JRequest::setVar('fabrik_incsessionfilters', false);
- $where = $listModel->_buildQueryWhere(JRequest::getVar('incfilters', 0));
- if (!empty($pks)) {
- //only load the current record sets record counts
- $where .= trim($where) == '' ? ' WHERE ' : ' AND ';
- $where .= "$linkKey IN (" . implode(',', $pks) . ")";
- }
- $listModel->set('_joinsSQL', null); //force reload of join sql
- $listModel->set('includeCddInJoin', false); //trigger load of joins without cdd elements - seems to mess up count otherwise
- //see http://fabrikar.com/forums/showthread.php?t=12860
- //$totalSql = "SELECT $linkKey AS id, COUNT($linkKey) AS total FROM " . $element->db_table_name . " " . $tableModel->_buildQueryJoin();
- $k2 = $db->Quote(FabrikString::safeColNameToArrayKey($key));
- //$totalSql = "SELECT $k2 AS linkKey, $linkKey AS id, COUNT($linkKey) AS total FROM " . $listModel->getTable()->db_table_name . " " . $listModel->_buildQueryJoin();
- //$$$ Jannus - see http://fabrikar.com/forums/showthread.php?t=20751
- $distinct = $listModel->mergeJoinedData() ? 'DISTINCT ' : '';
- $totalSql = "SELECT $k2 AS linkKey, $linkKey AS id, COUNT($distinct ".$listModel->getTable()->db_primary_key.") AS total FROM " . $listModel->getTable()->db_table_name . " " . $listModel->_buildQueryJoin();
- $totalSql .= " $where GROUP BY $linkKey";
- $listModel->set('includeCddInJoin', true);
- $db->setQuery($totalSql);
- $this->recordCounts[$k] =& $db->loadObjectList('id');
- $this->recordCounts[$k]['linkKey'] = FabrikString::safeColNameToArrayKey($key);
- FabrikHelperHTML::debug($db->getQuery(), 'getRecordCounts query: '.$linkKey);
- FabrikHelperHTML::debug($this->recordCounts[$k], 'getRecordCounts data: '.$linkKey);
- JRequest::setVar('fabrik_incsessionfilters', $origIncSesssionFilters);
- return $this->recordCounts[$k];
- }
- /**
- * creates the html <a> link allowing you to edit other forms from the table
- * E.g. Faceted browsing: those specified in the table's "Form's whose primary keys link to this table"
- *
- * @param bol $popUp
- * @param object element 27/06/2011 - changed to passing in element
- * @param object $row
- * @param string $key
- * @param string $val
- * @param int param repeat value 27/11/2011
- * @return string <a> html part
- */
- function viewFormLink($popUp = false, $element, $row = null, $key = '', $val = '', $usekey = false, $f = 0)
- {
- $params =& $this->getParams();
- $listid = $element->table_id;
- $formid = $element->form_id;
- $linkedFormText = $params->get('linkedformtext', '', '_default', 'array');
- $label = $this->parseMessageForRowHolder(JArrayHelper::getValue($linkedFormText, $f), JArrayHelper::fromObject($row));
- $app = JFactory::getApplication();
- $Itemid = $app->getMenu('site')->getActive()->id;
- if (is_null($listid)) {
- $list = $this->getTable();
- $listid = $list->id;
- }
- if (is_null($formid)) {
- $form = $this->getFormModel()->getForm();
- $formid = $form->id;
- }
- $facetTable = $this->_facetedTable($listid);
- if (!$facetTable->canAdd()) {
- return '<div style="text-align:center"><a title="'.JText::_('JERROR_ALERTNOAUTHOR').'"><img src="media/com_fabrik/images/login.png" alt="'.JText::_('JERROR_ALERTNOAUTHOR').'" /></a></div>';
- }
- if ($app->isAdmin()) {
- $bits[] = "task=form.view";
- $bits[] = "cid=$formid";
- } else {
- $bits[] = "view=form";
- //$bits[] = "listid=$listid";
- $bits[] = "Itemid=$Itemid";
- }
- $bits[] = "formid=$formid";
- $bits[] = "referring_table=". $this->getTable()->id;
- // $$$ hugh - change in fabrikdatabasejoin getValue() means we have to append _raw to key name
- if ($key != '') {
- $bits[] = "{$key}_raw=$val";
- }
- if ($popUp) {
- $bits[] = "tmpl=component";
- $bits[] = "ajax=1";
- }
- if ($usekey and $key != '' and !is_null($row)) {
- $bits[] = "usekey=" . FabrikString::shortColName($key);
- $bits[] = "rowid=" . $row->slug;
- } else {
- $bits[] = "rowid=0";
- }
- $url = "index.php?option=com_fabrik&" . implode("&", $bits);
- $url = JRoute::_($url);
- if (is_null($label) || $label == '') {
- $label = JText::_('COM_FABRIK_LINKED_FORM_ADD');
- }
- if ($popUp) {
- FabrikHelperHTML::mocha('a.popupwin');
- $opts = new stdClass();
- $opts->maximizable = 1;
- $opts->title = JText::_('COM_FABRIK_ADD');
- $opts->evalScripts = 1;
- $opts = json_encode($opts);
- $link = "<a rel=\"$opts\" href=\"$url\" class=\"popupwin\" title=\"$label\">" . $label . "</a>";
- } else {
- $link = "<a href=\"$url\" title=\"$label\">" . $label . "</a>";
- }
- $url = "<span class=\"addbutton\">$link</span></a>";
- return $url;
- }
- /**
- * get one of the current tables facet tables
- *(used in tables that link to this tables links)
- * @param int table id
- * @return object table
- */
- function _facetedTable($id)
- {
- if (!isset($this->facettables)) {
- $this->facettables = array();
- }
- if (!array_key_exists($id, $this->facettables)) {
- $this->facettables[$id] = JModel::getInstance('List', 'FabrikFEModel');
- $this->facettables[$id]->setId($id);
- }
- return $this->facettables[$id];
- }
- /**
- * build the link (<a href..>) for viewing table data
- *
- * @param bol $popUp is the link to generated a popup to show
- * @param obj element 27/06/2011
- * @param object $row
- * @param string $key 28/06/2011 - do longer passed in with _raw appended (done in this method)
- * @param string $val
- * @param int number of related records
- * @param int ref to related data admin info 27/16/2011
- * @return string
- */
- function viewDataLink($popUp = false, $element, $row = null, $key = '', $val = '', $count = 0, $f)
- {
- $listid = $element->table_id;
- $app = JFactory::getApplication();
- $params =& $this->getParams();
- $linkedTableText = $params->get('linkedtabletext', '', '_default', 'array');
- $label = $this->parseMessageForRowHolder(JArrayHelper::getValue($linkedTableText, $f), JArrayHelper::fromObject($row));
- $Itemid = $app->isAdmin() ? 0 : @$app->getMenu('site')->getActive()->id;
- $action = $app->isAdmin() ? "task" : "view";
- $url = "index.php?option=com_fabrik&";
- if (is_null($listid)) {
- $list = $this->getTable();
- $listid = $list->id;
- }
- $facetTable = $this->_facetedTable($listid);
- if (!$facetTable->canView()) {
- return '<div style="text-align:center"><a title="'.JText::_('Insufficient access rights. Please login').'"><img src="media/com_fabrik/images/login.png" alt="'.JText::_('iInsufficient access rights. Please login').'" /></a></div>';
- }
- $tlabel = ($label === '') ? JText::_('COM_FABRIK_NO_RECORDS') : '(0) '.$label;
- if ($count === 0) {
- $aExisitngLinkedForms = $params->get('linkedform', '', '_default', 'array');
- $linkedForm = JArrayHelper::getValue($aExisitngLinkedForms, $f, false);
- $addLink = $linkedForm == '0' ? $this->viewFormLink($popUp, $element, $row, $key, $val, false, $f) : '';
- return '<div style="text-align:center" class="related_data_norecords">'.$tlabel.'</div>'.$addLink;
- }
- $key .= '_raw';
- if ($label === '') {
- $label = JText::_('COM_FABRIK_VIEW');
- }
- $label = '('.$count.') '.$label;
- if ($app->isAdmin()) {
- $bits[] = "task=viewTable";
- $bits[] = "cid=$listid";
- } else {
- $bits[] = "view=list";
- $bits[] = "listid=$listid";
- $tableLinks = $this->getTableLinks();
- // $$$ rob 01/03/2011 find at matching itemid in another menu item for the related data link
- foreach ($tableLinks as $tlink) {
- if (strstr($tlink->link, 'index.php?option=com_fabrik&view=list&listid='.$listid)) {
- $bits[] = "Itemid=".$tlink->id;
- $Itemid = $tlink->id;
- break;
- }
- }
- $bits[] = "Itemid=$Itemid";
- }
- if ($key != '') {
- $bits[] = "{$key}=$val";
- }
- $bits[] = 'limitstart=0';
- if ($popUp) {
- $bits[] = "tmpl=component";
- $bits[] = "ajax=1";
- }
- $bits[] = "&resetfilters=1";
- //$bits[] = "clearfilters=1"; //nope stops url filter form workin on related data :(
- $url .= implode("&", $bits);
- $url = JRoute::_($url);
- if ($popUp) {
- FabrikHelperHTML::mocha('a.popupwin');
- $opts = new stdClass();
- $opts->maximizable = 1;
- $opts->title = JText::_('COM_FABRIK_VIEW');
- $opts->evalScripts = 1;
- $opts = str_replace('"', "'", json_encode($opts));
- $url = '<a rel="'.$opts.'" href="'. $url.'" class="popupwin">'.$label.'</a>';
- } else {
- $url = '<a class="related_data" href="'.$url.'">'.$label."</a>";
- }
- return $url;
- }
- /**
- * add a normal/custom link to the element data
- *
- * @param string element $data
- * @param object element
- * @param object of all row data
- * @return string element data with link added if specified
- */
- public function _addLink($data, &$elementModel, $row, $repeatCounter = 0)
- {
- $element =& $elementModel->getElement();
- if ($this->_outPutFormat == 'csv' || $element->link_to_detail == 0) {
- return $data;
- }
- $params =& $elementModel->getParams();
- $customLink = $params->get('custom_link');
- // $$$ rob if its a custom link then we aren't linking to the details view so we should
- // ignore the view details access settings
- if (!$this->canViewDetails($row) && trim($customLink) == '') {
- return $data;
- }
- $list = $this->getTable();
- $primaryKeyVal = $this->getKeyIndetifier($row);
- $link = $this->linkHref($elementModel, $row, $repeatCounter);
- if ($link == '') {
- return $data;
- }
- //try to remove any previously entered links
- $data = preg_replace('/<a(.*?)>|<\/a>/', '', $data);
- $data = "<a class=\"fabrik___rowlink\" href=\"$link\">$data</a>";
- return $data;
- }
- /**
- * since 2.0.4 get the href for the edit link
- * @param object $elementModel
- * @param array $row data
- * @return string link href
- */
- public function linkHref($elementModel, $row, $repeatCounter = 0)
- {
- $element =& $elementModel->getElement();
- $table =& $this->getTable();
- $params =& $elementModel->getParams();
- $customLink = $params->get('custom_link');
- $link = '';
- if ($customLink == '') {
- // $$$ rob only test canEdit and canView on stardard edit links - if custom we should always use them,
- //3.0 get either edit or view link - as viewDetailslInk now always returns the view details link
- if ($this->canEdit($row)) {
- $this->_aLinkElements[] = $element->name;
- $link = $this->editLink($row);
- } else if ($this->canViewDetails($row)) {
- $this->_aLinkElements[] = $element->name;
- $link = $this->viewDetailsLink($row);
- }
- } else {
- $array = JArrayHelper::fromObject($row);
- foreach ($array as $k => &$v) {
- $v = json_decode($v, $true);
- if (is_array($v)) {
- $v = JArrayHelper::getValue($v, $repeatCounter);
- }
- }
- $array['rowid'] = $this->getSlug($row);
- $array['listid'] = $table->id;
- $link = JRoute::_($this->parseMessageForRowHolder($customLink, $array));
- }
- return $link;
- }
- /**
- * get query to make records
- * @return string sql
- */
- function _buildQuery()
- {
- global $_PROFILER;
- JDEBUG ? $_PROFILER->mark('_buildQuery: start') : null;
- $query = array();
- if ($this->mergeJoinedData()) {
- // $$$ rob - get a list of the main table's ids limited on the navigation
- // this will then be used to filter the main query,
- // by modifying the where part of the query
- $db = $this->getDb();
- $table = $this->getTable();
- // $$$ rob build order first so that we know of any elemenets we need to include in the select statement
- $order = $this->_buildQueryOrder();
- $this->selectedOrderFields = (array)$this->selectedOrderFields;
- array_unshift($this->selectedOrderFields , "DISTINCT ".$table->db_primary_key . " AS __pk_val");
- $query['select'] = "SELECT ". implode(', ', $this->selectedOrderFields) . " FROM ".$db->nameQuote($table->db_table_name);
- $query['join'] = $this->_buildQueryJoin();
- $query['where'] = $this->_buildQueryWhere(JRequest::getVar('incfilters', 1));
- $query['grouby'] = $this->_buildQueryGroupBy();
- $query['order'] = $order;
- //check that the order by fields are in the select statement
- $squery = implode(" ", $query);
- $db->setQuery($squery, $this->limitStart, $this->limitLength);
- FabrikHelperHTML::debug($db->getQuery(), 'table:mergeJoinedData get ids');
- $ids = JArrayHelper::getColumn($db->loadObjectList(), '__pk_val');
- }
- $query = array();
- $query['select'] = $this->_buildQuerySelect();
- JDEBUG ? $_PROFILER->mark('queryselect: got') : null;
- $query['join'] = $this->_buildQueryJoin();
- JDEBUG ? $_PROFILER->mark('queryjoin: got') : null;
- if ($this->mergeJoinedData()) {
- // $$$ rob We've already used _buildQueryWhere to get our list of main pk ids.
- // so lets use that list of ids to create the where statement. This will return 5/10/20 etc
- // records from our main table, as per our page nav, even if a main record has 3 rows of joined
- // data. If no ids found then do where 1 = -1 to return no records
- if (!empty($ids)) {
- $query['where'] = " WHERE $table->db_primary_key IN (".implode($ids, ',').')';
- } else {
- $query['where'] = " WHERE 1 = -1";
- }
- } else {
- // $$$ rob we aren't merging joined records so lets just add the standard where query
- //incfilters set when exporting as CSV
- $query['where'] = $this->_buildQueryWhere(JRequest::getVar('incfilters', 1));
- }
- $query['groupby'] = $this->_buildQueryGroupBy();
- $query['order'] = $this->_buildQueryOrder();
- $query = $this->pluginQuery($query);
- $query = implode(" ", $query);
- return $query;
- }
- /**
- * pass an sql query through the table plug-ins
- * @param string $query
- * @return string altered query.
- */
- public function pluginQuery($query)
- {
- //pass the query as an object property so it can be updated via reference
- $args = new stdClass();
- $args->query = $query;
- $this->getPluginManager()->runPlugins('onQueryBuilt', $this, 'list', $args);
- $query = $args->query;
- return $query;
- }
- /**
- * get the select part of the query
- *
- * @return string
- */
- function _buildQuerySelect()
- {
- global $_PROFILER;
- JDEBUG ? $_PROFILER->mark('queryselect: start') : null;
- $db = $this->getDb();
- $form =& $this->getFormModel();
- $table =& $this->getTable();
- $form->getGroupsHiarachy(true);
- JDEBUG ? $_PROFILER->mark('queryselect: fields load start') : null;
- $fields =& $this->getAsFields();
- $pk = FabrikString::safeColName($table->db_primary_key);
- //SEFSLUG TEST
- $params =& $this->getParams();
- if (in_array($this->_outPutFormat, array('raw', 'html', 'feed', 'pdf', 'phocapdf'))) {
- $slug = $params->get('sef-slug');
- if ($slug != '') {
- $slug = FabrikString::safeColName($slug);
- $fields[] = "CONCAT_WS(':', $pk, $slug) AS slug";
- } else {
- if ($pk !== '``') {
- $fields[] = "$pk AS slug";
- }
- }
- }
- //END
- JDEBUG ? $_PROFILER->mark('queryselect: fields loaded') : null;
- $sfields = (empty($fields)) ? '' : implode(", \n ", $fields) . "\n ";
- //$$$rob added raw as an option to fix issue in saving calendener data
- if (trim($table->db_primary_key) != '' && (in_array($this->_outPutFormat, array('raw','html','feed','pdf','phocapdf','csv')))) {
- $sfields .= ", ";
- $strPKey = $pk . " AS " . $db->nameQuote('__pk_val') . "\n";
- $query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT ' . $sfields . $strPKey;
- } else {
- $query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT ' . trim($sfields, ", \n") . "\n";
- }
- $query .= " FROM ".$db->nameQuote($table->db_table_name)." \n";
- return $query;
- }
- /**
- * get the part of the sql statement that orders the table data
- * @param mixed false or a query object
- * @return string ordering part of sql statement
- */
- function _buildQueryOrder($query = false)
- {
- $params = $this->getParams();
- $table =& $this->getTable();
- $db = FabrikWorker::getDbo();
- $this->selectedOrderFields = array();
- if ($this->_outPutFormat == 'feed')
- {
- $dateColId = (int)$params->get('feed_date', 0);
- $db->setQuery('SELECT name FROM #__{package}_elements WHERE id = '.$dateColId);
- $dateCol = $db->nameQuote($table->db_table_name).'.'.$db->nameQuote($db->loadResult());
- if ($dateColId !== 0) {
- $this->order_dir = 'DESC';
- $this->order_by = $dateCol;
- if (!$query) {
- return "\n ORDER BY $dateCol DESC";
- } else {
- $query->order($dateCol.' DESC');
- return $query;
- }
- }
- }
- $session = JFactory::getSession();
- //$$$rob - when table reordered the controller runs order() and
- // stores the order settings in the session by calling setOrderByAndDir()
- // it then redirects to the table view and here all we need to do it get
- // those order settings from the session
- $elements =& $this->getElements();
- //build the order by statement from the session
- $strOrder = '';
- $clearOrdering = (bool)JRequest::getInt('clearordering', false) && JRequest::getCmd('task') !== 'order';
- //$$$tom Added single-ordering option
- if ($params->get('enable_single_sorting', 'default') == 'default') { // Use global
- $fbConfig =& JComponentHelper::getParams('com_fabrik');
- $singleOrdering = $fbConfig->get('enable_single_sorting', false);
- }
- else {
- $singleOrdering = $params->get('enable_single_sorting', false);
- }
- $id = $this->getId();
- foreach ($elements as $element) {
- $context = 'com_fabrik.table'.$id.'.order.'.$element->getElement()->id;
- if ($clearOrdering) {
- $session->set($context, '');
- } else {
- //$$$tom Added single-ordering option
- if (!$singleOrdering || ($singleOrdering && $element->getElement()->id == JRequest::getInt('orderby', ''))) {
- $dir = $session->get($context);
- if ($dir != '' && $dir != '-' && trim($dir) != 'Array') {
- $strOrder == '' ? $strOrder = "\n ORDER BY " : $strOrder .= ',';
- $strOrder .= $element->getOrderByName()." $dir";
- $this->orderEls[] = $element->getOrderByName();
- $this->orderDirs[] = $dir;
- $element->getAsField_html($this->selectedOrderFields, $aAsFields);
- }
- }
- else {
- $session->set($context, '');
- }
- }
- }
- //if nothing found in session use default ordering
- if ($strOrder == '') {
- $orderbys = json_decode($table->order_by, true);
- $orderdirs = json_decode($table->order_dir, true);
- if (!empty($orderbys)) {
- $bits = array();
- for ($o = 0; $o < count($orderbys); $o++) {
- $dir = JArrayHelper::getValue($orderdirs, $o, 'desc');
- if ($orderbys[$o] !== '') {
- $orderby = FabrikString::safeColName($orderbys[$o]);
- $els = $this->getElements('filtername');
- if (array_key_exists($orderby, $els)) {
- // $$$ hugh - getOrderByName can return a CONCAT, ie join element ...
- $field = $els[$orderby]->getOrderByName();
- if (!stristr($field, 'CONCAT(')) {
- $field = FabrikString::safeColName($field);
- }
- $bits[] = " $field $dir";
- $this->orderEls[] = $field;
- $this->orderDirs[] = $dir;
- } else {
- if (strstr($orderby, '_raw`')) {
- $orderby = FabrikString::safeColNameToArrayKey($orderby);
- }
- $bits[] = " $orderby $dir";
- $this->orderEls[] = $orderby;
- $this->orderDirs[] = $dir;
- }
- }
- }
- if (!empty($bits)) {
- if (!$query) {
- $strOrder = "\n ORDER BY" . implode(',', $bits);
- } else {
- $query->order(implode(',', $bits));
- }
- }
- }
- }
- // apply group ordering
- // @TODO - explain something to hugh! Why is this "group ordering"? AFAICT, it's just a secondary
- // order by, isn't specific to the Group By feature in any way? So why not just put this option in
- //
- $groupOrderBy = $params->get('group_by_order');
- if ($groupOrderBy != '') {
- $groupOrderDir = $params->get('group_by_order_dir');
- $strOrder == '' ? $strOrder = "\n ORDER BY " : $strOrder .= ',';
- $orderby = strstr($groupOrderBy, '_raw`') ? FabrikString::safeColNameToArrayKey($groupOrderBy) : FabrikString::safeColName($groupOrderBy);
- if (!$query) {
- $strOrder .= $orderby." ".$groupOrderDir;
- } else {
- $query->order($orderby." ".$groupOrderDir);
- }
- $this->orderEls[] = $orderby;
- $this->orderDirs[] = $groupOrderDir;
- }
- return $query === false ? $strOrder : $query;
- }
- /**
- * called when the table column order by is clicked
- * store order options in session
- * @return null
- */
- function setOr…
Large files files are truncated, but you can click here to view the full file