forked from pollen8/fabrik
-
Notifications
You must be signed in to change notification settings - Fork 381
/
list.php
2410 lines (2220 loc) · 68.2 KB
/
list.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
/**
* Fabrik Admin List Model
*
* @package Joomla.Administrator
* @subpackage Fabrik
* @copyright Copyright (C) 2005 Fabrik. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @since 1.6
*/
// No direct access.
defined('_JEXEC') or die;
require_once 'fabmodeladmin.php';
/**
* Fabrik Admin List Model
*
* @package Joomla.Administrator
* @subpackage Fabrik
* @since 3.0
*/
class FabrikAdminModelList extends FabModelAdmin
{
/**
* The prefix to use with controller messages.
*
* @var string
*/
protected $text_prefix = 'COM_FABRIK_LIST';
/**
* Front end form model
*
* @var object model
*/
protected $formModel = null;
/**
* Front end list model
*
* @var object
*/
protected $feListModel = null;
/**
* Currently loaded list row
*
* @var array
*/
protected $tables = array();
/**
* Plugin type
*
* @var string
* @deprecated ?
*/
protected $pluginType = 'List';
/**
* Returns a reference to the a Table object, always creating it.
*
* @param string $type The table type to instantiate
* @param string $prefix A prefix for the table class name. Optional.
* @param array $config Configuration array for model. Optional.
*
* @return JTable A database object
*
* @since 1.6
*/
public function getTable($type = 'List', $prefix = 'FabrikTable', $config = array())
{
$sig = $type . $prefix . implode('.', $config);
if (!array_key_exists($sig, $this->tables))
{
$config['dbo'] = FabriKWorker::getDbo(true);
$this->tables[$sig] = FabTable::getInstance($type, $prefix, $config);
}
return $this->tables[$sig];
}
/**
* Method to get the record form.
*
* @param array $data Data for the form.
* @param bool $loadData True if the form is to load its own data (default case), false if not.
*
* @return mixed A JForm object on success, false on failure
*
* @since 1.6
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_fabrik.list', 'list', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
$form->model = $this;
return $form;
}
/**
* Method to get the confirm list delete form.
*
* @param array $data Data for the form.
* @param bool $loadData True if the form is to load its own data (default case), false if not.
*
* @return mixed A JForm object on success, false on failure
*
* @since 1.6
*/
public function getConfirmDeleteForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_fabrik.confirmdelete', 'confirmlistdelete', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
}
/**
* Method to get the data that should be injected in the form.
*
* @return mixed The data for the form.
*
* @since 1.6
*/
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_fabrik.edit.list.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
/**
* Method to change the published state of one or more records.
*
* @param array &$pks A list of the primary keys to change.
* @param int $value The value of the published state.
*
* @return boolean True on success.
*
* @since 1.6
*/
public function publish(&$pks, $value = 1)
{
// Initialise variables.
$dispatcher = JDispatcher::getInstance();
$user = JFactory::getUser();
$table = $this->getTable();
$pks = (array) $pks;
// Include the content plugins for the change of state event.
JPluginHelper::importPlugin('content');
// Access checks.
foreach ($pks as $i => $pk)
{
if ($table->load($pk))
{
if (!$this->canEditState($table))
{
// Prune items that you can't change.
unset($pks[$i]);
JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDIT_STATE_NOT_PERMITTED'));
}
}
}
// Attempt to change the state of the records.
if (!$table->publish($pks, $value, $user->get('id')))
{
$this->setError($table->getError());
return false;
}
$context = $this->option . '.' . $this->name;
// Trigger the onContentChangeState event.
$result = $dispatcher->trigger($this->event_change_state, array($context, $pks, $value));
if (in_array(false, $result, true))
{
$this->setError($table->getError());
return false;
}
return true;
}
/**
* Build and/or dropdown list
*
* @param bool $addSlashes to reutrn data
* @param string $name input name
*
* @return string dropdown
*/
protected function getFilterJoinDd($addSlashes = true, $name = 'join')
{
$aConditions = array();
$aConditions[] = JHTML::_('select.option', 'AND');
$aConditions[] = JHTML::_('select.option', 'OR');
$dd = str_replace("\n", "", JHTML::_('select.genericlist', $aConditions, $name, "class=\"inputbox input-small\" size=\"1\" ", 'value', 'text', ''));
if ($addSlashes)
{
$dd = addslashes($dd);
}
return $dd;
}
/**
* Build prefilter dropdown
*
* @param bool $addSlashes add slashes to reutrn data
* @param string $name name of the drop down
* @param int $mode states what values get put into drop down
*
* @return string dropdown
*/
protected function getFilterConditionDd($addSlashes = true, $name = 'conditions', $mode = 1)
{
$aConditions = array();
switch ($mode)
{
case 1: /* used for search filter */
$aConditions[] = JHTML::_('select.option', '<>', 'NOT EQUALS');
$aConditions[] = JHTML::_('select.option', '=', 'EQUALS');
$aConditions[] = JHTML::_('select.option', 'like', 'BEGINS WITH');
$aConditions[] = JHTML::_('select.option', 'like', 'CONTAINS');
$aConditions[] = JHTML::_('select.option', 'like', 'ENDS WITH');
$aConditions[] = JHTML::_('select.option', '>', 'GREATER THAN');
$aConditions[] = JHTML::_('select.option', '>=', 'GREATER THAN OR EQUALS');
$aConditions[] = JHTML::_('select.option', '<', 'LESS THAN');
$aConditions[] = JHTML::_('select.option', '<=', 'LESS THAN OR EQUALS');
break;
case 2: /* used for prefilter */
$aConditions[] = JHTML::_('select.option', 'equals', 'EQUALS');
$aConditions[] = JHTML::_('select.option', 'notequals', 'NOT EQUAL TO');
$aConditions[] = JHTML::_('select.option', 'begins', 'BEGINS WITH');
$aConditions[] = JHTML::_('select.option', 'contains', 'CONTAINS');
$aConditions[] = JHTML::_('select.option', 'ends', 'ENDS WITH');
$aConditions[] = JHTML::_('select.option', '>', 'GREATER THAN');
$aConditions[] = JHTML::_('select.option', '>=', 'GREATER THAN OR EQUALS');
$aConditions[] = JHTML::_('select.option', '<', 'LESS THAN');
$aConditions[] = JHTML::_('select.option', 'IS NULL', 'IS NULL');
$aConditions[] = JHTML::_('select.option', '<=', 'LESS THAN OR EQUALS');
$aConditions[] = JHTML::_('select.option', 'in', 'IN');
$aConditions[] = JHTML::_('select.option', 'not_in', 'NOT IN');
$aConditions[] = JHTML::_('select.option', 'earlierthisyear', JText::_('COM_FABRIK_EARLIER_THIS_YEAR'));
$aConditions[] = JHTML::_('select.option', 'laterthisyear', JText::_('COM_FABRIK_LATER_THIS_YEAR'));
$aConditions[] = JHTML::_('select.option', 'yesterday', JText::_('COM_FABRIK_YESTERDAY'));
$aConditions[] = JHTML::_('select.option', 'today', JText::_('COM_FABRIK_TODAY'));
$aConditions[] = JHTML::_('select.option', 'tomorrow', JText::_('COM_FABRIK_TOMORROW'));
$aConditions[] = JHTML::_('select.option', 'thismonth', JText::_('COM_FABRIK_THIS_MONTH'));
$aConditions[] = JHTML::_('select.option', 'lastmonth', JText::_('COM_FABRIK_LAST_MONTH'));
$aConditions[] = JHTML::_('select.option', 'nextmonth', JText::_('COM_FABRIK_NEXT_MONTH'));
break;
}
$dd = str_replace("\n", "", JHTML::_('select.genericlist', $aConditions, $name, 'class="inputbox input-small" size="1" ', 'value', 'text', ''));
if ($addSlashes)
{
$dd = addslashes($dd);
}
return $dd;
}
/**
* Get connection model
*
* @return object connect model
*/
protected function getCnn()
{
$item = $this->getItem();
$connModel = JModelLegacy::getInstance('Connection', 'FabrikFEModel');
$connModel->setId($item->connection_id);
$connModel->getConnection($item->connection_id);
return $connModel;
}
/**
* Create the js that manages the edit list view page
*
* @return string js
*/
public function getJs()
{
$connModel = $this->getCnn();
$plugins = $this->getPlugins();
$item = $this->getItem();
$pluginManager = JModelLegacy::getInstance('Pluginmanager', 'FabrikFEModel');
JText::script('COM_FABRIK_OPTIONS');
JText::script('COM_FABRIK_JOIN');
JText::script('COM_FABRIK_FIELD');
JText::script('COM_FABRIK_CONDITION');
JText::script('COM_FABRIK_VALUE');
JText::script('COM_FABRIK_EVAL');
JText::script('COM_FABRIK_APPLY_FILTER_TO');
JText::script('COM_FABRIK_DELETE');
JText::script('JYES');
JText::script('JNO');
JText::script('COM_FABRIK_QUERY');
JTEXT::script('COM_FABRIK_NO_QUOTES');
JText::script('COM_FABRIK_TEXT');
JText::script('COM_FABRIK_TYPE');
JText::script('COM_FABRIK_PLEASE_SELECT');
JText::script('COM_FABRIK_GROUPED');
JText::script('COM_FABRIK_TO');
JText::script('COM_FABRIK_FROM');
JText::script('COM_FABRIK_JOIN_TYPE');
JText::script('COM_FABRIK_FROM_COLUMN');
JText::script('COM_FABRIK_TO_COLUMN');
JText::script('COM_FABRIK_REPEAT_GROUP_BUTTON_LABEL');
JText::script('COM_FABRIK_PUBLISHED');
$joinTypeOpts = array();
$joinTypeOpts[] = array('inner', JText::_('INNER JOIN'));
$joinTypeOpts[] = array('left', JText::_('LEFT JOIN'));
$joinTypeOpts[] = array('right', JText::_('RIGHT JOIN'));
$activetableOpts[] = "";
$activetableOpts[] = $item->db_table_name;
$joins = $this->getJoins();
for ($i = 0; $i < count($joins); $i++)
{
$j = $joins[$i];
$activetableOpts[] = $j->table_join;
$activetableOpts[] = $j->join_from_table;
}
$activetableOpts = array_unique($activetableOpts);
$activetableOpts = array_values($activetableOpts);
$opts = new stdClass;
$opts->joinOpts = $joinTypeOpts;
$opts->tableOpts = $connModel->getThisTables(true);
$opts->activetableOpts = $activetableOpts;
$opts->j3 = FabrikWorker::j3();
$opts = json_encode($opts);
$filterOpts = new stdClass;
$filterOpts->filterJoinDd = $this->getFilterJoinDd(false, 'jform[params][filter-join][]');
$filterOpts->filterCondDd = $this->getFilterConditionDd(false, 'jform[params][filter-conditions][]', 2);
$filterOpts->filterAccess = JHtml::_('access.level', 'jform[params][filter-access][]', $item->access, 'class="input-small"');
$filterOpts->filterAccess = str_replace(array("\n", "\r"), '', $filterOpts->filterAccess);
$filterOpts->j3 = FabrikWorker::j3();
$filterOpts = json_encode($filterOpts);
$formModel = $this->getFormModel();
$filterfields = $formModel->getElementList('jform[params][filter-fields][]', '', false, false, true, 'name', 'class="inputbox input-small" size="1"');
$filterfields = addslashes(str_replace(array("\n", "\r"), '', $filterfields));
$plugins = json_encode($this->getPlugins());
$js = array();
$js[] = "window.addEvent('domready', function () {";
$js[] = "Fabrik.controller = new PluginManager($plugins, " . (int) $this->getItem()->id . ", 'list');";
$js[] = "oAdminTable = new ListForm($opts);";
$js[] = "oAdminTable.watchJoins();";
for ($i = 0; $i < count($joins); $i++)
{
$joinGroupParams = json_decode($joins[$i]->params);
$j = $joins[$i];
$joinFormFields = json_encode($j->joinFormFields);
$joinToFields = json_encode($j->joinToFields);
$repeat = $joinGroupParams->repeat_group_button == 1 ? 1 : 0;
$js[] = " oAdminTable.addJoin('{$j->group_id}','{$j->id}','{$j->join_type}','{$j->table_join}',"
. "'{$j->table_key}','{$j->table_join_key}','{$j->join_from_table}', $joinFormFields, $joinToFields, $repeat);";
}
$js[] = "oAdminFilters = new adminFilters('filterContainer', '$filterfields', $filterOpts);";
$form = $this->getForm();
$afilterJoins = $form->getValue('params.filter-join');
// Force to arrays as single prefilters imported from 2.x will be stored as string values
$afilterFields = (array) $form->getValue('params.filter-fields');
$afilterConditions = (array) $form->getValue('params.filter-conditions');
$afilterEval = (array) $form->getValue('params.filter-eval');
$afilterValues = (array) $form->getValue('params.filter-value');
$afilterAccess = (array) $form->getValue('params.filter-access');
$aGrouped = (array) $form->getValue('params.filter-grouped');
for ($i = 0; $i < count($afilterFields); $i++)
{
$selJoin = JArrayHelper::getValue($afilterJoins, $i, 'and');
// 2.0 upgraded sites had quoted filter names
$selFilter = str_replace('`', '', $afilterFields[$i]);
$grouped = JArrayHelper::getValue($aGrouped, $i, 0);
$selCondition = $afilterConditions[$i];
$filerEval = (int) JArrayHelper::getValue($afilterEval, $i, '1');
if ($selCondition == '>')
{
$selCondition = '>';
}
if ($selCondition == '<')
{
$selCondition = '<';
}
$selValue = JArrayHelper::getValue($afilterValues, $i, '');
$selAccess = $afilterAccess[$i];
// Alow for multiline js variables ?
$selValue = htmlspecialchars_decode($selValue, ENT_QUOTES);
$selValue = json_encode($selValue);
if ($selFilter != '')
{
$js[] = "\toAdminFilters.addFilterOption('$selJoin', '$selFilter', '$selCondition', $selValue, '$selAccess', $filerEval, '$grouped');\n";
}
}
$js[] = "});";
return implode("\n", $js);
}
/**
* Get the list's join objects
*
* @return array
*/
protected function getJoins()
{
$item = $this->getItem();
if ((int) $item->id === 0)
{
return array();
}
$db = FabrikWorker::getDbo(true);
$query = $db->getQuery(true);
$query->select('*, j.id AS id, j.params as jparams')->from('#__{package}_joins AS j')
->join('INNER', '#__{package}_groups AS g ON g.id = j.group_id')->where('j.list_id = ' . (int) $item->id);
$db->setQuery($query);
$joins = $db->loadObjectList();
$fabrikDb = $this->getFEModel()->getDb();
$c = count($joins);
for ($i = 0; $i < $c; $i++)
{
$join =& $joins[$i];
$jparams = $join->jparams == '' ? new stdClass : json_decode($join->jparams);
if (isset($jparams->type) && ($jparams->type == 'element' || $jparams->type == 'repeatElement'))
{
unset($joins[$i]);
continue;
}
$fields = $fabrikDb->getTableColumns($join->join_from_table);
$join->joinFormFields = array_keys($fields);
$fields = $fabrikDb->getTableColumns($join->table_join);
$join->joinToFields = array_keys($fields);
}
// $$$ re-index the array in case we zapped anything
return array_values($joins);
}
/**
* Load up a front end form model - used in saving the list
*
* @return object front end form model
*/
public function getFormModel()
{
if (is_null($this->formModel))
{
$config = array();
$config['dbo'] = FabrikWorker::getDbo(true);
$this->formModel = JModelLegacy::getInstance('Form', 'FabrikFEModel', $config);
$this->formModel->setDbo($config['dbo']);
/**
* $$$ rob commenting out as this loads up an empty form when saving a new list
* $item = $this->getItem();
* $this->formModel->setId($this->getState('list.form_id', $item->id));
* $this->formModel->getForm();
*/
/**
* $$$ rob isnt this wrong as normally the front end form models list model is the fe list model?
* $this->formModel->setListModel($this);
*/
}
return $this->formModel;
}
/**
* Set the form model
*
* @param object $model form model
*
* @return void
*/
public function setFormModel($model)
{
$this->formModel = $model;
}
/**
* Load up the front end list model so we can use some of its methods
*
* @return object front end list model
*/
public function getFEModel()
{
if (is_null($this->feListModel))
{
$this->feListModel = JModelLegacy::getInstance('List', 'FabrikFEModel');
$this->feListModel->setState('list.id', $this->getState('list.id'));
}
return $this->feListModel;
}
/**
* Validate the form
*
* @param object $form The form to validate against.
* @param array $data The data to validate.
* @param string $group The name of the field group to validate.
*
* @return mixed false or data
*/
public function validate($form, $data, $group = null)
{
$params = $data['params'];
$data = parent::validate($form, $data, $group);
if (!$data)
{
return false;
}
if (empty($data['_database_name']) && JArrayHelper::getValue($data, 'db_table_name') == '')
{
$this->setError(JText::_('COM_FABRIK_SELECT_DB_OR_ENTER_NAME'));
return false;
}
// Hack - must be able to add the plugin xml fields file to $form to include in validation but cant see how at the moment
$data['params'] = $params;
return $data;
}
/**
* Save the form
*
* @param array $data the jform part of the request data
*
* @return bool
*/
public function save($data)
{
$this->populateState();
$app = JFactory::getApplication();
$input = $app->input;
$user = JFactory::getUser();
$config = JFactory::getConfig();
$date = JFactory::getDate();
$row = $this->getTable();
$id = JArrayHelper::getValue($data, 'id');
$row->load($id);
$params = new JRegistry($row->params);
$this->setState('list.id', $id);
$this->setState('list.form_id', $row->form_id);
$feModel = $this->getFEModel();
$formModel = $this->getFormModel();
// Get original collation
$db = $feModel->getDb();
$db->setQuery('SHOW TABLE STATUS LIKE ' . $db->quote($data['db_table_name']));
$info = $db->loadObject();
$origCollation = is_object($info) ? $info->Collation : $params->get('collation', 'none');
if (!$row->bind($data))
{
$this->setError($row->getError());
return false;
}
$filter = new JFilterInput(null, null, 1, 1);
$introduction = JArrayHelper::getValue($input->get('jform', array(), 'array'), 'introduction');
$row->introduction = $filter->clean($introduction);
$row->order_by = json_encode($input->get('order_by', array(), 'array'));
$row->order_dir = json_encode($input->get('order_dir', array(), 'array'));
if (!$row->check())
{
$this->setError($row->getError());
return false;
}
$this->collation($feModel, $origCollation, $row);
$isNew = true;
if ($id == 0)
{
if ($row->created == '')
{
$row->created = $date->toSql();
}
// Save the row now
$row->store();
$isNew = false;
$newtable = trim(JArrayHelper::getValue($data, '_database_name'));
// Mysql will force db table names to lower case even if you set the db name to upper case - so use clean()
$newtable = FabrikString::clean($newtable);
// Check the entered database table doesnt already exist
if ($newtable != '' && $this->databaseTableExists($newtable))
{
$this->setError(JText::_('COM_FABRIK_DATABASE_TABLE_ALREADY_EXISTS'));
return false;
}
if (!$this->canCreateDbTable())
{
$this->setError(Jtext::_('COM_FABRIK_INSUFFICIENT_RIGHTS_TO_CREATE_TABLE'));
return false;
}
// Create fabrik form
$formModel = $this->createLinkedForm();
$row->form_id = $this->getState('list.form_id');
// Create fabrik group
$groupData = FabrikWorker::formDefaults('group');
$groupData['name'] = $row->label;
$groupData['label'] = $row->label;
$input->set('_createGroup', 1, 'post');
$groupId = $this->createLinkedGroup($groupData, false);
if ($newtable == '')
{
// New fabrik list but existing db table
$this->createLinkedElements($groupId);
}
else
{
$row->db_table_name = $newtable;
$row->auto_inc = 1;
$dbOpts = array();
$params = new JRegistry($row->params);
$dbOpts['COLLATE'] = $params->get('collation', '');
$res = $this->createDBTable($newtable, $input->get('defaultfields', array('id' => 'internalid', 'date_time' => 'date'), 'array'), $dbOpts);
if (is_array($res))
{
$row->db_primary_key = $newtable . '.' . $res[0];
}
}
}
$params = new JRegistry($row->params);
if ($row->id != 0)
{
$datenow = JFactory::getDate();
$row->modified = $datenow->toSql();
$row->modified_by = $user->get('id');
}
FabrikAdminHelper::prepareSaveDate($row->publish_down);
FabrikAdminHelper::prepareSaveDate($row->created);
FabrikAdminHelper::prepareSaveDate($row->publish_up);
$pk = JArrayHelper::getValue($data, 'db_primary_key');
if ($pk == '')
{
$fields = $row->getFields();
$key = $row->getKeyName();
// Store without quoteNames as thats db specific
$row->db_primary_key = $row->db_primary_key == '' ? $row->db_table_name . "." . $key : $row->db_primary_key;
$row->auto_inc = JString::stristr($fields[$key]->Extra, 'auto_increment') ? true : false;
}
if (!$row->store())
{
$this->setError($row->getError());
return false;
}
$pk = $row->db_primary_key;
$this->updateJoins($data);
// Needed to ensure pk field is not quoted
$feModel->setTable($row);
if (!$feModel->isView())
{
$this->updatePrimaryKey($row->db_primary_key, $row->auto_inc);
}
// Make an array of elments and a presumed index size, map is then used in creating indexes
$map = array();
$groups = $this->getFormModel()->getGroupsHiarachy();
foreach ($groups as $groupModel)
{
$elementModels = $groupModel->getMyElements();
foreach ($elementModels as $element)
{
// Int and DATETIME elements cant have a index size attrib
$coltype = $element->getFieldDescription();
if (JString::stristr($coltype, 'int'))
{
$size = '';
}
elseif (JString::stristr($coltype, 'datetime'))
{
$size = '';
}
else
{
$size = '10';
}
$map[$element->getFullName(false, false, false)] = $size;
$map[$element->getElement()->id] = $size;
}
}
// Update indexes (added array_key_exists check as these may be during after CSV import)
if (!empty($aOrderBy) && array_key_exists($row->order_by, $map))
{
foreach ($aOrderBy as $orderBy)
{
if (array_key_exists($orderBy, $map))
{
$feModel->addIndex($orderBy, 'tableorder', 'INDEX', $map[$orderBy]);
}
}
}
if ($row->group_by !== '' && array_key_exists($row->group_by, $map))
{
$feModel->addIndex($row->group_by, 'groupby', 'INDEX', $map["$row->group_by"]);
}
if (trim($params->get('group_by_order')) !== '')
{
$feModel->addIndex($params->get('group_by_order'), 'groupbyorder', 'INDEX', $map[$params->get('group_by_order')]);
}
$afilterFields = (array) $params->get('filter-fields', array());
foreach ($afilterFields as $field)
{
if (array_key_exists($field, $map))
{
$feModel->addIndex($field, 'prefilter', 'INDEX', $map[$field]);
}
}
/* $$$rob - joomfish not available for j1.7
if (JFolder::exists(JPATH_ADMINISTRATOR . '/components/com_joomfish/contentelements')) {
if ($params->get('allow-data-translation')) {
if (!$this->makeJoomfishXML()) {
$this->setError(JTEXT::_( "Unable to make Joomfish XML file"));
return false;
}
} else {
$this->removeJoomfishXML();
}
} */
$pkName = $row->getKeyName();
if (isset($row->$pkName))
{
$this->setState($this->getName() . '.id', $row->$pkName);
}
$this->setState($this->getName() . '.new', $isNew);
parent::cleanCache('com_fabrik');
return true;
}
/**
* Alter the db table's collation
*
* @param object $feModel Front end list model
* @param string $origCollation Original collection name
* @param string $row New collation
*
* @since 3.0.7
*
* @return boolean
*/
protected function collation($feModel, $origCollation, $row)
{
// Don't attempt to alter new table, or a view
if ($row->id == 0 || $feModel->isView())
{
return;
}
$params = new JRegistry($row->params);
$newCollation = $params->get('collation');
if ($newCollation !== $origCollation)
{
$db = $feModel->getDb();
$item = $feModel->getTable();
$db->setQuery('ALTER TABLE ' . $item->db_table_name . ' COLLATE ' . $newCollation);
if (!$db->execute())
{
JError::raiseNotice(500, $db->getErrorMsg());
return false;
}
}
return true;
}
/**
* Check to see if a table exists
*
* @param string $tableName name of table (ovewrites form_id val to test)
*
* @return bool false if no table found true if table found
*/
public function databaseTableExists($tableName = null)
{
if ($tableName === '')
{
return false;
}
$table = $this->getTable();
if (is_null($tableName))
{
$tableName = $table->db_table_name;
}
$fabrikDatabase = $this->getDb();
$sql = 'SHOW TABLES LIKE ' . $fabrikDatabase->quote($tableName);
$fabrikDatabase->setQuery($sql);
$total = $fabrikDatabase->loadResult();
echo $fabrikDatabase->getError();
return ($total == '') ? false : true;
}
/**
* Deals with ensuring joins are managed correctly when table is saved
*
* @param array $data jform data
*
* @return void
*/
private function updateJoins($data)
{
$db = FabrikWorker::getDbo(true);
$query = $db->getQuery(true);
// If we are creating a new list then don't update any joins - can result in groups and elements being removed.
if ((int) $this->getState('list.id') === 0)
{
return;
}
// $$$ hugh - added "AND element_id = 0" to avoid fallout from "random join and group deletion" issue from May 2012
$query->select('*')->from('#__{package}_joins')->where('list_id = ' . (int) $this->getState('list.id') . ' AND element_id = 0');
$db->setQuery($query);
$aOldJoins = $db->loadObjectList();
$params = $data['params'];
$aOldJoinsToKeep = array();
$joinModel = JModelLegacy::getInstance('Join', 'FabrikFEModel');
$joinIds = JArrayHelper::getValue($params, 'join_id', array());
$joinTypes = JArrayHelper::getValue($params, 'join_type', array());
$joinTableFrom = JArrayHelper::getValue($params, 'join_from_table', array());
$joinTable = JArrayHelper::getValue($params, 'table_join', array());
$tableKey = JArrayHelper::getValue($params, 'table_key', array());
$joinTableKey = JArrayHelper::getValue($params, 'table_join_key', array());
$groupIds = JArrayHelper::getValue($params, 'group_id', array());
$repeats = JArrayHelper::getValue($params, 'join_repeat', array());
$jc = count($joinTypes);
// Test for repeat elements to eusure their join isnt removed from here
foreach ($aOldJoins as $oldJoin)
{
if ($oldJoin->params !== '')
{
$oldParams = json_decode($oldJoin->params);
if (isset($oldParams->type) && $oldParams->type == 'repeatElement')
{
$aOldJoinsToKeep[] = $oldJoin->id;
}
}
}
for ($i = 0; $i < $jc; $i++)
{
$existingJoin = false;
foreach ($aOldJoins as $oOldJoin)
{
if ($joinIds[$i] == $oOldJoin->id)
{
$existingJoin = true;
}
}
// $$$rob make an index on the join element (fk)
$els = $this->getFEModel()->getElements();
foreach ($els as $el)
{
if ($el->getElement()->name == $tableKey[$i])
{
$size = JString::stristr($el->getFieldDescription(), 'int') ? '' : '10';
}
}
$this->getFEModel()->addIndex($tableKey[$i], 'join', 'INDEX', $size);
if (!$existingJoin)
{
$this->makeNewJoin($tableKey[$i], $joinTableKey[$i], $joinTypes[$i], $joinTable[$i], $joinTableFrom[$i], $repeats[$i][0]);
}
else
{
/* load in the exisitng join
* if the table_join has changed we need to create a new join
* (with its corresponding group and elements)
* and mark the loaded one as to be deleted
*/
$joinModel->setId($joinIds[$i]);
$joinModel->clearJoin();
$join = $joinModel->getJoin();
if ($join->table_join != $joinTable[$i])
{
$this->makeNewJoin($tableKey[$i], $joinTableKey[$i], $joinTypes[$i], $joinTable[$i], $joinTableFrom[$i], $repeats[$i][0]);
}
else
{
// The table_join has stayed the same so we simply update the join info
$join->table_key = str_replace('`', '', $tableKey[$i]);
$join->table_join_key = $joinTableKey[$i];
$join->join_type = $joinTypes[$i];
$join->store();
// Update group
$group = $this->getTable('Group');
$group->load($join->group_id);
$gparams = json_decode($group->params);
$gparams->repeat_group_button = $repeats[$i][0] == 1 ? 1 : 0;
$group->params = json_encode($gparams);
$group->store();
$aOldJoinsToKeep[] = $joinIds[$i];
}
}
}
// Remove non exisiting joins
if (is_array($aOldJoins))
{
foreach ($aOldJoins as $oOldJoin)
{
if (!in_array($oOldJoin->id, $aOldJoinsToKeep))
{
// Delete join
$join = $this->getTable('Join');
$joinModel->setId($oOldJoin->id);
$joinModel->clearJoin();
$joinModel->getJoin();
$joinModel->deleteAll($oOldJoin->group_id);
}
}
}
}
/**
* New join make the group, group elements and formgroup entries for the join data
*
* @param string $tableKey table key
* @param string $joinTableKey join to table key
* @param string $joinType join type
* @param string $joinTable join to table
* @param string $joinTableFrom join table
* @param bool $isRepeat is the group a repeat
*
* @return void
*/
protected function makeNewJoin($tableKey, $joinTableKey, $joinType, $joinTable, $joinTableFrom, $isRepeat)
{
$app = JFactory::getApplication();
$input = $app->input;
$formModel = $this->getFormModel();
$groupData = FabrikWorker::formDefaults('group');
$groupData['name'] = $this->getTable()->label . '- [' . $joinTable . ']';
$groupData['label'] = $joinTable;
$groupId = $this->createLinkedGroup($groupData, true, $isRepeat);
$origTable = JArrayHelper::getValue($input->get('jform', array(), 'array'), 'db_table_name');
$join = $this->getTable('Join');
$join->id = null;
$join->list_id = $this->getState('list.id');
$join->join_from_table = $joinTableFrom;