forked from pollen8/fabrik
-
Notifications
You must be signed in to change notification settings - Fork 381
/
databasejoin.php
3875 lines (3392 loc) · 106 KB
/
databasejoin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Database Join Element
*
* @package Joomla.Plugin
* @subpackage Fabrik.element.databasejoin
* @copyright Copyright (C) 2005-2015 fabrikar.com - All rights reserved.
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
*/
// No direct access
defined('_JEXEC') or die('Restricted access');
use \Joomla\Registry\Registry;
use \Joomla\Utilities\ArrayHelper;
/**
* Plugin element to render list of data looked up from a database table
* Can render as checkboxes, radio buttons, select lists, multi select lists and auto-complete
*
* @package Joomla.Plugin
* @subpackage Fabrik.element.databasejoin
* @since 3.0
*/
class PlgFabrik_ElementDatabasejoin extends PlgFabrik_ElementList
{
/**
* connection
*
* @var FabrikFEModelConnection
*/
protected $cn = null;
protected $joinDb = null;
/**
* Created in getJoin
*
* @var FabrikFEModelJoin
*/
protected $join = null;
/**
* Simple join query
*
* @var array
*/
protected $sql = array();
/**
* Option values
*
* @var array
*/
protected $optionVals = array();
/**
* Linked form data
*
* @var array
*/
protected $linkedForms = null;
/**
* Additional where for auto-complete query
*
* @var string
*/
public $autocomplete_where = '';
/**
* Name of the join db to connect to
*
* @var string
*/
protected $dbname = null;
/**
* J Parameter name for the field containing the cdd label value
*
* @var string
*/
protected $labelParam = 'join_val_column';
/**
* J Parameter name for the field containing the concat label
*
* @var string
*/
protected $concatLabelParam = 'join_val_column_concat';
/**
* The value's required format (int/string/json/array/object)
*
* @since 3.1b2
*
* @var string
*/
protected $valueFormat = 'array';
/**
* @var string
*/
protected $orderBy = '';
/**
* Create the SQL select 'name AS alias' segment for list/form queries
*
* @param array &$aFields array of element names
* @param array &$aAsFields array of 'name AS alias' fields
* @param array $opts options
*
* @return void
*/
public function getAsField_html(&$aFields, &$aAsFields, $opts = array())
{
if ($this->isJoin())
{
// $$$ rob was commented out - but meant that the SELECT GROUP_CONCAT sub-query was never user
return parent::getAsField_html($aFields, $aAsFields, $opts);
}
$table = $this->actualTableName();
$params = $this->getParams();
$db = FabrikWorker::getDbo();
$listModel = $this->getlistModel();
$element = $this->getElement();
$connection = $listModel->getConnection();
// Make sure same connection as this table
$fullElName = FArrayHelper::getValue($opts, 'alias', $table . '___' . $element->name);
if ($params->get('join_conn_id') == $connection->get('id') || $element->plugin != 'databasejoin')
{
$join = $this->getJoin();
if (!$join)
{
return false;
}
$tables = $this->getFormModel()->getLinkedFabrikLists($params->get('join_db_name'));
/* store unjoined values as well (used in non-join group table views)
* this wasn't working for test case:
* events -> (db join) event_artists -> el join (artist)
* $$$ rob in csv import keytable not set
* $$$ hugh - if keytable isn't set, the safeColName blows up!
* Trying to debug issue with linked join elements, which don't get detected by
* getJoins or getJoin 'cos element ID doesn't match element_id in fabrik_joins
*$k = isset($join->keytable) ? $join->keytable : $join->join_from_table;
*$k = FabrikString::safeColName("`$join->keytable`.`$element->name`");
*/
$keyTable = isset($join->keytable) ? $join->keytable : $join->join_from_table;
$k = FabrikString::safeColName($keyTable . '.' . $element->name);
$k2 = $this->getJoinLabelColumn();
if (FArrayHelper::getValue($opts, 'inc_raw', true))
{
$aFields[] = $k . ' AS ' . $db->qn($fullElName . '_raw');
$aAsFields[] = $db->qn($fullElName . '_raw');
}
$aFields[] = $k2 . ' AS ' . $db->qn($fullElName);
$aAsFields[] = $db->qn($fullElName);
}
else
{
$aFields[] = $db->qn($table . '.' . $element->name) . ' AS ' . $db->qn($fullElName);
$aAsFields[] = $db->qn($fullElName);
}
}
/**
* Get the field name to use in the list's slug url
*
* @param bool $raw Use raw value (true) or label (false)
*
* @since 3.0.6
*
* @return string
*/
public function getSlugName($raw = false)
{
return $raw ? parent::getSlugName($raw) : $this->getJoinLabelColumn();
}
/**
* Get raw column name
*
* @param bool $useStep use step in name
*
* @return string
*/
public function getRawColumn($useStep = true)
{
$join = $this->getJoin();
if (!$join)
{
return;
}
$element = $this->getElement();
$k = isset($join->keytable) ? $join->keytable : $join->join_from_table;
$name = $element->name . '_raw';
return $useStep ? $k . '___' . $name : FabrikString::safeColName($k . '.' . $name);
}
/**
* Create an array of label/values which will be used to populate the elements filter dropdown
* returns only data found in the table you are filtering on
*
* @param bool $normal do we render as a normal filter or as an advanced search filter
* @param string $tableName table name to use - defaults to element's current table
* @param string $label field to use, defaults to element name
* @param string $id field to use, defaults to element name
* @param bool $incjoin include join
*
* @return array filter value and labels
*/
protected function filterValueList_Exact($normal, $tableName = '', $label = '', $id = '', $incjoin = true)
{
if ($this->isJoin())
{
$fbConfig = JComponentHelper::getParams('com_fabrik');
$limit = $fbConfig->get('filter_list_max', 100);
$rows = array_values($this->checkboxRows(null, null, null, null, 0, $limit));
}
else
{
// Autocomplete with concat label was not working if we called the parent method
if ($this->app->input->get('method') === 'autocomplete_options')
{
$data = array();
$opts = array();
$v = $this->app->input->get('value', '', 'string');
/*
* $$$ hugh (and Joe) - added 'autocomplete_how', currently just "starts_with" or "contains"
* default to "contains" for backward compat.
* http://fabrikar.com/forums/showthread.php?p=165192&posted=1#post165192
*/
$params = $this->getParams();
$this->autocomplete_where = $this->_autocompleteWhere($params->get('dbjoin_autocomplete_how', 'contains'), $label, $v);
$rows = $this->_getOptionVals($data, 0, true, $opts);
}
else
{
$rows = parent::filterValueList_Exact($normal, $tableName, $label, $id, $incjoin);
}
}
return $rows;
}
/**
* Get the field name to use as the column that contains the join's label data
*
* @param bool $useStep use step in element name
*
* @return string join label column either returns concat statement or quotes `tablename`.`elementname`
*/
public function getJoinLabelColumn($useStep = false)
{
if (!isset($this->joinLabelCols))
{
$this->joinLabelCols = array();
}
if (array_key_exists((int) $useStep, $this->joinLabelCols))
{
return $this->joinLabelCols[$useStep];
}
$params = $this->getParams();
$db = $this->getDb();
$join = $this->getJoin();
/**
* $$$ hugh - bandaid for inlineedit, problem where $join isn't loaded, as per comments in getJoin().
* for now, just avoid this code if $join isn't an object.
*/
if (is_object($join) && ($params->get($this->concatLabelParam) != ''))
{
if ($this->app->input->get('override_join_val_column_concat') != 1)
{
$val = $this->parseThisTable($params->get($this->concatLabelParam), $join);
$w = new FabrikWorker;
$val = $w->parseMessageForPlaceHolder($val, array(), false, false, null, false);
$this->joinLabelCols[(int) $useStep] = 'CONCAT_WS(\'\', ' . $val . ')';
return 'CONCAT_WS(\'\', ' . $val . ')';
}
else
{
/*
* A boolean search is in progress - we can't use concat might need to do something
* else here (http://fabrikar.com/forums/index.php?threads/search-plugin-sql-error.35177/)
*/
}
}
$label = $this->getJoinLabel();
// Depending on the plugin getJoinLabel() returns a params property or the actual name, so default to it if we cant find a property
$label = $params->get($label, $label);
$joinTableName = is_object($join) ? $join->table_join_alias : '';
$this->joinLabelCols[(int) $useStep] = $useStep ? $joinTableName . '___' . $label : $db->qn($joinTableName . '.' . $label);
return $this->joinLabelCols[(int) $useStep];
}
/**
* @param string $string Search string
* @param FabrikTableJoin $join Join table
* @param string $alias Table alias - defaults to the join->table_join_alias
*
* @return mixed
*/
protected function parseThisTable($string, $join = null, $alias = null)
{
if (is_null($join))
{
$join = $this->getJoin();
}
if (is_null($alias))
{
$alias = $join->table_join_alias;
}
return str_replace('{thistable}', FabrikString::safeNameQuote($alias), $string);
}
/**
* Get the join label name
*
* @return string
*/
protected function getJoinLabel()
{
$join = $this->getJoin();
if (!$join)
{
return false;
}
$label = FabrikString::shortColName($join->params->get('join-label'));
if ($label == '')
{
if (!$this->isJoin())
{
JError::raiseWarning(500, 'db join: Could not find the join label for ' .
$this->getElement()->get('name') . ' try unlinking and saving it');
}
$label = $this->getElement()->name;
}
return $label;
}
/**
* Get as field for csv export
* can be overwritten in the plugin class - see database join element for example
* testing to see that if the aFields are passed by reference do they update the table object?
*
* @param array &$aFields containing field sql
* @param array &$aAsFields containing field aliases
* @param string $table table name (depreciated)
*
* @return void
*/
public function getAsField_csv(&$aFields, &$aAsFields, $table = '')
{
$this->getAsField_html($aFields, $aAsFields, $table);
}
/**
* Get join row
*
* @return FabrikTableJoin Join table or false if not loaded
*/
protected function getJoin()
{
if (isset($this->join))
{
return $this->join;
}
$input = $this->app->input;
$element = $this->getElement();
if ($element->get('published') == 0)
{
return false;
}
if (!$this->getFormModel()->getForm()->record_in_database)
{
// Db join in form not recording to db
$joinModel = JModelLegacy::getInstance('Join', 'FabrikFEModel');
$this->join = $joinModel->getJoinFromKey('element_id', $element->get('id'));
return $this->join;
}
else
{
$listModel = $this->getlistModel();
$table = $listModel->getTable();
$joins = $listModel->getJoins();
foreach ($joins as $join)
{
if ($join->element_id == $element->get('id'))
{
$this->join = $join;
if (is_string($this->join->params))
{
$this->join->params = new Registry($this->join->params);
}
return $this->join;
}
}
$config = array();
$config['dbo'] = FabrikWorker::getDbo(true);
$this->join = JTable::getInstance('Join', 'FabrikTable', $config);
if ($this->join->load(array('element_id' => $element->get('id'))))
{
if (is_string($this->join->params))
{
$this->join->params = new Registry($this->join->params);
}
return $this->join;
}
}
// Try to build the join record (could have been generated from a content type import)
$data = array('id' => 0, 'group_id' => $element->get('group_id'));
$this->join = $this->updateFabrikJoin($data, $element->get('id'), $this->getDbName(), $this->getJoinValueFieldName(), $this->getLabelParamVal());
// Rebuild the join aliases.
$this->getlistModel()->getJoins();
$j = (object) $this->join->getProperties();
$j->params = (string) $j->params;
$this->getlistModel()->makeJoinAliases($j);
if ($this->join)
{
return $this->join;
}
/*
* Suppress error for inlineedit, something not quite right as groupModel::getPublishedElements() is limited by the elementid request va
* but the list model is calling getAsFields() and loading up the db join element.
* so test case would be an inline edit list with a database join element and editing anything but the db join element
*/
if (!in_array($input->get('task'), array('inlineedit', 'form.inlineedit')) && $input->get('format') !== 'raw')
{
throw new RuntimeException('unable to process db join element id:' . $element->id, 500);
}
return false;
}
/**
* Load this elements joins
*
* @return array
*/
public function getJoins()
{
$db = FabrikWorker::getDbo(true);
if (!isset($this->_aJoins))
{
$query = $db->getQuery(true);
$query->select('*')->from('#__{package}_joins')->where('element_id = ' . (int) $this->id)->orderby('id');
$db->setQuery($query);
$this->_aJoins = $db->LoadObjectList();
}
return $this->_aJoins;
}
/**
* Get other joins that point to this element
*
* @param JTable &$table Table
*
* @deprecated - don't think its used
*
* @return array
*/
public function getJoinsToThisKey(&$table)
{
$db = FabrikWorker::getDbo(true);
$query = $db->getQuery(true);
$query->select('*, t.label AS tablelabel')->from('#__{package}_elements AS el')
->join('LEFT', '#__{package}_formgroup AS fg ON fg.group_id = el.group_id')
->join('LEFT', '#__{package}_forms AS f ON f.id = fg.form_id')
->join('LEFT', ' #__{package}_tables AS t ON t.form_id = f.id')
->where('plugin = ' . $db->quote('databasejoin'))
->where('join_db_name = ' . $db->quote($table->get('db_table_name')))
->where('join_conn_id = ' . (int) $table->get('connection_id'));
$db->setQuery($query);
return $db->loadObjectList();
}
/**
* Run any eval'ed option code from element settings
*
* @param array $opts array of option objects
*/
protected function evalOptions(&$opts)
{
$params = $this->getParams();
$eval = $params->get('dabase_join_label_eval');
if (trim($eval) !== '')
{
foreach ($opts as $key => &$opt)
{
if (eval($eval) === false)
{
unset($opts[$key]);
}
}
}
}
/**
* Get array of option values
*
* @param array $data Data
* @param int $repeatCounter Repeat group counter
* @param bool $incWhere Do we add custom where statement into sql
* @param array $opts Additional options passed into buildQuery()
*
* @return array option values
*/
protected function _getOptionVals($data = array(), $repeatCounter = 0, $incWhere = true, $opts = array())
{
$params = $this->getParams();
$db = $this->getDb();
// $$$ hugh - attempting to make sure we never do an unconstrained query for auto-complete
$displayType = $this->getDisplayType();
$value = (array) $this->getValue($data, $repeatCounter);
/*
* $$$ rob 20/08/2012 - removed empty test - seems that this method is called more than one time, when in auto-complete filter
* First time sends the label in data second time sends the value (which is the correct one)
*
* $$$ rob 07/01/2014 - replaced empty test - otherwise default value would override autocomplete search.
* I re-tested the auto-complete filter with this change and it appears to be ok.
*/
if ($displayType === 'auto-complete' && empty($this->autocomplete_where))
{
if (!empty($value) && $value[0] !== '')
{
$quoteV = array();
foreach ($value as $v)
{
$quoteV[] = $db->quote($v);
}
$this->autocomplete_where = $this->getJoinValueColumn() . ' IN (' . implode(', ', $quoteV) . ')';
}
}
// $$$ rob 18/06/2012 cache the option vals on a per query basis (was previously incwhere but this was not ok
// for auto-completes in repeating groups
$sql = $this->buildQuery($data, $incWhere, $opts);
if (!$sql)
{
return array();
}
$sqlKey = (string) $sql;
if (isset($this->optionVals[$sqlKey]))
{
return $this->optionVals[$sqlKey];
}
$db->setQuery($sql);
FabrikHelperHTML::debug((string) $db->getQuery(), $this->getElement()->name . 'databasejoin element: get options query');
$this->optionVals[$sqlKey] = $db->loadObjectList();
FabrikHelperHTML::debug($this->optionVals, 'databasejoin elements');
if (!is_array($this->optionVals[$sqlKey]))
{
$this->optionVals[$sqlKey] = array();
}
$eval = $params->get('dabase_join_label_eval');
foreach ($this->optionVals[$sqlKey] as $key => &$opt)
{
// Check if concat label empty
if ($this->emptyConcatString($opt->text))
{
$opt->text = '';
}
if (trim($eval) !== '')
{
// $$$ hugh - added allowing removing an option by returning false
if (eval($eval) === false)
{
unset($this->optionVals[$sqlKey][$key]);
}
}
}
$displayType = $this->getDisplayType();
// Remove tags from labels
if ($this->canUse() && $displayType != 'radio' && $displayType != 'checkbox')
{
foreach ($this->optionVals[$sqlKey] as $key => &$opt)
{
$opt->text = strip_tags($opt->text);
}
}
return $this->optionVals[$sqlKey];
}
/**
* For fields that use the concat label, it may try to insert constants, but if no
* replacement data found then the concatenated constants should be considered as empty
*
* @param string $label Concatenate label
*
* @return boolean
*/
protected function emptyConcatString($label)
{
$params = $this->getParams();
$concat = $params->get($this->concatLabelParam, '');
if ($concat === '' || !$params->get('clean_concat', false))
{
return false;
}
$bits = explode(',', $concat);
$countBits = count($bits); //unset is modifying count($bits)
for ($i = 0; $i < $countBits; $i++)
{
if (strstr(trim($bits[$i]), '{thistable}.'))
{
unset($bits[$i]);
}
else
{
$bits[$i] = FabrikString::ltrimword($bits[$i], "'");
$bits[$i] = FabrikString::rtrimword($bits[$i], "'");
}
}
if ($label == implode($bits))
{
return true;
}
return false;
}
/**
* Fix html validation warning on empty options labels
*
* @param array &$rows option objects $rows
* @param string $txt object label
*
* @return null
*/
private function addSpaceToEmptyLabels(&$rows, $txt = 'text')
{
foreach ($rows as &$t)
{
if ($t->$txt == '')
{
$t->$txt = ' ';
}
}
}
/**
* Get a list of the HTML options used in the database join drop down / radio buttons
*
* @param array $data From current record (when editing form?)
* @param int $repeatCounter Repeat group counter
* @param bool $incWhere Do we include custom where in query
* @param array $opts Additional options passed into _getOptionVals()
*
* @return array option objects
*/
protected function _getOptions($data = array(), $repeatCounter = 0, $incWhere = true, $opts = array())
{
$params = $this->getParams();
$this->getDb();
$tmp = array();
$aDdObjs = $this->_getOptionVals($data, $repeatCounter, $incWhere, $opts);
foreach ($aDdObjs as &$o)
{
// For values like '1"'
// $$$ hugh - added second two params so we set double_encode false
if ($this->getDisplayType() != 'radio' && $this->getDisplayType() != 'checkbox')
{
$o->text = htmlspecialchars($o->text, ENT_NOQUOTES, 'UTF-8', false);
}
}
if (is_array($aDdObjs))
{
$tmp = array_merge($tmp, $aDdObjs);
}
$this->addSpaceToEmptyLabels($tmp);
if ($this->showPleaseSelect())
{
array_unshift($tmp, JHTML::_('select.option', $params->get('database_join_noselectionvalue', ''), $this->_getSelectLabel()));
if ($params->get('join_desc_column', '') !== '')
{
$tmp[0]->description = '';
}
}
return $tmp;
}
/**
* Get select option label
*
* @param bool $filter get alt label for filter, if present using :: splitter
*
* @return string
*/
protected function _getSelectLabel($filter = false)
{
$params = $this->getParams();
$label = $params->get('database_join_noselectionlabel');
if (strstr($label, '::'))
{
$labels = explode('::', $label);
$label = $filter ? $labels[1] : $labels[0];
}
if (!$filter && $label == '')
{
$label = 'COM_FABRIK_PLEASE_SELECT';
}
return FText::_($label);
}
/**
* Do you add a please select option to the list
*
* @since 3.0b
*
* @return bool
*/
protected function showPleaseSelect()
{
$params = $this->getParams();
$displayType = $this->getDisplayType();
if ($displayType == 'dropdown' && $params->get('database_join_show_please_select', true))
{
return true;
}
return false;
}
/**
* Check to see if pre-filter should be applied
* Kind of an inverse access lookup
*
* @param int $gid group id to check against
* @param string $ref for filter
*
* @return bool must apply filter - true, ignore filter (user has enough access rights) false;
*/
protected function mustApplyWhere($gid, $ref)
{
// $$$ hugh - adding 'where when' so can control whether to apply WHERE either on
// new, edit or both (1, 2 or 3)
$params = $this->getParams();
$whereWhen = $params->get('database_join_where_when', '3');
$isNew = $this->getFormModel()->isNewRecord();
if ($isNew && $whereWhen == '2')
{
return false;
}
elseif (!$isNew && $whereWhen == '1')
{
return false;
}
return in_array($gid, $this->user->getAuthorisedViewLevels());
}
/**
* Create the sql query used to get the join data
*
* @param array $data data
* @param bool $incWhere include where
* @param array $opts query options
*
* @return mixed JDatabaseQuery or false if query can't be built
*/
protected function buildQuery($data = array(), $incWhere = true, $opts = array())
{
$sig = isset($this->autocomplete_where) ? $this->autocomplete_where . '.' . $incWhere : $incWhere;
$sig .= '.' . serialize($opts);
$db = FabrikWorker::getDbo();
$query = $db->getQuery(true);
if (isset($this->sql[$sig]))
{
return $this->sql[$sig];
}
$params = $this->getParams();
$query = $this->buildQueryWhere($data, $incWhere, null, $opts, $query);
// $$$rob not sure these should be used anyway?
$table = $params->get('join_db_name');
$key = $this->getJoinValueColumn();
$val = $this->getLabelOrConcatVal();
$join = $this->getJoin();
if ($table == '')
{
$table = $join->table_join;
$key = $join->table_join_alias . '.' . $join->table_join_key;
$val = $join->params->get('join-label', $val);
}
if ($key == '' || $val == '')
{
return false;
}
if (!strstr($val, 'CONCAT'))
{
$val = $db->qn($val);
}
$query->select('DISTINCT(' . $key . ') AS value, ' . $val . ' AS text');
$this->buildQueryDescription($query, $data);
$additionalFields = $this->getAdditionalQueryFields();
if ($additionalFields != '')
{
$query->select($additionalFields);
}
$query->from($db->qn($table) . ' AS ' . $db->qn($join->table_join_alias));
$query = $this->buildQueryJoin($query);
/* $$$ hugh - let them specify an order by, i.e. don't append default if the $where already has an 'order by'
* @TODO - we should probably split 'order by' out in to another setting field, because if they are using
* the 'apply where beneath' and/or 'apply where when' feature, any custom ordering will not be applied
* if the 'where' is not being applied, which probably isn't what they want.
*/
$query = $this->getOrderBy('', $query);
$this->sql[$sig] = $query;
return $this->sql[$sig];
}
/**
* Add the description field to the buildQuery select statement
*
* @param JQuery &$query BuildQuery
* @param array $data BuildQuery data
*
* @return void
*/
protected function buildQueryDescription(&$query, $data)
{
$params = $this->getParams();
$desc = $params->get('join_desc_column', '');
if ($desc !== '')
{
$db = FabrikWorker::getDbo();
$w = new FabrikWorker;
$data = is_array($data) ? $data : array();
$desc = $w->parseMessageForPlaceHolder($desc, $data, false);
$desc = FabrikString::isConcat($desc) ? $desc : $db->qn($desc);
$desc = "REPLACE(" . $desc . ", '\n', '<br />')";
$query->select($desc . ' AS description');
}
}
/**
* If buildQuery needs additional fields then set them here, used in notes plugin
*
* @since 3.0rc1
*
* @return string fields to add e.g return ',name, username AS other'
*/
protected function getAdditionalQueryFields()
{
return '';
}
/**
* If buildQuery needs additional joins then set them here, used in notes plugin
* $$$ hugh - added new "Additional join statement" option in join element, which now gets
* parsed here. Should probably take the main logic in this, and put it in a helper, as this
* is probably something we'll need to do elsewhere.
*
* @param mixed $query false to return string, or JQueryBuilder object
*
* @since 3.0rc1
*
* @return string|JQueryerBuilder join statement to add
*/
protected function buildQueryJoin($query = false)
{
if ($query !== false)
{
$params = $this->getParams();
$query_join = trim($params->get('database_join_join_sql'), '');
/*
* Set up RE of all possible valid MySQL join types, as per join_table spec here:
* http://dev.mysql.com/doc/refman/5.0/en/join.html
* EXCEPT just 'JOIN' by itself. Don't ask.
*/
$re = array();
$re[] = '(LEFT\s+JOIN)';
$re[] = '(LEFT\s+OUTER\s+JOIN)';
$re[] = '(RIGHT\s+JOIN)';
$re[] = '(RIGHT\s+OUTER\s+JOIN)';
$re[] = '(INNER\s+JOIN)';
$re[] = '(CROSS\s+JOIN)';
$re[] = '(STRAIGHT_JOIN)';
$re[] = '(NATURAL\s+JOIN)';
$re[] = '(NATURAL\s+LEFT\s+JOIN)';
$re[] = '(NATURAL\s+RIGHT\s+JOIN)';
$re[] = '(NATURAL\s+LEFT\s+OUTER\s+JOIN)';
$re[] = '(NATURAL\s+RIGHT\s+OUTER\s+JOIN)';
$re = implode('|', $re);
/*
* Using NO_EMPT and SPLIT_CAPTURE, we should end up with an array which alternates
* between the JOIN type, and the rest of the expression
*/
$joins = preg_split("#$re#i", $query_join, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
if (!empty($joins))
{
$ojoin = $this->getJoin();
$join_types = array();
$join_exprs = array();
foreach ($joins as $index => $join)
{
if (!($index & 1))
{
/*
* Index is odd, so should be a JOIN type.
* If it doesn't have the word 'join' in it, something went
* wrong, so just bail.
*/
if (!stristr($join, 'join'))
{
return '';
}
/*
* Strip out the word JOIN. Must use preg_replace, so we don't break STRAIGHT_JOIN.
* Trim it, and stuff it in the types array.
*/
$join = preg_replace("#\s+JOIN\s*#i", '', $join);
$join_types[] = trim($join);
}