PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/components/com_fabrik/models/table.php

https://github.com/chrisinammo/arthurmcneil
PHP | 3994 lines | 2886 code | 400 blank | 708 comment | 677 complexity | b38126dd4abc91b2851f41221bc1ba95 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * @package Joomla
  4. * @subpackage Fabrik
  5. * @copyright Copyright (C) 2005 Rob Clayburn. All rights reserved.
  6. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
  7. */
  8. // Check to ensure this file is included in Joomla!
  9. defined('_JEXEC') or die();
  10. require_once( COM_FABRIK_FRONTEND.DS.'helpers'.DS.'json.php' );
  11. require_once( COM_FABRIK_FRONTEND.DS.'helpers'.DS.'pagination.php' );
  12. require_once( COM_FABRIK_FRONTEND.DS.'helpers'.DS.'string.php' );
  13. class FabrikModelTable extends JModel {
  14. /** @var object the tables connection object */
  15. var $_oConn = null;
  16. /** @var object table Table */
  17. var $_table = null;
  18. /** @var array filters applied to table */
  19. var $_aFilter = null;
  20. /** @var array prefilters applied to the table */
  21. var $_aPrefilters = array();
  22. /** @var object table's database connection object (loaded from connection object) */
  23. var $_oConnDB = null;
  24. /** @var object table's form model */
  25. var $_oForm = null;
  26. /** @var array joins */
  27. var $_aJoins = null;
  28. /** @var array column calculations */
  29. var $_aRunCalculations = array();
  30. /** @var string table output format - set to rss to collect correct element data within function gettData()*/
  31. var $_outPutFormat = 'html';
  32. var $_isMambot = false;
  33. var $_admin = false;
  34. /** @var object to contain access rights **/
  35. var $_access = null;
  36. /** @var int the id of the last inserted record (or if updated the last record updated) **/
  37. var $_lastInsertId = null;
  38. /** @var bol determine if we apply prefilters (0 = yes, 1 = no )*/
  39. var $_togglePreFilters = 0;
  40. /** @var array store data to create joined records from */
  41. var $_joinsToProcess = array();
  42. /** @var array database fields */
  43. var $_dbFields = null;
  44. /** @var bol force reload table calculations **/
  45. var $_reloadCalculations = false;
  46. /** @var array data contains request data **/
  47. var $_aData = null;
  48. /** 'var array data to render the table with **/
  49. var $_tableData = null;
  50. /** @var string method to use when submitting form data // post or ajax*/
  51. var $_postMethod = 'post';
  52. /** @var int package id */
  53. var $_packageId = null;
  54. /** @var object plugin manager */
  55. var $_pluginManager = null;
  56. /** @var int id of table to load */
  57. var $_id = null;
  58. /** @var string join sql **/
  59. var $_joinsSQL = null;
  60. /** @var bol is the object inside a package? */
  61. //var $_inPackage = false;
  62. /** @var bol when getting the tableData this decides if only the elements published to the
  63. table view are loaded. Primarily used by visualization plugins to get all table data regardless
  64. of whether its published to the table view */
  65. var $_onlyTableData = true;
  66. var $_formGroupElementData = array();
  67. var $_joinsToThisKey = null;
  68. var $_real_filter_action = null;
  69. var $_aAsFields = null;
  70. /** array merged request and session data used to potentially filter the table **/
  71. var $_request = null;
  72. var $_aRow = null;
  73. /** array rows to delete **/
  74. vaR $_rowsToDelete = null;
  75. /**
  76. * Constructor
  77. *
  78. * @since 1.5
  79. */
  80. function __construct()
  81. {
  82. parent::__construct();
  83. $usersConfig = &JComponentHelper::getParams( 'com_fabrik' );
  84. $id = JRequest::getInt( 'tableid', $usersConfig->get( 'tableid' ) );
  85. $this->setId($id);
  86. $this->_access = new stdClass();
  87. }
  88. /**
  89. * main query to build table
  90. *
  91. */
  92. function render()
  93. {
  94. global $mainframe, $_PROFILER;
  95. $document =& JFactory::getDocument( );
  96. if (is_null( $this->_id ) || $this->_id == '0') {
  97. return JError::raiseError( 500, JText::_('Table id not set - can not render'));
  98. }
  99. $params =& $this->getParams();
  100. $session =& JFactory::getSession();
  101. $this->_outPutFormat = JRequest::getVar( 'format', 'html' );
  102. $pluginManager =& JModel::getInstance( 'Pluginmanager', 'FabrikModel' );
  103. $pluginManager->loadPlugInGroup( 'table' );
  104. if (!$pluginManager->runPlugins( 'onStartRender', $this, 'table' )) {
  105. return;
  106. }
  107. $table =& $this->getTable();
  108. //cant set time limit in safe mode so suppress warning
  109. @set_time_limit ( 800 );
  110. $this->_request = $this->getRequestData();
  111. $context = 'com_fabrik.table.'. $this->_id.'.list.';
  112. $limitLength = $mainframe->getUserStateFromRequest( $context.'limitLength', 'limit', $table->rows_per_page );
  113. $limitStart = $mainframe->getUserStateFromRequest($context.'limitstart', 'limitstart', 0, 'int');
  114. if ($this->_outPutFormat == 'feed') {
  115. $limitLength = JRequest::getVar( 'limit', $params->get( 'rsslimit',150 ) );
  116. $maxLimit = $params->get( 'rsslimitmax', 2500 );
  117. if ($limitLength > $maxLimit) {
  118. $limitLength = $maxLimit;
  119. }
  120. }
  121. $total = $this->getTotalRecords( );
  122. $this->_pageNav =& $this->_getPagination( $total, $limitStart, $limitLength );
  123. if ($limitLength == 0) {
  124. $pageNav->limit = 0;
  125. }
  126. $this->_tableData = $this->getData();
  127. $this->getCalculations( );
  128. $table->hit();
  129. }
  130. /**
  131. * this merges session data for the fromForm with any request data
  132. * allowing us to filter data results from both search forms and filters
  133. *
  134. * @return array
  135. */
  136. function getRequestData()
  137. {
  138. global $_SESSION;
  139. //session_destroy();
  140. if (isset($this->_request)) {
  141. return $this->_request;
  142. }
  143. $aData = JRequest::get( 'request' );
  144. $formModel =& $this->getForm();
  145. $table =& $this->getTable();
  146. if (is_array( $_SESSION )) {
  147. if (array_key_exists( "fabrik", $_SESSION )) {
  148. if (array_key_exists( 'fromForm', $_SESSION["fabrik"] )) {
  149. $fromForm = $_SESSION["fabrik"]['fromForm'];
  150. //only merge if the fromForm is not the same as the current table's form id
  151. if ($_SESSION["fabrik"]['fromForm'] != $formModel->_id) {
  152. $this->_oFromForm =& JModel::getInstance( 'Form', 'FabrikModel' );
  153. $this->_oFromForm->setId( $fromForm );
  154. $fromFormTable = $this->_oFromForm->getForm();
  155. $fromFormParams = $this->_oFromForm->getParams();
  156. //fudge the sesson so that any search form data's keys are the same as the current
  157. //tables
  158. if (array_key_exists( $fromForm, $_SESSION['fabrik'] )) {
  159. foreach ($_SESSION['fabrik'][$fromForm] as $k1=>$v) {
  160. //only unset if not done previously
  161. if (strstr( $k1, "___" )) {
  162. $k2 = $table->db_table_name . "___" . array_pop(explode("___", $k1));
  163. } else {
  164. $k2 = $table->db_table_name . "___" . $k1;
  165. }
  166. if (array_key_exists( $k2, $aData )) {
  167. //override search form session info with any posted filters
  168. $v = $aData[$k2];
  169. }
  170. $_SESSION['fabrik'][$fromForm][$k2] = $v;
  171. }
  172. }
  173. if (array_key_exists( $fromForm, $_SESSION["fabrik"])) {
  174. $aData = array_merge( $aData, $_SESSION["fabrik"][$fromForm] );
  175. }
  176. }
  177. //$$$rob since after 1.0.5.2 DONT unset as page nav no longer picks up the filter
  178. //unset( $_SESSION["fabrik"]['fromForm'] );
  179. }
  180. }
  181. }
  182. return $aData;
  183. }
  184. /**
  185. * get the table's data
  186. *
  187. * @return array of objects (rows)
  188. */
  189. function getData()
  190. {
  191. $fabrikDb =& $this->getDb();
  192. $query = $this->_buildQuery();
  193. $fabrikDb->setQuery( $query, $this->_pageNav->limitstart, $this->_pageNav->limit );
  194. if (JRequest::getBool( 'fabrikdebug', 0 ) == 1) {
  195. echo "<pre>"; echo $fabrikDb->getQuery();echo "</pre>";
  196. }
  197. $data = $fabrikDb->loadObjectList( );
  198. if ($data === false) {
  199. JError::raiseNotice(500, 'getData: ' . $fabrikDb->getErrorMsg( ) );
  200. }
  201. //append the cursor & total to the data
  202. if ($this->_outPutFormat == 'html' || $this->_outPutFormat == 'raw') {
  203. for ($i=0; $i<count($data); $i++) {
  204. $data[$i]->_cursor = $i + $this->_pageNav->limitstart;
  205. $data[$i]->_total = $this->_pageNav->total;
  206. }
  207. }
  208. $this->formatData( $data );
  209. return $data;
  210. }
  211. /**
  212. * run the table data through element filters
  213. *
  214. * @param array $data
  215. */
  216. function formatData( &$data )
  217. {
  218. jimport('joomla.filesystem.file');
  219. $form =& $this->getForm();
  220. $table =& $this->getTable();
  221. $pluginManager =& JModel::getInstance( 'Pluginmanager', 'FabrikModel' );
  222. $method = 'renderTableData_' . $this->_outPutFormat;
  223. $this->_aLinkElements = array();
  224. foreach ($form->_groups as $groupModel) {
  225. if (is_array( $groupModel->_aElements )) {
  226. foreach ($groupModel->_aElements as $elementModel) {
  227. $e =& $elementModel->getElement();
  228. $elementModel->setContext( $groupModel, $form, $this );
  229. $params =& $elementModel->getParams( );
  230. $col = $elementModel->getFullName( false, true, false );
  231. //check if there is a custom out put handler for the tables format
  232. // currently supports "renderTableData_csv", "renderTableData_rss", "renderTableData_html", "renderTableData_json"
  233. if (!empty( $data ) && array_key_exists( $col, $data[0] )) {
  234. if (method_exists( $elementModel, $method )) {
  235. for ($i=0; $i<count( $data ); $i++) {
  236. $thisRow = $data[$i];
  237. $coldata = $data->$col;
  238. $d = $elementModel->$method( $coldata, $col, $thisRow );
  239. $data[$i]->$col = $this->_addLink( $d, $elementModel, $thisRow );
  240. }
  241. } else {
  242. $ec = count( $data );
  243. for ( $i=0; $i< $ec; $i++ ) {
  244. $thisRow = $data[$i];
  245. $coldata = $thisRow->$col;
  246. $d = $elementModel->renderTableData( $coldata, $thisRow );
  247. $data[$i]->$col = $this->_addLink( $d, $elementModel, $thisRow );
  248. $rawCol = $col . "_raw";
  249. if (!array_key_exists( $rawCol, $thisRow)){
  250. $data[$i]->$rawCol = $elementModel->renderRawTableData( $coldata, $thisRow );
  251. }
  252. }
  253. // run a final function for each fo the elements (basically here to
  254. // avoid you doing extraneous sql calls in renderTableData
  255. // ie create sql query in rendertabledata, then run it in mergeTableData
  256. // currently used for advanced table joins only
  257. $elementModel->mergeTableData( $data, $this );
  258. }
  259. //see if we replace data with icons
  260. /*
  261. if ($params->get('icon_folder') != -1 && $params->get('icon_folder') != '') {
  262. jimport('joomla.filesystem.file');
  263. for ($i=0; $i<count( $data ); $i++) {
  264. $thisRow = $data[$i];
  265. $coldata = $thisRow->$col;
  266. $data[$i]->$col = $elementModel->replaceWithIcons( $coldata );
  267. }
  268. }
  269. */
  270. }
  271. }
  272. }
  273. }
  274. $this->_aGroupInfo = array();
  275. $groupTitle = array();
  276. //check if the data has a group by applied to it
  277. if ($table->group_by != '') {
  278. $groupedData = array();
  279. $thisGroupedData = array();
  280. $groupBy = $table->group_by;
  281. //see if we can use a raw value instead
  282. if (!empty( $data ) && array_key_exists( $groupBy . "_raw", $data[0] )) {
  283. $groupBy = $groupBy . "_raw";
  284. }
  285. $groupTitle = null;
  286. $aGroupTitles = array();
  287. $groupId = 0;
  288. for ( $i=0; $i<count( $data ); $i++ ) {
  289. if (!in_array( $data[$i]->$groupBy , $aGroupTitles )) {
  290. $aGroupTitles[] = $data[$i]->$groupBy;
  291. $groupedData[$data[$i]->$groupBy] = array();
  292. }
  293. $data[$i]->_groupId = $data[$i]->$groupBy;
  294. $gKey = $data[$i]->$groupBy;
  295. // if the group_by was added in in getAsFields remove it from the returned data set (to avoid mess in package view)
  296. if ($this->_group_by_added ){
  297. unset($data[$i]->$groupBy );
  298. }
  299. if ($this->_temp_db_key_addded ){
  300. $k = $table->db_primary_key;;
  301. }
  302. $groupedData[$gKey][] = $data[$i];
  303. }
  304. $data = $groupedData;
  305. } else {
  306. for( $i=0; $i<count( $data ); $i++ ){
  307. if ($this->_temp_db_key_addded ){
  308. $k = $table->db_primary_key;;
  309. }
  310. }
  311. //make sure that the none grouped data is in the same format
  312. $data = array( $data );
  313. }
  314. if ($this->_outPutFormat != 'pdf' && $this->_outPutFormat != 'csv' && $this->_outPutFormat != 'feed') {
  315. $this->addSelectBoxAndLinks( $data );
  316. if (JRequest::getVar( 'fabrikdebug' )) {
  317. echo "<pre>";print_r($data);echo"</pre>";
  318. }
  319. }
  320. }
  321. /**
  322. * add the select box and various links into the data array
  323. * @param array table row objects
  324. */
  325. function addSelectBoxAndLinks( &$data )
  326. {
  327. global $Itemid;
  328. $table =& $this->getTable();
  329. $db =& JFactory::getDBO();
  330. $params =& $this->getParams();
  331. $nextview = ($this->canEdit()) ? "form" : "details";
  332. $tmpKey = '__pk_val';
  333. $aExisitngLinkedTables = $params->get('linkedtable', '', '_default', 'array');
  334. $aExisitngLinkedForms = $params->get('linkedform', '', '_default', 'array');
  335. $linkedform_linktype = $params->get( 'linkedform_linktype', '', '_default', 'array' );
  336. $linkedtable_linktype = $params->get( 'linkedtable_linktype', '', '_default', 'array' );
  337. $aExistingTableHeaders = $params->get( 'linkedtableheader', '', '_default', 'array' );
  338. $aExistingFormHeaders = $params->get( 'linkedformheader', '', '_default', 'array' );
  339. //get a list of fabrik tables and ids for view table and form links
  340. $action = ($this->_admin) ? "task" : "view";
  341. $sql = "SELECT id, label FROM #__fabrik_tables";
  342. $db->setQuery( $sql );
  343. $aTableNames = $db->loadObjectList( 'label' );
  344. $cx = count($data);
  345. $viewLinkAdded = false;
  346. //for ($x=0; $x<$cx; $x++) { //if grouped data then the key is not numeric
  347. foreach ($data as $key=>$group) {
  348. //$group =& $data[$key]; //Messed up in php 5.1 group positioning in data became ambiguous
  349. $cg = count( $group );
  350. for( $i=0; $i < $cg; $i++ ){
  351. $row =& $data[$key][$i];
  352. $pKeyVal = (array_key_exists( $tmpKey, $row )) ? $row->$tmpKey : '';
  353. $row->fabrik_delete = ($this->canDelete()) ? '<input type="checkbox" id="id_'.$row->_cursor .'" name="ids['.$row->_cursor.']" value="' . $pKeyVal . '" />' : '';
  354. //add in some default links if no element choosen to be a link
  355. if (empty( $this->_aLinkElements ) and ($this->canView() || $this->canEdit())){
  356. $link = ( $this->_outPutFormat == 'json' ) ? "#" : JRoute::_("index.php?option=com_fabrik&c=form&$action=$nextview&Itemid=$Itemid&fabrik=" . $table->form_id . "&rowid=$pKeyVal&tableid=" .$this->_id . "&fabrik_cursor=" . $row->_cursor . "&fabrik_total=" . $row->_total );
  357. if ($this->canEdit()) {
  358. $row->fabrik_edit = "<a class='fabrik___rowlink' href='$link'>" . JText::_('Edit') . "</a>";
  359. } else {
  360. if($this->canViewDetails()){
  361. $viewLinkAdded = true;
  362. $row->fabrik_edit = "<a class='fabrik___rowlink' href='$link'>" . JText::_('View') . "</a>";
  363. } else {
  364. $row->fabrik_edit = '';
  365. }
  366. }
  367. }
  368. //@TODO: test if all of these are necessary
  369. if ($this->canViewDetails()) {
  370. $link = JRoute::_( "index.php?option=com_fabrik&c=form&$action=form&Itemid=$Itemid&fabrik=" . $table->form_id . "&rowid=$pKeyVal&tableid=" .$this->_id . "&fabrik_cursor=" . $row->_cursor . "&fabrik_total=" . $row->_total );
  371. $row->fabrik_view = "<a class='fabrik___rowlink' href='$link'>" . JText::_('View') . "</a>";
  372. }
  373. if ($this->canViewDetails( ) && $params->get( 'detaillink' ) == '1' && !$viewLinkAdded ) {
  374. $row->__details_link = $this->viewDetailsLink( $pKeyVal );
  375. }
  376. // create columns containing links which point to tables associated with this table
  377. $joinsToThisKey = $this->getJoinsToThisKey( );
  378. $f = 0;
  379. foreach ($joinsToThisKey as $element) {
  380. $linkedTable = array_key_exists($f, $aExisitngLinkedTables) ? $aExisitngLinkedTables[$f] : false;
  381. $popUpLink = array_key_exists($f, $linkedtable_linktype) ? $linkedtable_linktype[$f] : false;
  382. if ($linkedTable != '0') {
  383. if ($element->tablelabel == $table->label) { //if the link points to the same table
  384. $thiskey = $table->db_table_name.'.'.$this->_oTable->_tbl_key;
  385. $key = $element->element_name;
  386. $x = $element->element_name;
  387. $val = $row->$thiskey;
  388. } else {
  389. $linkKey = $element->db_table_name . "___" . $element->name;
  390. $key = $linkKey . "_table_heading";
  391. $val = $pKeyVal;
  392. }
  393. $element->table_id = ( array_key_exists( $element->tablelabel, $aTableNames)) ? $aTableNames[$element->tablelabel]->id : '';
  394. if ($popUpLink != '0') {
  395. //pop up window link
  396. $url = JRoute::_( "index.php?option=com_fabrik&tmpl=component&Itemid=$Itemid&view=table&tableid=$element->table_id&$linkKey" . "[value]=$val&fabrik_cursor=" . $row->_cursor . "&fabrik_total=" . $row->_total );
  397. FabrikHelperHTML::mocha( 'a.popupwin' );
  398. $group[$i]->$key = '<a rel="{\'maximizable\':true}" href="'. $url.'" class="popupwin">'. JText::_('View') .'</a>';
  399. } else {
  400. $url = JRoute::_( "index.php?option=com_fabrik&Itemid=$Itemid&$action=table&tableid=$element->table_id&$linkKey" . "[value]=$val&fabrik_cursor=" . $row->_cursor . "&fabrik_total=" . $row->_total );
  401. $group[$i]->$key = "<a href=\"$url\">" . JText::_('View'). "</a>";
  402. }
  403. }
  404. $f ++;
  405. }
  406. $linksToForms = $this->getLinksToThisKey( );
  407. $f = 0;
  408. //create columns containing links which point to forms assosciated with this table
  409. foreach ( $linksToForms as $element ) {
  410. if ($element != '') {
  411. $linkedForm = array_key_exists($f, $aExisitngLinkedForms) ? $aExisitngLinkedForms[$f] : false;
  412. $popUpLink = array_key_exists($f, $linkedform_linktype) ? $linkedform_linktype[$f] : false;
  413. $linkKey = $element->db_table_name . "___" . $element->name;
  414. $key = $linkKey . "_form_heading";
  415. if ($linkedForm != '0') {
  416. if ($popUpLink != '0') {
  417. $url = JRoute::_("index.php?option=com_fabrik&tmpl=component&Itemid=$Itemid&$action=form&tableid=$element->table_id&fabrik=$element->form_id&$linkKey" . "[value]=$val");
  418. FabrikHelperHTML::mocha( 'a.popupwin' );
  419. $group[$i]->$key = '<a rel="{\'maximizable\':true}" href="'. $url.'" class="popupwin">'. JText::_('Add') .'</a>';
  420. } else {
  421. $url = JRoute::_("index.php?option=com_fabrik&Itemid=$Itemid&$action=form&tableid=$element->table_id&fabrik=$element->form_id&$linkKey" . "[value]=$val");
  422. $group[$i]->$key = "<a href=\"$url\">" . JText::_('Add') . "</a>";
  423. }
  424. }
  425. }
  426. $f ++;
  427. }
  428. }
  429. }
  430. }
  431. /**
  432. * add a custom link to the element data
  433. *
  434. * @param string element $data
  435. * @param object element
  436. * @param object of all row data
  437. */
  438. function _addLink( $data, &$elementModel, &$row )
  439. {
  440. global $Itemid;
  441. if ($this->_outPutFormat == 'csv') {
  442. return $data;
  443. }
  444. $nextview = ($this->canEdit()) ? "form" : "details";
  445. $params =& $elementModel->getParams();
  446. $element =& $elementModel->getElement();
  447. $table =& $this->getTable();
  448. if ($element->link_to_detail == '1' && ( $this->canEdit() || $this->canView())) {
  449. $this->_aLinkElements = $element->name;
  450. if ($this->_postMethod == 'post') {
  451. $primaryKeyVal = $this->getKeyIndetifier( $row );
  452. if ($this->_admin) {
  453. $link = JRoute::_( "index.php?option=com_fabrik&c=form&task=$nextview&fabrik=" . $table->form_id . "$primaryKeyVal&fabrik_cursor=" . @$row->_cursor . "&fabrik_total=" . @$row->_total . "&tableid=" .$this->_id );
  454. } else {
  455. $link = JRoute::_( "index.php?option=com_fabrik&c=form&view=$nextview&Itemid=$Itemid&fabrik=" . $table->form_id . "$primaryKeyVal&fabrik_cursor=" . @$row->_cursor . "&fabrik_total=" . @$row->_total . "&tableid=" .$this->_id );
  456. }
  457. } else {
  458. $link = '#';
  459. }
  460. //try to remove any previously entered links
  461. $data = preg_replace( '/<a(.*?)>|<\/a>/', '', $data );
  462. $data = "<a class='fabrik___rowlink' href='$link'>$data</a>";
  463. } else {
  464. $customLink = $params->get( 'custom_link' );
  465. if ($customLink != '') {
  466. //$w = new FabrikWorker();
  467. //$customLink = $w->parseMessageForPlaceHolder($customLink, JArrayHelper::fromObject( $row ));
  468. $customLink = $this->parseMessageForRowHolder($customLink, JArrayHelper::fromObject( $row ));
  469. //try to remove any previously entered links
  470. $data = preg_replace( '/<a(.*?)>|<\/a>/', '', $data );
  471. $data = "<a class='fabrik___rowlink' href='$customLink'>$data</a>";
  472. }
  473. }
  474. return $data;
  475. }
  476. /**
  477. * get query to make records
  478. * @return string sql
  479. */
  480. function _buildQuery()
  481. {
  482. $query = $this->_buildQuerySelect();
  483. $query .= $this->_buildQueryJoin();
  484. $query .= $this->_buildQueryWhere();
  485. $query .= $this->_buildQueryOrder();
  486. return $query;
  487. }
  488. function _buildQuerySelect()
  489. {
  490. $form =& $this->getForm();
  491. $table =& $this->getTable();
  492. $form->getGroupsHiarachy( $this->_onlyTableData, true );
  493. $this->_getAsFields();
  494. $fields = (empty( $this->_aFields )) ? '' : implode( ", \n ", $this->_aFields ) . "\n ";
  495. if (trim( $table->db_primary_key ) != '' && ( $this->_outPutFormat == 'html' || $this->_outPutFormat == 'feed' ) ) {
  496. if ($this->isView()) {
  497. $strPKey = ''; //view dont have primary key!
  498. } else {
  499. $fields .= ", ";
  500. $strPKey = $table->db_primary_key . " AS __pk_val\n";
  501. }
  502. $query = 'SELECT DISTINCT ' . $fields . $strPKey;
  503. } else {
  504. $query = 'SELECT DISTINCT ' . trim($fields, ", \n") . "\n";
  505. }
  506. $query .= " FROM `$table->db_table_name` \n" ;
  507. return $query;
  508. }
  509. /**
  510. * get the part of the sql statement that orders the table data
  511. * @return string ordering part of sql statement
  512. */
  513. function _buildQueryOrder()
  514. {
  515. global $mainframe;
  516. $params = $this->getParams();
  517. if ($this->_outPutFormat == 'feed' )
  518. {
  519. $dateCol = $params->get( 'feed_date', '' );
  520. if( $dateCol != '' ){
  521. $this->order_dir = 'DESC';
  522. $this->order_by = $dateCol;
  523. return "\n ORDER BY `$dateCol` DESC";
  524. }
  525. }
  526. $session =& JFactory::getSession();
  527. $table =& $this->getTable();
  528. $postOrderBy = JRequest::getVar( 'orderby', '', 'post' );
  529. $postOrderBy = str_replace( ".", "___", $postOrderBy );
  530. $postOrderDir = JRequest::getVar( 'orderdir', '', 'post' );
  531. $arOrderVals = array('asc', 'desc', '-');
  532. if (in_array( $postOrderDir, $arOrderVals )) {
  533. $context = 'com_fabrik.table.'. $this->_id.'.order.'.$postOrderBy;
  534. $session->set( $context, $postOrderDir );
  535. }
  536. //build the order by statement from the session
  537. $strOrder = '';
  538. foreach ($this->_aAsFields as $field) {
  539. $field = str_replace('`', '', $field);
  540. $context = 'com_fabrik.table.'. $this->_id.'.order.'.$field;
  541. $dir = $session->get( $context );
  542. if ($dir != '' && $dir != '-' && trim( $dir ) != 'Array' ) {
  543. $field = str_replace( "___", ".", $field );
  544. if (!strstr( $field, '.' )) {
  545. $field = $table->db_table_name.'.'. $field ;
  546. }
  547. //ensure its quoted
  548. $field = explode( ".", $field );
  549. $field = "`" . $field[0] . "`.`" . $field[1] . "`";
  550. $strOrder == '' ? $strOrder = "\n ORDER BY " : $strOrder .= ',';
  551. $strOrder .= " $field $dir";
  552. }
  553. }
  554. //if nothing found in session use default ordering
  555. if ($strOrder == '' ) {
  556. if ($table->order_by != '') {
  557. $table->order_dir != ''? $dir = $table->order_dir : $dir = 'desc';
  558. $field = str_replace( "___", ".", $table->order_by );
  559. $field = explode( ".", $field );
  560. if(count($field) == 2 && $field[1] != '') {
  561. $field = "`" . $field[0] . "`.`" . $field[1] . "`";
  562. $strOrder = "\n ORDER BY $field $dir";
  563. }
  564. }
  565. }
  566. // apply group ordering
  567. $groupOrderBy = $params->get( 'group_by_order' );
  568. if ($groupOrderBy != '' && in_array( $groupOrderBy, $this->_aAsFields )) {
  569. $groupOrderDir = $this->_params->get( 'group_by_order_dir' );
  570. $strOrder == '' ? $strOrder = "\n ORDER BY " : $strOrder .= ',';
  571. $strOrder .= " `$groupOrderBy` $groupOrderDir ";
  572. }
  573. return $strOrder;
  574. }
  575. /**
  576. * get the part of the sql query that creates the joins
  577. * used when building the table's data
  578. *
  579. * @return string join sql
  580. */
  581. function _buildQueryJoin()
  582. {
  583. if (isset( $this->_joinSQL )) {
  584. return $this->_joinsSQL;
  585. }
  586. $sql = '';
  587. $joins =& $this->getJoins();
  588. $tableGroups = array();
  589. foreach ($joins as $join) {
  590. $sql .= strtoupper($join->join_type) ." JOIN `$join->table_join`" ;
  591. if ($join->table_join_alias == '') {
  592. /*$sql .= " ON `$join->table_join`.`$join->table_join_key` = " .
  593. "`$join->join_from_table`.`$join->table_key` \n";*/
  594. $sql .= " ON `$join->table_join`.`$join->table_join_key` = " .
  595. "`$join->keytable`.`$join->table_key` \n";
  596. } else {
  597. /*$sql .= " AS `" . $join->table_join_alias .
  598. "` ON `" . $join->table_join_alias . "`.`$join->table_join_key` = " .
  599. "`$join->join_from_table`.`$join->table_key` \n ";*/
  600. $sql .= " AS `" . $join->table_join_alias .
  601. "` ON `" . $join->table_join_alias . "`.`$join->table_join_key` = " .
  602. "`$join->keytable`.`$join->table_key` \n ";
  603. }
  604. }
  605. return $sql;
  606. }
  607. /**
  608. * get the part of the sql query that relates to the where statement
  609. *
  610. * @param bol $incFilters
  611. * @return string where query
  612. */
  613. function _buildQueryWhere( $incFilters = true )
  614. {
  615. if (isset( $this->_whereSQL )) {
  616. return $this->_whereSQL[$incFilters];
  617. }
  618. $aFilters =& $this->getFilterArray();
  619. $params =& $this->getParams();
  620. if (isset( $params ) && $this->_togglePreFilters == 0) {
  621. $aPrefilters = $this->getPrefilterArray( );
  622. } else {
  623. $aPrefilters = array();
  624. }
  625. $aOrSQL = array( );
  626. $aFoundOrGroupings = array( );
  627. $i = 0;
  628. $aSQLBits = array();
  629. if (is_array( $aFilters )) {
  630. /* stores sql for or statements */
  631. $c = 0;
  632. foreach ($aFilters as $key=>$val) {
  633. /*work through or columns first to build sql ( col = val or col = val...)
  634. * then remove them from the rest of the array
  635. */
  636. if ( isset( $val['aOrCols'] ) ) {
  637. $aOrColumns = $val['aOrCols'] ;
  638. $filterVal = isset( $val['value'] ) ? $val['value'] : '';
  639. /* check if we've already performed it elsewhere */
  640. $done = false;
  641. foreach ($aFoundOrGroupings as $aFoundOrGroupSet) {
  642. $a = filter_unused( $aFoundOrGroupSet, $aOrColumns );
  643. if (empty( $a )){
  644. $done = true;
  645. }
  646. }
  647. if (!$done) {
  648. /*
  649. * ok we havent processed this group -
  650. * lets add it to the groups the we have processed
  651. */
  652. $aFoundOrGroupings[] = $aOrColumns;
  653. /*
  654. *now lets build that query string!
  655. */
  656. $orSql ='(';
  657. foreach ($aOrColumns as $col) {
  658. $col = FabrikWorker::getDbSafeName( $col );
  659. $orSql .= "`$col` = '$filterVal' OR " ;
  660. }
  661. $orSql = substr($orSql, 0, strlen($orSql)-3) . ')';
  662. $aOrSQL[] = $orSql;
  663. }
  664. /* ok, even if its been done before we still need to remove it from the filter array */
  665. unset ( $aFilters[$key] );
  666. $c++;
  667. }
  668. }
  669. foreach ($aFilters as $key=>$val) {
  670. $filterType = isset( $val['type'] ) ? $val['type']: 'dropdown';
  671. $filterVal = isset( $val['value'] ) ? $val['value'] : '';
  672. $filterExactMatch = isset( $val['match'] ) ? $val['match'] : '';
  673. $fullWordsOnly = isset( $val['full_words_only'] )? $val['full_words_only'] : '0';
  674. if (array_key_exists( $key, $aPrefilters )){
  675. if (array_key_exists( 'sqlCond' , $aPrefilters[$key] )) {
  676. $sqlCond = "( " .$val['sqlCond'] . " AND " . $aPrefilters[$key]['sqlCond'] . " )";
  677. } else {
  678. //$$$rob used for prefilter and table - "Tables with database join elements linking to this table " pointing to same prefilter opt
  679. $sqlCond = "( " .$val['sqlCond'];
  680. foreach ($aPrefilters[$key] as $tmpC) {
  681. $sqlCond .= " AND " . $tmpC['sqlCond'];
  682. }
  683. $sqlCond .= " )";
  684. }
  685. unset( $aPrefilters[$key] );
  686. } else {
  687. $sqlCond = $val['sqlCond'];
  688. }
  689. if ( $filterVal != "" ) {
  690. $aSQLBits[] = " AND ";
  691. $aSQLBits[] = $sqlCond;
  692. $i ++;
  693. }
  694. }
  695. }
  696. //add in any prefiltres not duplicated by filters
  697. //put them at the beginning of query as well
  698. $aSQLBits2 = array();
  699. foreach ($aPrefilters as $key=>$ar) {
  700. if ($key !== '') {
  701. $aSQLBits2[] = $ar['concat'];
  702. $aSQLBits2[] = $ar['sqlCond'];
  703. }
  704. }
  705. // $$$rob work out the where statment minus any filters (so only include prefilters)
  706. // this is needed to ensure that the filter drop downs contain the correct info.
  707. $sqlNoFilter = '';
  708. if (!empty( $aSQLBits2 )) {
  709. $aSQLBits2[0] = "WHERE";
  710. $sqlNoFilter .= implode( ' ', $aSQLBits2 );
  711. if (count( $aOrSQL ) > 0) {
  712. if (empty( $aSQLBits2 )) {
  713. $sqlNoFilter .= " WHERE " . implode( ' AND ', $aOrSQL );
  714. } else {
  715. $sqlNoFilter .= ' AND ' . implode( ' AND ', $aOrSQL );
  716. }
  717. }
  718. }
  719. //apply advanced filter query
  720. $advancedFilter = JRequest::getVar('advancedFilterContainer', array('value' => ''), 'default', 'none', 2);
  721. $sql = '';
  722. $aSQLBits = array_merge( $aSQLBits2, $aSQLBits );
  723. if (!empty( $aSQLBits )) {
  724. $aSQLBits[0] = "WHERE";
  725. $sql .= implode( ' ', $aSQLBits );
  726. if (count( $aOrSQL ) > 0) {
  727. if (empty( $aSQLBits )) {
  728. $sql .= " WHERE " . implode( ' AND ', $aOrSQL );
  729. } else {
  730. $sql .= ' AND ' . implode( ' AND ', $aOrSQL );
  731. }
  732. }
  733. }
  734. if ($advancedFilter['value'] != '') {
  735. $sql .= empty( $sql ) ? " WHERE " : " AND ";
  736. $sql .= trim( trim( $advancedFilter['value'], "AND" ), "OR" );
  737. }
  738. $this->_whereSQL = array( '0'=>$sqlNoFilter, '1'=>$sql );
  739. return $this->_whereSQL[$incFilters];
  740. }
  741. /**
  742. * get the part of the table sql statement that selects which fields to load
  743. * (both this_>_aASFields and this->_aFields)
  744. *
  745. * @return array field names to select in getelement data sql query
  746. */
  747. function &_getAsFields()
  748. {
  749. if (!is_null( $this->_aAsFields )) {
  750. return $this->_aAsFields;
  751. }
  752. $form =& $this->getForm();
  753. $table =& $this->getTable();
  754. $aJoinObjs =& $this->getJoins();
  755. $this->_aAsFields = array();
  756. $this->_aFields = array();
  757. $this->_temp_db_key_addded = false;
  758. foreach ($form->_groups as $groupModel) {
  759. $table_name = $table->db_table_name;
  760. $group =& $groupModel->getGroup();
  761. if ($group->is_join) {
  762. foreach ($aJoinObjs as $join) {
  763. //also ignore any joins that are elements
  764. if (array_key_exists( 'group_id', $join ) && $join->group_id == $group->id && $join->element_id == 0 ) {
  765. $table_name = $join->table_join;
  766. }
  767. }
  768. }
  769. foreach ($groupModel->_aElements as $elementModel) {
  770. if (!$this->_onlyTableData || $elementModel->inTableFields( $this )) {
  771. $method = "getAsField_" . $this->_outPutFormat;
  772. if (!method_exists( $elementModel, $method )) {
  773. $method = "getAsField_html";
  774. }
  775. $elementModel->$method( $this->_aFields, $this->_aAsFields, $table_name );
  776. }
  777. }
  778. }
  779. //temporaraily add in the db key so that the edit links work, must remove it before final return
  780. // of getData();
  781. if (!$this->isView()) {
  782. if (!$this->_temp_db_key_addded && $table->db_primary_key != '') {
  783. $str = str_replace( '___', '.', $table->db_primary_key ) . " AS " . str_replace( '.', '___', $table->db_primary_key );
  784. //if we are quoting the priamry key in the db then we need to remove these quotes
  785. $str = str_replace( '`___`', '___', $str );
  786. $this->_aFields[] = $str;
  787. $this->_aAsFields[] = $table->db_primary_key;
  788. }
  789. }
  790. //for raw data in packages
  791. if ($this->_outPutFormat == 'raw') {
  792. $str = str_replace( '___', '.', $table->db_primary_key ) . " AS __pk_val";
  793. $str = str_replace( '`___`', '___', $str );
  794. $this->_aFields[] = $str;
  795. }
  796. //end
  797. $this->_group_by_added = false;
  798. //if the group by element isnt in the fields add it (otherwise group by wont work)
  799. if (!in_array( $table->group_by, $this->_aAsFields ) && trim( $table->group_by ) != '') {
  800. $this->_aFields[] = str_replace( '___', '.', $table->group_by ) . " AS `$table->group_by`";
  801. $this->_aAsFields[] = $table->group_by;
  802. $this->_group_by_added = true;
  803. }
  804. return $this->_aAsFields;
  805. }
  806. /**
  807. * checks if the params object has been created and if not creates and returns it
  808. * @return object params
  809. */
  810. function &getParams()
  811. {
  812. $table =& $this->getTable();
  813. if (!isset( $this->_params )) {
  814. $this->_params = &new fabrikParams( $table->attribs, JPATH_SITE . '/administrator/components/com_fabrik/models/table.xml', 'component' );
  815. }
  816. return $this->_params;
  817. }
  818. /**
  819. * Method to set the table id
  820. *
  821. * @access public
  822. * @param int table ID number
  823. */
  824. function setId( $id )
  825. {
  826. $this->_id = $id;
  827. }
  828. /**
  829. * sets the instances admin state
  830. * @param bol admin state
  831. */
  832. function setAdmin( $bol )
  833. {
  834. $this->_admin = $bol;
  835. }
  836. /**
  837. * get the table object for the models _id
  838. *
  839. * @return object table
  840. */
  841. function &getTable()
  842. {
  843. if (is_null( $this->_table )) {
  844. JTable::addIncludePath( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_fabrik'.DS.'tables' );
  845. $row = JTable::getInstance( 'table', 'Table' );
  846. $row->load( $this->_id );
  847. $this->_table =& $row;
  848. }
  849. return $this->_table;
  850. }
  851. /**
  852. * load the database associated with the table
  853. *@return object database
  854. */
  855. function &getDb()
  856. {
  857. if (!isset( $this->_oConnDB )) {
  858. $cnn =& $this->getConnection();
  859. if (!is_object( $cnn )) {
  860. return JError::raiseError( 500, JText::_( 'Fabrik was unable to load the database object for this table' ) );
  861. }
  862. $this->_oConnDB =& $cnn->getDb( );
  863. }
  864. return $this->_oConnDB;
  865. }
  866. /**
  867. * function get the tables connection object
  868. * sets $this->_oConn to the tables connection
  869. * @return object connection
  870. */
  871. function &getConnection( )
  872. {
  873. $config =& JFactory::getConfig();
  874. if (!isset( $this->_oConn )) {
  875. $table =& $this->getTable();
  876. $connectionModel =& JModel::getInstance( 'connection', 'FabrikModel' );
  877. $connId = ( is_null( $table->connection_id ) ) ? JRequest::getVar( 'connection_id', null ) : $table->connection_id;
  878. $connectionModel->setId( $connId );
  879. if ($connId == '' || is_null( $connId ) || $connId == '-1' ){ //-1 for creating new table
  880. $connectionModel->loadDefaultConnection();
  881. $connectionModel->setId( $connectionModel->_connection->id );
  882. }
  883. $connection =& $connectionModel->getConnection( );
  884. // if its the default connection then load from the
  885. // config file
  886. if ($connectionModel->isDefault() ){
  887. $connection->host = $config->getValue('config.host');
  888. $connection->user = $config->getValue('config.user');
  889. $connection->password = $config->getValue('config.password');
  890. $connection->database = $config->getValue('config.db');
  891. }
  892. $this->_oConn =& $connectionModel;
  893. }
  894. return $this->_oConn;
  895. }
  896. /**
  897. * is the table published
  898. *
  899. * @return bol published state
  900. */
  901. function canPublish()
  902. {
  903. $table =& $this->getTable();
  904. global $mainframe;
  905. $db =& JFactory::getDBO();
  906. if (method_exists( $db, 'getNullDate' )) {
  907. $nullDate = $db->getNullDate( );
  908. } else {
  909. $nullDate = $this->getNullDate( );
  910. }
  911. $publishup =& JFactory::getDate($table->publish_up, $mainframe->getCfg('offset'));
  912. $publishup = $publishup->toUnix();
  913. $publishdown =& JFactory::getDate($table->publish_down, $mainframe->getCfg('offset'));
  914. $publishdown = $publishdown->toUnix();
  915. $jnow =& JFactory::getDate();
  916. $now = $jnow->toUnix();
  917. if ($table->state == '1') {
  918. if ($now >= $publishup || $table->publish_up == '' || $table->publish_up == $nullDate) {
  919. if ($now <= $publishdown || $table->publish_down == '' || $table->publish_down == $nullDate) {
  920. return true;
  921. }
  922. }
  923. }
  924. return false;
  925. return $table->state;
  926. }
  927. /**
  928. *
  929. */
  930. function canEmpty()
  931. {
  932. $user =& JFactory::getUser();
  933. $acl =& JFactory::getACL();
  934. $table =& $this->getTable();
  935. $params =& $this->getParams();
  936. $a = $params->get( 'allow_drop', 0 );
  937. if ($a == '29'|| $a == ''|| $a == 0) {
  938. $this->_access->allow_drop = true;
  939. } else {
  940. if (!is_object( $this->_access ) || !array_key_exists( 'allow_drop', $this->_access )) {
  941. $groupNames =& FabrikWorker::getACLGroups( $a );
  942. foreach ($groupNames as $name) {
  943. FabrikWorker::setACL( 'action', 'allow_drop', 'fabrik', $name, 'components', null );
  944. }
  945. if ($acl->acl_check( 'action', 'allow_drop', 'fabrik', $user->get(' usertype' ), 'components', null )) {
  946. $this->_access->allow_drop = true;
  947. } else {
  948. $this->_access->allow_drop = false;
  949. }
  950. }
  951. }
  952. return $this->_access->allow_drop;
  953. }
  954. /**
  955. * check if the user can view the detailed records
  956. *
  957. * @return bol
  958. */
  959. function canViewDetails()
  960. {
  961. $user =& JFactory::getUser();
  962. $acl =& JFactory::getACL();
  963. $table =& $this->getTable();
  964. $params =& $this->getParams();
  965. $a = $params->get( 'allow_view_details', 0 );
  966. if ($a == '29'|| $a == ''|| $a == 0) {
  967. $this->_access->viewdetails = true;
  968. } else {
  969. if (!is_object( $this->_access ) || !array_key_exists( 'viewdetails', $this->_access )) {
  970. $groupNames =& FabrikWorker::getACLGroups( $a );
  971. foreach ($groupNames as $name) {
  972. FabrikWorker::setACL( 'action', 'viewdetails', 'fabrik', $name, 'components', null );
  973. }
  974. if ($acl->acl_check( 'action', 'viewdetails', 'fabrik', $user->get(' usertype' ), 'components', null )) {
  975. $this->_access->viewdetails = true;
  976. } else {
  977. $this->_access->viewdetails = false;
  978. }
  979. }
  980. }
  981. return $this->_access->viewdetails;
  982. }
  983. /**
  984. * checks user access for editing records
  985. *
  986. * @return bol access allowed
  987. */
  988. function canEdit()
  989. {
  990. $user =& JFactory::getUser();
  991. $acl =& JFactory::getACL();
  992. $table =& $this->getTable();
  993. $params =& $this->getParams();
  994. $a = $params->get( 'allow_edit_details', 25 );
  995. if ($a == '29'|| $a == ''|| $a == 0) {
  996. $this->_access->edit = true;
  997. } else {
  998. if(!is_object($this->_access) || !array_key_exists('edit', $this->_access)){
  999. $groupNames = FabrikWorker::getACLGroups( $a );
  1000. foreach ($groupNames as $name) {
  1001. FabrikWorker::setACL( 'action', 'edit', 'fabrik', $name, 'components', null );
  1002. }
  1003. if ($acl->acl_check( 'action', 'edit', 'fabrik', $user->get( 'usertype' ), 'components', null )) {
  1004. $this->_access->edit = true;
  1005. } else {
  1006. $this->_access->edit = false;
  1007. }
  1008. }
  1009. }
  1010. return $this->_access->edit;
  1011. }
  1012. /**
  1013. * checks user access for deleting records
  1014. *
  1015. * @return bol access allowed
  1016. */
  1017. function canDelete()
  1018. {
  1019. $user = &JFactory::getUser();
  1020. $acl =& JFactory::getACL();
  1021. $table =& $this->getTable();
  1022. $params =& $this->getParams();
  1023. $a = $params->get( 'allow_delete', 25 );
  1024. if ($a == '29'|| $a == '' || $a == 0 ){
  1025. $this->_access->delete = true;
  1026. } else {
  1027. if (!is_object( $this->_access ) || !array_key_exists( 'delete', $this->_access )) {
  1028. $groupNames = FabrikWorker::getACLGroups( $a );
  1029. foreach ($groupNames as $name) {
  1030. FabrikWorker::setACL( 'action', 'delete', 'fabrik', $name, 'components', null );
  1031. }
  1032. if ($acl->acl_check( 'action', 'delete', 'fabrik', $user->get( 'usertype' ), 'components', null )) {
  1033. $this->_access->delete = true;
  1034. } else {
  1035. $this->_access->delete = false;
  1036. }
  1037. }
  1038. }
  1039. return $this->_access->delete;
  1040. }
  1041. /**
  1042. * checks user access for adding records
  1043. *
  1044. * @return bol access allowed
  1045. */
  1046. function canAdd()
  1047. {
  1048. $user =& JFactory::getUser();
  1049. $acl =& JFactory::getACL();
  1050. $params =& $this->getParams();
  1051. $table =& $this->getTable();
  1052. $a = $params->get( 'allow_add', 25 );
  1053. if ($a == '29' || $a == ''|| $a == 0){
  1054. $this->_access->add = true;
  1055. } else {
  1056. if (!is_object( $this->_access ) || !array_key_exists( 'add', $this->_access )) {
  1057. $groupNames = FabrikWorker::getACLGroups( $a );
  1058. foreach ($groupNames as $name) {
  1059. FabrikWorker::setACL( 'action', 'add', 'fabrik', $name, 'components', null );
  1060. }
  1061. if ($acl->acl_check( 'action', 'add', 'fabrik', $user->get( 'usertype' ), 'components', null )) {
  1062. $this->_access->add = true;
  1063. } else {
  1064. $this->_access->add = false;
  1065. }
  1066. }
  1067. }
  1068. return $this->_access->add;
  1069. }
  1070. /**
  1071. * check use can view the table
  1072. * @return bol can view or not
  1073. */
  1074. function canView( ){
  1075. $user =& JFactory::getUser();
  1076. $acl =& JFactory::getACL();
  1077. $table =& $this->getTable();
  1078. if ($table->access == '29'|| $table->access == '' || $table->access == 0) {
  1079. $this->_access->view = true;
  1080. } else {
  1081. if (!is_object($this->_access) || !array_key_exists('view', $this->_access)) {
  1082. $groupNames = FabrikWorker::getACLGroups( $table->access );
  1083. foreach ($groupNames as $name) {
  1084. FabrikWorker::setACL( 'action', 'view', 'fabrik', $name, 'components', null );
  1085. }
  1086. if ($acl->acl_check( 'action', 'view', 'fabrik', $user->get('usertype'), 'components', null )) {
  1087. $this->_access->view = true;
  1088. } else {
  1089. $this->_access->view = false;
  1090. }
  1091. }
  1092. }
  1093. return $this->_access->view;
  1094. }
  1095. /**
  1096. * load the table from the form_id value
  1097. * @param int $formId
  1098. * @return object table row
  1099. */
  1100. function loadFromFormId( $formId ){
  1101. JTable::addIncludePath( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_fabrik'.DS.'table' );
  1102. $row = JTable::getInstance( 'table', 'Table' );
  1103. $origKey = $row->_tbl_key;
  1104. $row->_tbl_key = "form_id";
  1105. $row->load( $formId );
  1106. $this->_table = $row;
  1107. $row->_tbl_key = $origKey;
  1108. $this->setId( $row->id );
  1109. return $row;
  1110. }
  1111. /**
  1112. * alias to loadJoins - should be used instead
  1113. * @return array join objects (table rows - not table objects or models)
  1114. */
  1115. function &getJoins()
  1116. {
  1117. if (!isset( $this->_aJoins )) {
  1118. $form =& $this->getForm();
  1119. $form->getGroupsHiarachy( false );
  1120. $ids = $form->getElementIds();
  1121. $table =& $this->getTable();
  1122. $db =& JFactory::getDBO();
  1123. $sql = "SELECT * FROM #__fabrik_joins WHERE table_id = '$this->_id'";
  1124. if (!empty( $ids )) {
  1125. $sql .= " OR element_id IN ( " . implode(", ", $ids) .")";
  1126. }
  1127. //maybe we will have to order by element_id asc to ensure that table joins are loaded
  1128. //before element joins (if an element join is in a table join then its 'join_from_table' key needs to be updated
  1129. $sql .= " ORDER BY id";
  1130. $db->setQuery( $sql );
  1131. $this->_aJoins = $db->loadObjectList( );
  1132. if ($db->getErrorNum()) {
  1133. JError::raiseError( 500, $db->stderr());
  1134. }
  1135. $aliases = array();
  1136. $tableGroups = array();
  1137. foreach ($this->_aJoins as $join) {
  1138. //if their 'table_join' has been used then update with an alais
  1139. if (in_array( $join->table_join, $aliases )) {
  1140. $base = $join->table_join;
  1141. $a = $base;
  1142. $c = 0;
  1143. while (in_array( $a, $aliases )) {
  1144. $a = "{$base}_{$c}";
  1145. $c ++;
  1146. }
  1147. $join->table_join_alias = $a;
  1148. } else {
  1149. $join->table_join_alias = $join->table_join;
  1150. }
  1151. $aliases[] = $join->table_join;
  1152. //if they are element joins add in this tables name as the calling joining table.
  1153. if ($join->join_from_table == '') {
  1154. $join->join_from_table = $table->db_table_name;
  1155. }
  1156. // test case:
  1157. /*
  1158. * you have a talbe that joins to a 2nd table
  1159. * in that 2nd table there is a database join element
  1160. * that 2nd elements key needs to point to the 2nd tables name and not the first
  1161. *
  1162. * e.g. when you want to create a n-n relationship
  1163. *
  1164. * events -> (table join) events_artists -> (element join) artist
  1165. */
  1166. $join->keytable = $join->join_from_table;
  1167. if (!array_key_exists( $join->group_id, $tableGroups )) {
  1168. $tableGroups[$join->group_id] = $join->table_join_alias;
  1169. } else {
  1170. if ($join->element_id != 0) {
  1171. $join->keytable = $tableGroups[$join->group_id];
  1172. }
  1173. }
  1174. }
  1175. }
  1176. return $this->_aJoins;
  1177. }
  1178. /**
  1179. * gets the field names for the given table
  1180. * @param string table name
  1181. * @return array table fields
  1182. */
  1183. function getDBFields( $tbl = null )
  1184. {
  1185. if (is_null( $tbl )) {
  1186. $table =& $this->getTable();
  1187. $tbl = $table->db_table_name ;
  1188. }
  1189. if (!strstr( $tbl, '`' )) {
  1190. $tbl = "`$tbl`";
  1191. }
  1192. if (!isset( $this->_dbFields[$tbl] ) ){
  1193. $db =& $this->getDb();
  1194. $db->setQuery( "DESCRIBE $tbl" );
  1195. $this->_dbFields[$tbl] = $db->loadObjectList( );
  1196. }
  1197. return $this->_dbFields[$tbl];
  1198. }
  1199. /**
  1200. * add or update a database column via sql
  1201. * @param object element plugin
  1202. * @param bol is new
  1203. * @param string origional field name
  1204. */
  1205. function alterStructure( &$elementModel, $new, $origColName=null )
  1206. {
  1207. $db =& JFactory::getDBO();
  1208. $element =& $elementModel->getElement();
  1209. $pluginManager =& JModel::getInstance( 'Pluginmanager', 'FabrikModel' );
  1210. $basePlugIn =& $pluginManager->getPlugIn( $element->plugin, 'element' );
  1211. $fbConfig = JComponentHelper::getParams( 'com_fabrik' );
  1212. $fabrikDb =$this->getDb();
  1213. $table =& $this->getTable();
  1214. $tableName = $table->db_table_name;
  1215. $objtype = $basePlugIn->getFieldDescription();
  1216. $dbdescriptions = $this->getDBFields( $tableName );
  1217. if (!$fbConfig->get( 'fbConf_alter_existing_db_cols' )) {
  1218. foreach ($dbdescriptions as $f) {
  1219. if ($f->Field == $origColName) {
  1220. $objtype = $f->Type;
  1221. }
  1222. }
  1223. }
  1224. if (!is_null( $objtype )) {
  1225. foreach ($dbdescriptions as $dbdescription) {
  1226. $fieldname = $dbdescription->Field;
  1227. $exitingfields[] = strtolower($fieldname);
  1228. }
  1229. $lastfield = $fieldname;
  1230. if (in_array( strtolower($element->name), $exitingfields )) {
  1231. return ;
  1232. }
  1233. FabrikString::safeColName( $element->name );
  1234. FabrikString::safeColName( $tableName );
  1235. FabrikString::safeColName( $lastfield );
  1236. if (( $new && !in_array( strtolower($element->name), $exitingfields) ) || !in_array( strtolower($origColName), $exitingfields )) {
  1237. $sql = "ALTER TABLE $tableName ADD COLUMN $element->name $objtype AFTER $lastfield";
  1238. } else {
  1239. if ($origColName == null) {
  1240. $origColName = $element->name;
  1241. }
  1242. FabrikString::safeColName( $origColName );
  1243. $sql = "ALTER TABLE $tableName CHANGE $origColName " . $element->name ;
  1244. $sql .= " $objtype";
  1245. }
  1246. $fabrikDb->setQuery( $sql );
  1247. if (!$fabrikDb->query( )) {
  1248. return JError::raiseError( 500, 'alter structure: ' . $fabrikDb->getErrorMsg( ));
  1249. }
  1250. $this->createCacheQuery();
  1251. }
  1252. return true;
  1253. }
  1254. /**
  1255. * if not loaded this loads in the table's form object
  1256. * also binds a reference of the table to the form.
  1257. * @return object form model with form table loaded
  1258. */
  1259. function &getForm()
  1260. {
  1261. if (is_null( $this->_oForm )) {
  1262. $this->_oForm =& JModel::getInstance( 'Form', 'FabrikModel' );
  1263. $table =& $this->getTable();
  1264. $this->_oForm->setId( $table->form_id );
  1265. $this->_oForm->getForm();
  1266. $this->_oForm->setTableModel( $this );
  1267. //ensure joins are loaded
  1268. }
  1269. return $this->_oForm;
  1270. }
  1271. /**
  1272. * tests if the table is in fact a view
  1273. * @returns true if table is a view
  1274. */
  1275. function isView()
  1276. {
  1277. $params =& $this->getParams();
  1278. $isview = $params->get('isview', null);
  1279. if (is_null($isview)) {
  1280. $db =& JFactory::getDBO();
  1281. $table =& $this->getTable();
  1282. $cn = $this->getConnection();
  1283. $c = $cn->getConnection();
  1284. $dbname = $c->database;
  1285. $sql = "show table status like '$table->db_table_name'";
  1286. $sql = " select table_name, table_type, engine from INFORMATION_SCHEMA.tables ".
  1287. "where table_name = '$table->db_table_name' and table_type = 'view' and table_schema = '$dbname'";
  1288. $db->setQuery( $sql );
  1289. $row = $db->loadObjectList();
  1290. $isview = empty($row) ? false : true;
  1291. $intisview = $isview ? 1 : 0;
  1292. //store and save param for following tests
  1293. $params->set('isview', $isview);
  1294. $table->attribs .= "\nisview=$intisview\n";
  1295. $table->store();
  1296. }
  1297. return $isview;
  1298. }
  1299. /** DEPRECIATED SHOULD NOT BE NEEDED NOW
  1300. function _loadJoinOnce( $join )
  1301. {
  1302. return $join->table_join;
  1303. }
  1304. **/
  1305. /**
  1306. * filter array is created in $this->_loadFilterArray
  1307. *@return array filters
  1308. */
  1309. function &getFilterArray( )
  1310. {
  1311. if (isset( $this->_aFilter )) {
  1312. return $this->_aFilter;
  1313. }
  1314. $user = &JFactory::getUser();
  1315. $request = $this->getRequestData();
  1316. $this->_aFilter = array();
  1317. $this->_aPrefilters =& $this->getPrefilterArray();
  1318. $form =& $this->getForm();
  1319. $filterCondSQL = '';
  1320. $aPostFilters = array();
  1321. $useFullName = JRequest::getBool( 'fullName', 1 );
  1322. if (is_null( $form->_groups )) {
  1323. $form->getGroupsHiarachy();
  1324. }
  1325. foreach ($form->_groups as $groupModel) {
  1326. $group =& $groupModel->getGroup();
  1327. foreach ($groupModel->_aElements as $elementModel) {
  1328. $element =& $elementModel->getElement();
  1329. $thisData = $this->_aData;
  1330. if ($group->is_join) {
  1331. if (@array_key_exists( 'join', $request ) && @is_array( $request['join'][$group->join_id] )) {
  1332. $thisData = $this->_aData['join'][$group->join_id];
  1333. }
  1334. $key = $elementModel->getFilterFullName( false, true, false );
  1335. } else {
  1336. $key = $elementModel->getFilterFullName( true, true, false );
  1337. }
  1338. $dbKey = str_replace( "___", ".", $key );
  1339. $dbKey = FabrikWorker::getDbSafeName( $dbKey );
  1340. if (array_key_exists( $key, $request )) {
  1341. $safeKey = FabrikWorker::getDbSafeName( $dbKey );
  1342. $arr = $elementModel->getFilterConditionSQL( $request[$key], $this->_aFilter, $safeKey, $key );
  1343. $arr['no-filter-setup'] = ($element->filter_type == '') ? 1 : 0;
  1344. $arr['ellabel'] = $element->label;
  1345. if (!empty( $arr['sqlCond'] )) {
  1346. $sqlCond = "( " . $arr['sqlCond'] ;

Large files files are truncated, but you can click here to view the full file