/
auto-modules.php
executable file
·1784 lines (1500 loc) · 55.9 KB
/
auto-modules.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
<?
/*
Class: BigTreeAutoModule
Handles functions for auto module forms / views created in Developer.
*/
class BigTreeAutoModule {
/*
Function: cacheNewItem
Caches a new database entry by investigating associated views.
Parameters:
id - The id of the new item.
table - The table the new item is in.
pending - Whether this is actually a pending entry or not.
recache - Whether to delete previous cached entries with this id (for use by recacheItem)
See Also:
<recacheItem>
*/
static function cacheNewItem($id,$table,$pending = false,$recache = false) {
if (!$pending) {
$item = sqlfetch(sqlquery("SELECT `$table`.*,bigtree_pending_changes.changes AS bigtree_changes FROM `$table` LEFT JOIN bigtree_pending_changes ON (bigtree_pending_changes.item_id = `$table`.id AND bigtree_pending_changes.table = '$table') WHERE `$table`.id = '$id'"));
$original_item = $item;
if ($item["bigtree_changes"]) {
$changes = json_decode($item["bigtree_changes"],true);
foreach ($changes as $key => $change) {
$item[$key] = $change;
}
}
} else {
$f = sqlfetch(sqlquery("SELECT * FROM bigtree_pending_changes WHERE id = '$id'"));
$item = json_decode($f["changes"],true);
$item["bigtree_pending"] = true;
$item["bigtree_pending_owner"] = $f["user"];
$item["id"] = "p".$f["id"];
$original_item = $item;
}
$q = sqlquery("SELECT * FROM bigtree_module_views WHERE `table` = '$table'");
while ($view = sqlfetch($q)) {
if ($recache) {
sqlquery("DELETE FROM bigtree_module_view_cache WHERE `view` = '".$view["id"]."' AND id = '".$item["id"]."'");
}
$view["fields"] = json_decode($view["fields"],true);
$view["actions"] = json_decode($view["actions"],true);
$view["options"] = json_decode($view["options"],true);
// In case this view has never been cached, run the whole view, otherwise just this one.
if (!self::cacheViewData($view)) {
// Find out what module we're using so we can get the gbp_field
$action = sqlfetch(sqlquery("SELECT module FROM bigtree_module_actions WHERE view = '".$view["id"]."'"));
$module = sqlfetch(sqlquery("SELECT gbp FROM bigtree_modules WHERE id = '".$action["module"]."'"));
$view["gbp"] = json_decode($module["gbp"],true);
$form = self::getRelatedFormForView($view);
$parsers = array();
$poplists = array();
foreach ($view["fields"] as $key => $field) {
$value = $item[$key];
if ($field["parser"]) {
$parsers[$key] = $field["parser"];
} elseif ($form["fields"][$key]["type"] == "list" && $form["fields"][$key]["list_type"] == "db") {
$poplists[$key] = array("description" => $form["fields"][$key]["pop-description"], "table" => $form["fields"][$key]["pop-table"]);
}
}
self::cacheRecord($item,$view,$parsers,$poplists,$original_item);
}
}
}
/*
Function: cacheRecord
Caches a single item in a view to the bigtree_module_view_cache table.
Parameters:
item - The database record to cache.
view - The related view entry.
parsers - An array of manual parsers set in the view.
poplists - An array of populated lists that relate to the item.
original_item - The item without pending changes applied for GBP.
*/
static function cacheRecord($item,$view,$parsers,$poplists,$original_item) {
// If we have a filter function, ask it first if we should cache it
if (isset($view["options"]["filter"]) && $view["options"]["filter"]) {
if (!call_user_func($view["options"]["filter"],$item)) {
return false;
}
}
global $cms;
// Setup the fields and VALUES to INSERT INTO the cache table.
$status = "l";
$pending_owner = 0;
if ($item["bigtree_changes"]) {
$status = "c";
} elseif (isset($item["bigtree_pending"])) {
$status = "p";
$pending_owner = $item["bigtree_pending_owner"];
}
$fields = array("view","id","status","position","approved","archived","featured","pending_owner");
// No more notices.
$approved = isset($item["approved"]) ? $item["approved"] : "";
$featured = isset($item["featured"]) ? $item["featured"] : "";
$archived = isset($item["archived"]) ? $item["archived"] : "";
$position = isset($item["position"]) ? $item["position"] : 0;
$vals = array("'".$view["id"]."'","'".$item["id"]."'","'$status'","'$position'","'$approved'","'$archived'","'$featured'","'".$pending_owner."'");
// Figure out which column we're going to use to sort the view.
if ($view["options"]["sort"]) {
$sort_field = BigTree::nextSQLColumnDefinition(ltrim($view["options"]["sort"],"`"));
} else {
$sort_field = false;
}
// Let's see if we have a grouping field. If we do, let's get all that info and cache it as well.
if (isset($view["options"]["group_field"]) && $view["options"]["group_field"]) {
$value = $item[$view["options"]["group_field"]];
// Check for a parser
if (isset($view["options"]["group_parser"]) && $view["options"]["group_parser"]) {
$value = BigTree::runParser($item,$value,$view["options"]["group_parser"]);
}
$fields[] = "group_field";
$vals[] = "'".sqlescape($value)."'";
if (is_numeric($value) && $view["options"]["other_table"]) {
$f = sqlfetch(sqlquery("SELECT * FROM `".$view["options"]["other_table"]."` WHERE id = '$value'"));
if ($view["options"]["ot_sort_field"]) {
$fields[] = "group_sort_field";
$vals[] = "'".sqlescape($f[$view["options"]["ot_sort_field"]])."'";
}
}
}
// Check for a nesting column
if (isset($view["options"]["nesting_column"]) && $view["options"]["nesting_column"]) {
$fields[] = "group_field";
$vals[] = "'".sqlescape($item[$view["options"]["nesting_column"]])."'";
}
// Group based permissions data
if (isset($view["gbp"]["enabled"]) && $view["gbp"]["table"] == $view["table"]) {
$fields[] = "gbp_field";
$vals[] = "'".sqlescape($item[$view["gbp"]["group_field"]])."'";
$fields[] = "published_gbp_field";
$vals[] = "'".sqlescape($original_item[$view["gbp"]["group_field"]])."'";
}
// Run parsers
foreach ($parsers as $key => $parser) {
$item[$key] = BigTree::runParser($item,$item[$key],$parser);
}
// Run pop lists
foreach ($poplists as $key => $pop) {
$f = sqlfetch(sqlquery("SELECT `".$pop["description"]."` FROM `".$pop["table"]."` WHERE id = '".$item[$key]."'"));
if (is_array($f)) {
$item[$key] = current($f);
}
}
// Insert into the view cache
if ($view["type"] == "images" || $view["type"] == "images-grouped") {
$fields[] = "column1";
$vals[] = "'".$item[$view["options"]["image"]]."'";
} else {
$x = 1;
foreach ($view["fields"] as $field => $options) {
$item[$field] = $cms->replaceInternalPageLinks($item[$field]);
$fields[] = "column$x";
if (isset($parsers[$field]) && $parsers[$field]) {
$vals[] = "'".sqlescape(BigTree::safeEncode($item[$field]))."'";
} else {
$vals[] = "'".sqlescape(BigTree::safeEncode(strip_tags($item[$field])))."'";
}
$x++;
}
}
if ($sort_field) {
$fields[] = "`sort_field`";
$vals[] = "'".sqlescape($item[$sort_field])."'";
}
sqlquery("INSERT INTO bigtree_module_view_cache (".implode(",",$fields).") VALUES (".implode(",",$vals).")");
}
/*
Function: cacheViewData
Grabs all the data from a view and does parsing on it based on automatic assumptions and manual parsers.
Parameters:
view - The view entry to cache data for.
*/
static function cacheViewData($view) {
// See if we already have cached data.
if (sqlrows(sqlquery("SELECT id FROM bigtree_module_view_cache WHERE view = '".$view["id"]."'"))) {
return false;
}
// Find out what module we're using so we can get the gbp_field
$action = sqlfetch(sqlquery("SELECT module FROM bigtree_module_actions WHERE view = '".$view["id"]."'"));
$module = sqlfetch(sqlquery("SELECT gbp FROM bigtree_modules WHERE id = '".$action["module"]."'"));
$view["gbp"] = json_decode($module["gbp"],true);
// Setup information on our parsers and populated lists.
$form = self::getRelatedFormForView($view);
$view["fields"] = is_array($view["fields"]) ? $view["fields"] : array();
$parsers = array();
$poplists = array();
foreach ($view["fields"] as $key => $field) {
// Get the form field
$ff = $form["fields"][$key];
if ($field["parser"]) {
$parsers[$key] = $field["parser"];
} elseif ($ff["type"] == "list" && $ff["list_type"] == "db") {
$poplists[$key] = array("description" => $ff["pop-description"], "table" => $ff["pop-table"]);
}
}
// See if we need to modify the cache table to add more fields.
$field_count = count($view["fields"]);
$table_description = BigTree::describeTable("bigtree_module_view_cache");
$cc = count($table_description["columns"]) - 13;
while ($field_count > $cc) {
$cc++;
sqlquery("ALTER TABLE bigtree_module_view_cache ADD COLUMN column$cc TEXT NOT NULL AFTER column".($cc-1));
}
// Cache all records that are published (and include their pending changes)
$q = sqlquery("SELECT `".$view["table"]."`.*,bigtree_pending_changes.changes AS bigtree_changes FROM `".$view["table"]."` LEFT JOIN bigtree_pending_changes ON (bigtree_pending_changes.item_id = `".$view["table"]."`.id AND bigtree_pending_changes.table = '".$view["table"]."')");
while ($item = sqlfetch($q)) {
$original_item = $item;
if ($item["bigtree_changes"]) {
$changes = json_decode($item["bigtree_changes"],true);
foreach ($changes as $key => $change) {
$item[$key] = $change;
}
}
self::cacheRecord($item,$view,$parsers,$poplists,$original_item);
}
$q = sqlquery("SELECT * FROM bigtree_pending_changes WHERE `table` = '".$view["table"]."' AND item_id IS NULL");
while ($f = sqlfetch($q)) {
$item = json_decode($f["changes"],true);
$item["bigtree_pending"] = true;
$item["bigtree_pending_owner"] = $f["user"];
$item["id"] = "p".$f["id"];
self::cacheRecord($item,$view,$parsers,$poplists,$item);
}
return true;
}
/*
Function: changeExists
Checks to see if a change exists for a given item in the bigtree_pending_changes table.
Parameters:
table - The table the item is from.
id - The ID of the item.
Returns:
true or false
*/
static function changeExists($table,$id) {
$f = sqlfetch(sqlquery("SELECT id FROM bigtree_pending_changes WHERE `table` = '".sqlescape($table)."' AND item_id = '".sqlescape($id)."'"));
if ($f) {
return true;
}
return false;
}
/*
Function: clearCache
Clears the cache of a view or all views with a given table.
Parameters:
view - The view id or view entry to clear the cache for or a table to find all views for (and clear their caches).
*/
static function clearCache($view) {
if (is_array($view)) {
sqlquery("DELETE FROM bigtree_module_view_cache WHERE view = '".sqlescape($view["id"])."'");
} elseif (is_numeric($view)) {
sqlquery("DELETE FROM bigtree_module_view_cache WHERE view = '$view'");
} else {
$q = sqlquery("SELECT id FROM bigtree_module_views WHERE `table` = '".sqlescape($view)."'");
while ($f = sqlfetch($q)) {
sqlquery("DELETE FROM bigtree_module_view_cache WHERE view = '".$f["id"]."'");
}
}
}
/*
Function: createItem
Creates an entry in the database for an auto module form.
Parameters:
table - The table to put the data in.
data - An array of form data to enter into the table. This function determines what data in the array applies to a column in the database and discards the rest.
many_to_many - Many to many relationship entries.
tags - Tags for the entry.
Returns:
The id of the new entry in the database.
*/
static function createItem($table,$data,$many_to_many = array(),$tags = array()) {
global $admin,$module;
$table_description = BigTree::describeTable($table);
$query_fields = array();
$query_vals = array();
foreach ($data as $key => $val) {
if (array_key_exists($key,$table_description["columns"])) {
$query_fields[] = "`".$key."`";
if ($val === "NULL" || $val == "NOW()") {
$query_vals[] = $val;
} else {
if (is_array($val)) {
$val = json_encode(BigTree::translateArray($val));
}
$query_vals[] = "'".sqlescape($val)."'";
}
}
}
// Insert, if there's a failure return false instead of doing the rest
$success = sqlquery("INSERT INTO `$table` (".implode(",",$query_fields).") VALUES (".implode(",",$query_vals).")");
if (!$success) {
return false;
}
$id = sqlid();
// Handle many to many
foreach ($many_to_many as $mtm) {
$table_description = BigTree::describeTable($mtm["table"]);
if (is_array($mtm["data"])) {
$x = count($mtm["data"]);
foreach ($mtm["data"] as $position => $item) {
if (isset($table_description["columns"]["position"])) {
sqlquery("INSERT INTO `".$mtm["table"]."` (`".$mtm["my-id"]."`,`".$mtm["other-id"]."`,`position`) VALUES ('$id','$item','$x')");
} else {
sqlquery("INSERT INTO `".$mtm["table"]."` (`".$mtm["my-id"]."`,`".$mtm["other-id"]."`) VALUES ('$id','$item')");
}
$x--;
}
}
}
// Handle the tags
sqlquery("DELETE FROM bigtree_tags_rel WHERE `table` = '".sqlescape($table)."' AND entry = '$id'");
if (is_array($tags)) {
foreach ($tags as $tag) {
sqlquery("DELETE FROM bigtree_tags_rel WHERE `table` = '".sqlescape($table)."' AND entry = $id AND tag = $tag");
sqlquery("INSERT INTO bigtree_tags_rel (`table`,`entry`,`tag`) VALUES ('".sqlescape($table)."',$id,$tag)");
}
}
self::cacheNewItem($id,$table);
if ($admin) {
$admin->track($table,$id,"created");
}
return $id;
}
/*
Function: createPendingItem
Creates an entry in the bigtree_pending_changes table for an auto module form.
Parameters:
module - The module for the entry.
table - The table to put the data in.
data - An array of form data to enter into the table. This function determines what data in the array applies to a column in the database and discards the rest.
many_to_many - Many to many relationship entries.
tags - Tags for the entry.
Returns:
The id of the new entry in the bigtree_pending_changes table.
*/
static function createPendingItem($module,$table,$data,$many_to_many = array(),$tags = array()) {
global $admin;
foreach ($data as $key => $val) {
if ($val === "NULL") {
$data[$key] = "";
}
if (is_array($val)) {
$data[$key] = BigTree::translateArray($val);
}
}
$data = sqlescape(json_encode($data));
$many_data = sqlescape(json_encode($many_to_many));
$tags_data = sqlescape(json_encode($tags));
sqlquery("INSERT INTO bigtree_pending_changes (`user`,`date`,`table`,`changes`,`mtm_changes`,`tags_changes`,`module`,`type`) VALUES (".$admin->ID.",NOW(),'$table','$data','$many_data','$tags_data','$module','NEW')");
$id = sqlid();
self::cacheNewItem($id,$table,true);
if ($admin) {
$admin->track($table,"p$id","created-pending");
}
return $id;
}
/*
Function: deleteItem
Deletes an item from the given table and removes any pending changes, then uncaches it from its views.
Parameters:
table - The table to delete an entry from.
id - The id of the entry.
*/
static function deleteItem($table,$id) {
global $admin;
$id = sqlescape($id);
sqlquery("DELETE FROM `$table` WHERE id = '$id'");
sqlquery("DELETE FROM bigtree_pending_changes WHERE `table` = '$table' AND item_id = '$id'");
self::uncacheItem($id,$table);
if ($admin) {
$admin->track($table,$id,"deleted");
}
}
/*
Function: deleteItem
Deletes a pending item from bigtree_pending_changes and uncaches it.
Parameters:
table - The table the entry would have been in (should it have ever been published).
id - The id of the pending entry.
*/
static function deletePendingItem($table,$id) {
global $admin;
$id = sqlescape($id);
sqlquery("DELETE FROM bigtree_pending_changes WHERE `table` = '$table' AND id = '$id'");
self::uncacheItem("p$id",$table);
if ($admin) {
$admin->track($table,"p$id","deleted-pending");
}
}
/*
Function: getDependantViews
Returns all views that have a dependance on a given table.
Parameters:
table - Table name
Returns:
An array of rows from bigtree_module_views.
*/
static function getDependantViews($table) {
$views = array();
$q = sqlquery("SELECT * FROM bigtree_module_views WHERE options LIKE '%".sqlescape($table)."%'");
while ($f = sqlfetch($q)) {
$views[] = $f;
}
return $views;
}
/*
Function: getEditAction
Returns a module action for the given module and form IDs.
Parameters:
module - Module ID
form - Form ID
Returns:
A bigtree_module_actions entry.
*/
static function getEditAction($module,$form) {
return sqlfetch(sqlquery("SELECT * FROM bigtree_module_actions WHERE form = '".sqlescape($form)."' AND module = '".sqlescape($module)."' AND route LIKE 'edit%'"));
}
/*
Function: getEmbedForm
Returns a module embeddable form.
Parameters:
id - The id of the form.
decode_ipl - Whether we want to decode internal page link on the css file (defaults to true)
Returns:
A module form entry with fields decoded.
*/
static function getEmbedForm($id,$decode_ipl = true) {
global $cms;
if (is_array($id)) {
$id = $id["id"];
}
$form = sqlfetch(sqlquery("SELECT * FROM bigtree_module_embeds WHERE id = '".sqlescape($id)."'"));
$form["fields"] = json_decode($form["fields"],true);
if ($decode_ipl) {
$form["css"] = $cms->getInternalPageLink($form["css"]);
}
return $form;
}
/*
Function: getEmbedFormByHash
Returns a module embeddable form.
Parameters:
hash - The hash of the form.
Returns:
A module form entry with fields decoded.
*/
static function getEmbedFormByHash($hash) {
global $cms;
$form = sqlfetch(sqlquery("SELECT * FROM bigtree_module_embeds WHERE hash = '".sqlescape($hash)."'"));
$form["fields"] = json_decode($form["fields"],true);
$form["css"] = $cms->getInternalPageLink($form["css"]);
return $form;
}
/*
Function: getFilterQuery
Returns a query string that is used for searching views based on group permissions.
Parameters:
view - The view to create a filter for.
Returns:
A set of MySQL statements that filter out information the user cannot access.
*/
static function getFilterQuery($view) {
global $admin;
$module = $admin->getModule(self::getModuleForView($view));
if (isset($module["gbp"]["enabled"]) && $module["gbp"]["enabled"] && $module["gbp"]["table"] == $view["table"]) {
$groups = $admin->getAccessGroups($module["id"]);
if (is_array($groups)) {
$gfl = array();
foreach ($groups as $g) {
if ($view["type"] == "nested" && $module["gbp"]["group_field"] == $view["options"]["nesting_column"]) {
$gfl[] = "`id` = '".sqlescape($g)."' OR `gbp_field` = '".sqlescape($g)."'";
} else {
$gfl[] = "`gbp_field` = '".sqlescape($g)."'";
}
}
return " AND (".implode(" OR ",$gfl).")";
}
}
return "";
}
/*
Function: getForm
Returns a module form.
Parameters:
id - The id of the form.
decode_ipl - Whether we want to decode internal page link on the return url (defaults to true)
Returns:
A module form entry with fields decoded.
*/
static function getForm($id,$decode_ipl = true) {
global $cms;
if (is_array($id)) {
$id = $id["id"];
}
$form = sqlfetch(sqlquery("SELECT * FROM bigtree_module_forms WHERE id = '".sqlescape($id)."'"));
$form["fields"] = json_decode($form["fields"],true);
if ($decode_ipl) {
$form["return_url"] = $cms->getInternalPageLink($form["return_url"]);
}
return $form;
}
/*
Function: getGroupsForView
Returns all groups in the view cache for a view.
Parameters:
view - The view entry.
Returns:
An array of groups.
*/
static function getGroupsForView($view) {
$groups = array();
$query = "SELECT DISTINCT(group_field) FROM bigtree_module_view_cache WHERE view = '".$view["id"]."'";
if (isset($view["options"]["ot_sort_field"]) && $view["options"]["ot_sort_field"]) {
// We're going to determine whether the group sort field is numeric or not first.
$is_numeric = true;
$q = sqlquery("SELECT DISTINCT(group_sort_field) FROM bigtree_module_view_cache WHERE view = '".$view["id"]."'");
while ($f = sqlfetch($q)) {
if (!is_numeric($f["group_sort_field"])) {
$is_numeric = false;
}
}
// If all of the groups are numeric we'll cast the sorting field as decimal so it's not interpretted as a string.
if ($is_numeric) {
$query .= " ORDER BY CAST(group_sort_field AS DECIMAL) ".$view["options"]["ot_sort_direction"];
} else {
$query .= " ORDER BY group_sort_field ".$view["options"]["ot_sort_direction"];
}
} else {
$query .= " ORDER BY group_field";
}
$q = sqlquery($query);
// If there's another table, we're going to query it separately.
if ($view["options"]["other_table"] && !$view["options"]["group_parser"]) {
$otq = array();
while ($f = sqlfetch($q)) {
$otq[] = "id = '".$f["group_field"]."'";
// We need to instatiate all of these as empty first in case the database relationship doesn't exist.
$groups[$f["group_field"]] = "";
}
if (count($otq)) {
if ($view["options"]["ot_sort_field"]) {
$otsf = $view["options"]["ot_sort_field"];
if ($view["options"]["ot_sort_direction"]) {
$otsd = $view["options"]["ot_sort_direction"];
} else {
$otsd = "ASC";
}
} else {
$otsf = "id";
$otsd = "ASC";
}
$q = sqlquery("SELECT id,`".$view["options"]["title_field"]."` AS `title` FROM `".$view["options"]["other_table"]."` WHERE ".implode(" OR ",$otq)." ORDER BY $otsf $otsd");
while ($f = sqlfetch($q)) {
$groups[$f["id"]] = $f["title"];
}
}
} else {
while ($f = sqlfetch($q)) {
$groups[$f["group_field"]] = $f["group_field"];
}
}
return $groups;
}
/*
Function: getItem
Returns an entry from a table with all its related information.
If a pending ID is passed in (prefixed with a p) getPendingItem is called instead.
Parameters:
table - The table to pull the entry from.
id - The id of the entry.
Returns:
An array with the following key/value pairs:
"item" - The entry from the table with pending changes already applied.
"tags" - A list of tags for the entry.
Returns false if the entry could not be found.
*/
static function getItem($table,$id) {
global $cms;
// The entry is pending if there's a "p" prefix on the id
if (substr($id,0,1) == "p") {
return self::getPendingItem($table,$id);
}
// Otherwise it's a live entry
$item = sqlfetch(sqlquery("SELECT * FROM `$table` WHERE id = '$id'"));
if (!$item) {
return false;
}
$tags = self::getTagsForEntry($table,$id);
// Process the internal page links, turn json_encoded arrays into arrays.
foreach ($item as $key => $val) {
if (is_array(json_decode($val,true))) {
$item[$key] = BigTree::untranslateArray(json_decode($val,true));
} else {
$item[$key] = $cms->replaceInternalPageLinks($val);
}
}
return array("item" => $item, "tags" => $tags);
}
/*
Function: getModuleForForm
Returns the associated module id for the given form.
Parameters:
form - Either a form entry or form id.
Returns:
The id of the module the form is a member of.
*/
static function getModuleForForm($form) {
if (is_array($form)) {
$form = $form["id"];
}
$f = sqlfetch(sqlquery("SELECT * FROM bigtree_module_actions WHERE form = '$form'"));
return $f["module"];
}
/*
Function: getModuleForView
Returns the associated module id for the given view.
Parameters:
view - Either a view entry or view id.
Returns:
The id of the module the view is a member of.
*/
static function getModuleForView($view) {
if (is_array($view)) {
$view = $view["id"];
}
$f = sqlfetch(sqlquery("SELECT * FROM bigtree_module_actions WHERE view = '$view'"));
return $f["module"];
}
/*
Function: getPendingItem
Gets an entry from a table with all its related information and pending changes applied.
Parameters:
table - The table to pull the entry from.
id - The id of the entry.
Returns:
An array with the following key/value pairs:
"item" - The entry from the table with pending changes already applied.
"mtm" - A list of many to many pending changes.
"tags" - A list of tags for the entry.
"status" - Whether the item is pending ("pending"), published ("published"), or has changes ("updated") awaiting publish.
Returns false if the entry could not be found.
*/
static function getPendingItem($table,$id) {
global $cms,$module;
$status = "published";
$many_to_many = array();
$resources = array();
$owner = false;
// The entry is pending if there's a "p" prefix on the id
if (substr($id,0,1) == "p") {
$change = sqlfetch(sqlquery("SELECT * FROM bigtree_pending_changes WHERE id = '".substr($id,1)."'"));
if (!$change) {
return false;
}
$item = json_decode($change["changes"],true);
$many_to_many = json_decode($change["mtm_changes"],true);
$temp_tags = json_decode($change["tags_changes"],true);
$tags = array();
if (!empty($temp_tags)) {
foreach ($temp_tags as $tid) {
$tags[] = sqlfetch(sqlquery("SELECT * FROM bigtree_tags WHERE id = '$tid'"));
}
}
$status = "pending";
$owner = $change["user"];
// Otherwise it's a live entry
} else {
$item = sqlfetch(sqlquery("SELECT * FROM `$table` WHERE id = '$id'"));
if (!$item) {
return false;
}
// Apply changes that are pending
$change = sqlfetch(sqlquery("SELECT * FROM bigtree_pending_changes WHERE `table` = '$table' AND `item_id` = '$id'"));
if ($change) {
$status = "updated";
$changes = json_decode($change["changes"],true);
foreach ($changes as $key => $val) {
$item[$key] = $val;
}
$many_to_many = json_decode($change["mtm_changes"],true);
$temp_tags = json_decode($change["tags_changes"],true);
$tags = array();
if (is_array($temp_tags)) {
foreach ($temp_tags as $tid) {
$tags[] = sqlfetch(sqlquery("SELECT * FROM bigtree_tags WHERE id = '$tid'"));
}
}
// If there's no pending changes, just pull the tags
} else {
$tags = self::getTagsForEntry($table,$id);
}
}
// Process the internal page links, turn json_encoded arrays into arrays.
foreach ($item as $key => $val) {
if (is_array($val)) {
$item[$key] = BigTree::untranslateArray($val);
} elseif (is_array(json_decode($val,true))) {
$item[$key] = BigTree::untranslateArray(json_decode($val,true));
} else {
$item[$key] = $cms->replaceInternalPageLinks($val);
}
}
return array("item" => $item, "mtm" => $many_to_many, "tags" => $tags, "status" => $status, "owner" => $owner);
}
/*
Function: getRelatedFormForReport
Returns the form for the same table as the given report.
Parameters:
report - A report entry.
Returns:
A form entry with fields decoded.
*/
static function getRelatedFormForReport($report) {
$f = sqlfetch(sqlquery("SELECT id FROM bigtree_module_forms WHERE `table` = '".sqlescape($report["table"])."'"));
return self::getForm($f["id"]);
}
/*
Function: getRelatedFormForView
Returns the form for the same table as the given view.
Parameters:
view - A view entry.
Returns:
A form entry with fields decoded.
*/
static function getRelatedFormForView($view) {
if ($view["related_form"]) {
return self::getForm($view["related_form"]);
}
$f = sqlfetch(sqlquery("SELECT id FROM bigtree_module_forms WHERE `table` = '".sqlescape($view["table"])."'"));
return self::getForm($f["id"]);
}
/*
Function: getRelatedViewForForm
Returns the view for the same table as the given form.
Parameters:
form - A form entry.
Returns:
A view entry.
*/
static function getRelatedViewForForm($form) {
// Try to find a view that's relating back to this form first
$f = sqlfetch(sqlquery("SELECT id FROM bigtree_module_views WHERE `related_form` = '".$form["id"]."'"));
// Fall back to any view that uses the same table
if (!$f) {
$f = sqlfetch(sqlquery("SELECT id FROM bigtree_module_views WHERE `table` = '".sqlescape($form["table"])."'"));
}
return self::getView($f["id"]);
}
/*
Function: getRelatedViewForReport
Returns the view for the same table as the given report.
Parameters:
report - A report entry.
Returns:
A view entry.
*/
static function getRelatedViewForReport($report) {
$f = sqlfetch(sqlquery("SELECT id FROM bigtree_module_views WHERE `table` = '".sqlescape($report["table"])."'"));
return self::getView($f["id"]);
}
/*
Function: getReport
Returns a report with the filters and fields decoded.
Parameters:
id - The ID of the report
Returns:
An array of report information.
*/
static function getReport($id) {
$f = sqlfetch(sqlquery("SELECT * FROM bigtree_module_reports WHERE id = '".sqlescape($id)."'"));
$f["fields"] = json_decode($f["fields"],true);
$f["filters"] = json_decode($f["filters"],true);
return $f;
}
/*
Function: getReportResults
Returns rows from the table that match the filters provided.
Parameters:
report - A bigtree_module_reports entry.
view - A bigtree_module_views entry.
form - A bigtree_module_forms entry.
filters - The submitted filters to run.
sort_field - The field to sort by.
sort_direction - The direction to sort by.
Returns:
An array of entries from the report's table.
*/
static function getReportResults($report,$view,$form,$filters,$sort_field = "id",$sort_direction = "DESC") {
$where = $items = $parsers = $poplists = array();
// Figure out if we have db populated lists and parsers
if ($report["type"] == "view") {
foreach ($view["fields"] as $key => $field) {
if ($field["parser"]) {
$parsers[$key] = $field["parser"];
}
}
}
foreach ($form["fields"] as $key => $field) {
if ($field["type"] == "list" && $field["list_type"] == "db") {
$poplists[$key] = array("description" => $form["fields"][$key]["pop-description"], "table" => $form["fields"][$key]["pop-table"]);
}
}
$query = "SELECT * FROM `".$report["table"]."`";
foreach ($report["filters"] as $id => $filter) {
if ($filters[$id]) {
// Search field
if ($filter["type"] == "search") {
$where[] = "`$id` LIKE '%".sqlescape($filters[$id])."%'";
// Dropdown
} elseif ($filter["type"] == "dropdown") {
$where[] = "`$id` = '".sqlescape($filters[$id])."'";
// Yes / No / Both
} elseif ($filter["type"] == "boolean") {
if ($filters[$id] == "Yes") {
$where[] = "(`$id` = 'on' OR `$id` = '1' OR `$id` != '')";
} elseif ($filters[$id] == "No") {
$where[] = "(`$id` = '' OR `$id` = '0' OR `$id` IS NULL)";
}
// Date Range
} elseif ($filter["type"] == "date-range") {
if ($filter[$id]["start"]) {
$where[] = "`$id` >= '".sqlescape($filter[$id]["start"])."'";
}
if ($filter[$id]["end"]) {
$where[] = "`$id` <= '".sqlescape($filter[$id]["end"])."'";
}
}
}
}