-
Notifications
You must be signed in to change notification settings - Fork 0
/
RockFinder2.module.php
1219 lines (1065 loc) · 33.4 KB
/
RockFinder2.module.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 namespace ProcessWire;
/**
* RockFinder2
*
* @author Bernhard Baumrock, 08.08.2019
* @license Licensed under MIT
*/
class RockFinder2 extends WireData implements Module {
public static function getModuleInfo() {
return [
'title' => 'RockFinder2',
'version' => '0.0.6',
'summary' => 'RockFinder2',
'icon' => 'search',
'requires' => ['TracyDebugger'],
'installs' => ['ProcessRockFinder2'],
'autoload' => 'template=admin',
'singular' => true,
];
}
/**
* RockFinder data object
*/
private $dataObject;
/**
* Callable to check for access
*
* By default this will only return true for superusers.
* @var callback
*/
public $hasAccess;
/**
* @var string name of this finder
*/
public $name;
/**
* @var array|string pw-selector to find base pages
*/
public $selector;
/**
* The query that selects all columns (final data) for this finder
* @var DatabaseQuerySelect
*/
public $query;
/**
* Columns that are added to this finder
* @var WireArray
*/
public $columns;
/**
* Array of column names in 'pages' DB table
*/
public $baseColumns;
/**
* Main data
* @var array
*/
private $mainData;
/**
* Reference to RockFinder2 api variable
*/
public $rf;
/**
* Show debug info?
* @var bool
*/
public $debug;
/**
* Array of options
* @var array
*/
public $options = [];
/**
* Array of relations
* @var array
*/
private $relations = [];
private $_relations = [];
/**
* Class constructor
*/
public function __construct() {
$this->name = uniqid();
// init columns array
$this->columns = $this->wire(new WireArray);
// default hasAccess callback
$this->hasAccess = function() {
return $this->user->isSuperuser();
};
}
/**
* Initialize the module (optional)
*/
public function init() {
// set api variable on first run
if(!$this->wire->RockFinder2) {
$this->name = 'rf2';
$this->wire->set('RockFinder2', $this);
$this->url = $this->config->urls->root.trim($this->url, "/")."/";
// get base table columns
// this is only attached to the base instance for better performance
$db = $this->config->dbName;
$result = $this->database->query("SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='$db'
AND `TABLE_NAME`='pages';");
$this->baseColumns = $result->fetchAll(\PDO::FETCH_COLUMN);
// handle API Endpoint requests
$this->addHookBefore('ProcessPageView::pageNotFound', $this, 'apiEndpoint');
// load JS
$this->config->scripts->add($this->config->urls($this). 'RockFinder2.js');
$this->addHookAfter("Page(template=admin)::render", function(HookEvent $event) {
if($this->config->ajax) return;
$html = $event->return;
$tag = $this->getScriptTag();
$event->return = str_replace('</head>', $tag.'</head>', $html);
});
// create backup path
$path = $this->config->paths->assets . 'RockFinder2/bak/';
$this->files->mkdir($path, true);
$this->bak = $path;
}
// Add reference to RockFinder2 api var to this instance
$this->rf = $this->wire->RockFinder2;
// attach column types via hook
$this->addHookAfter("RockFinder2::getCol", $this, 'addColumnTypes');
// attach renderers
$this->addHookAfter("RockFinder2::render(debug)", $this, 'debugRenderer');
$this->addHookAfter("RockFinder2::render(gzip)", $this, 'gzipRenderer');
// add dir to RockTabulator
$this->addHookAfter('RockTabulator::getDirs', function($event) {
$rt = $event->object;
$dirs = $event->return;
$dirs[] = $rt->toUrl(__DIR__ . '/tabulators');
$event->return = $dirs;
});
}
/* ########## general ########## */
/**
* Return RockFinder2 JavaScript init tag
* @return string
*/
public function getScriptTag() {
return $this->files->render(__DIR__.'/includes/script.php', [
'conf' => [
'url' => $this->url,
],
]);
}
/**
* Handle API Endpoint requests
* @param HookEvent $event
* @return void
*/
public function apiEndpoint($event) {
if(!$this->url) throw new WireException("You need to set an API Endpoint URL");
// is this the API Endpoint url?
$url = $this->config->urls->root.ltrim($event->arguments('url'), '/');
// if url does not match do a regular 404
if($url != $this->url) return;
// get finder that should be executed
$input = $this->input;
$name = $input->post('name', 'string') ?: $input->get('name', 'string');
// execute finder
if($name) {
$finder = $this->getByName($name);
if($finder) $finder->execute();
else throw new WireException("$name returns invalid result");
}
else {
$this->executeSandbox();
}
// todo: log errors (status codes)
}
/**
* Execute given finder
* @param null|string|RockFinder2 $finder
* @return void
*/
public function execute($finder = null) {
// if no finder is set we execute this one
if(!$finder) $this->output();
// if finder is a RockFinder2 we execute this one
if($finder instanceof RockFinder2) $finder->output();
// if it is a string get it and execute it
$file = $this->getFiles($finder);
$this->executeFile($file);
}
/**
* Send output to browser
*
* This method can be hooked so you can attach custom renderers.
*
* @return void
*/
public function output() {
$type = $this->input->get('type', 'string');
if(!$type) $type = $this->input->post('type', 'string');
if(!$type) $type = 'gzip';
// check access
$this->checkAccess($type);
// log request
if($this->debug) {
fl('See PW logs for more RockFinder2 debug info!');
$this->log("Finder {$this->name} SQL: " . $this->getSQL());
}
// render output
echo $this->render($type);
die();
}
/**
* Render content of this finder
*
* By default this returns gzip data as application/json. This can be
* modified via hooks, so you can attach all kinds of custom renderers.
*/
public function ___render($type) {}
/**
* Execute sandbox finder
*/
public function executeSandbox() {
if(!$this->user->isSuperuser()) {
throw new WireException("Only SuperUsers have access to the sandbox");
}
if($this->input->requestMethod() != 'POST') {
throw new WireException("The sandbox is only available via POST");
}
// get code from input and write it to a temp file
$tmp = $this->files->tempDir($this->className);
$file = $tmp.uniqid().".php";
file_put_contents($file, $this->input->post('code'));
$this->executeFile($file, true);
}
/**
* Execute finder file
* @param string $file
* @param bool $debug are we in the debug mode?
* @return void
*/
public function executeFile($file, $debug = false) {
try {
/** @var RockFinder2 $rf */
$rf = $this->files->render($file);
if(!$rf instanceof RockFinder2) {
// if superuser: try to eval to get proper error message
if($this->user->isSuperuser()) {
$php = file_get_contents($file);
if(strpos($php, '<?php') === 0) $php = substr($php, 5);
eval($php);
}
throw new WireException("Your code must return a RockFinder2 instance!");
}
$rf->debug = $debug;
$rf->execute();
} catch (\Throwable $th) {
$this->die($th->getMessage());
}
}
/**
* Return JSON error
* @param string $msg
* @return json
*/
public function err($msg) {
$this->log($msg);
return (object)[
'error' => $msg,
];
}
/**
* Return error json response
*/
public function die($msg) {
header("Content-type: application/json");
die(json_encode($this->err($msg)));
}
/**
* Get all backup files for given finder
* @return array
*/
public function getBackupFiles($name) {
$files = $this->files->find($this->bak, ['extensions'=>['php']]);
rsort($files);
$num = 0;
$max = $this->numBakFiles;
$arr = [];
foreach($files as $file) {
$info = (object)pathinfo($file);
if(strpos($info->basename, $name) !== 0) continue;
// delete old files if a maximum number is set
$num++;
if($max AND $num > $max) {
$this->files->unlink($file);
continue;
}
// add file to array
$arr[] = $file;
}
return $arr;
}
/**
* Check access to this finder
* @param string $type
* @return bool
*/
public function checkAccess($type = null) {
// check access
if(!is_callable($this->hasAccess)) throw new WireException("hasAccess must be callable");
if(!$this->hasAccess->__invoke($type)) throw new WireException("No access!");
return true;
}
/**
* Get finder by name
* @param string $name
* @param array $vars
* @return RockFinder2
*/
public function getByName($name, $vars = []) {
if(!$name) throw new WireException("Please specify a name");
$file = $this->getFiles($name);
if(!$file) throw new WireException("File for $name not found");
$path = $this->config->paths->assets.$this->className;
$rf = $this->files->render($file, $vars, ['allowedPaths' => [$path]]);
if($rf instanceof RockFinder2) return $rf;
return false;
}
/**
* Add or-group to given selector
* @param array $selector
* @param array $items
* @return void
*/
public function orGroup(&$selector, $items) {
$group = uniqid();
foreach($items as $item) {
$selector[] = [
'field' => $item[0],
'operator' => $item[1],
'value' => $item[2],
'group' => $group,
];
}
}
/**
* Same as getByName but does not throw exceptions if files do not exist
* @return mixed
*/
public function findByName($name) {
try {
$finder = $this->getByName($name);
return $finder;
} catch (\Throwable $th) {
return false;
}
}
/**
* Get all finder files
*
* If name is specified return only this single file (case sensitive).
*
* @param string $name
* @return string|array
*/
public function getFiles($name = null) {
$path = $this->config->paths->assets . 'RockFinder2';
$files = $this->files->find($path, ['extensions' => ['php']]);
if($name) {
foreach($files as $file) {
if(pathinfo($file)['filename'] == $name) return $file;
}
throw new WireException("File for $name not found");
}
return $files ?: [];
}
/**
* Get php file that corresponds to finder
* @return string
*/
public function getFile($finder) {
$file = false;
try {
$file = $this->getFiles($finder);
} catch (\Throwable $th) {
// don't throw errors
}
return $file;
}
/* ########## sql query constructor ########## */
/**
* Set selector of this finder
* @param string|array|DatabaseQuerySelect $selector
* @param array $options
* @return void
*/
public function find($selector, $options = []) {
$this->selector = $selector;
$defaults = [
// ignore sort order of initial page find operation
// this can significantly increase performance
'nosort' => false,
];
$options = array_merge($defaults, $options);
if($selector instanceof DatabaseQuerySelect) {
$query = $selector;
}
else {
// get ids of base selector
$selector = $this->wire(new Selectors($selector));
$pf = $this->wire(new PageFinder());
$query = $pf->find($selector, ['returnQuery' => true]);
// modify the base query to our needs
// we only need the page id
// setting the alias via AS is necessary for hideColumns() feature
$query->set('select', ['`pages`.`id` AS `id`']);
}
// if possible ignore sort order for better performance
if($options['nosort']) $query->set('orderby', []);
// save this query object for later
$this->query = $query;
}
/**
* Add columns to finder
* @param array $columns
*/
public function addColumns($columns) {
if(!$this->query) throw new WireException("Setup the selector before calling addColumns()");
if(!is_array($columns)) throw new WireException("Parameter must be an array");
// add columns one by one
foreach($columns as $k=>$v) {
// skip null value columns
if($v === null) continue;
// if key is integer we take the value instead
if(is_int($k)) {
$k = $v;
$v = null;
}
// setup initial column name
$column = $k;
// if a type is set, get type
// syntax is type:column, eg addColumns(['mytype:myColumn'])
$type = null;
if(strpos($column, ":")) {
$arr = explode(":", $column);
$type = $arr[0];
$column = $arr[1];
}
// column name alias
$alias = $v;
// add this column
$this->addColumn($column, $type, $alias);
}
}
/**
* Hide columns from final output
*
* This does NOT remove the columns from the columns array of the finder.
* The columns must exist there so that joins can be performed.
*
* @param array $columns
* @return void
*/
public function hideColumns($columns) {
$selects = $this->query->select;
foreach($columns as $column) {
// find select statement for this column
foreach($selects as $i=>$select) {
$select = strtolower($select);
$test = " as `$column`";
if($this->endsWith($select, $test)) unset($selects[$i]);
}
}
$this->query->set('select', $selects);
}
/**
* Does the given string end with the test string?
* @return bool
*/
public function endsWith($string, $test) {
$strlen = strlen($string);
$testlen = strlen($test);
if ($testlen > $strlen) return false;
return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
}
/**
* Add columns of given template
* @param string|Template $template
* @param array $hide
* @return void
*/
public function addTemplateColumns($template, $hide = []) {
$tpl = $this->templates->get((string)$template);
foreach($tpl->fields as $field) {
$fieldname = (string)$field;
if(in_array($fieldname, $hide)) continue;
$this->addColumn($fieldname);
}
}
/**
* Add options from field
* @param array|string $fields
* @return void
*/
public function addOptions($fields) {
if(is_array($fields)) {
foreach($fields as $field) $this->addOptions($field);
return;
}
$fieldname = (string)$fields;
$field = $this->fields->get($fieldname);
if(!$field) throw new WireException("Field $fieldname not found");
$data = [];
foreach($field->type->getOptions($field) as $opt) {
$data[$opt->id] = $opt->title;
}
$this->options[$fieldname] = $data;
}
/**
* Add relation to this finder
*
* A relation is an array of objects that is stored with the finder. This
* makes it possible to reference multiple related values from one row (1:n).
*
* Usage of $rows parameter:
* $main = new RockFinder2();
* $main->find(...);
* $main->addColumns(['title', 'foo']);
*
* $rel = new RockFinder2();
* $rel->find('template=foo');
* $rel->addColumns(['title']);
* $main->addRelation('my-foo-data', $rel, 'foo');
*
* This will add only pages to the relation "my-foo-data" that are listed
* in the "foo" column of the $main finder.
*
* @param string name
* @param mixed $data
* @param string $rows
* @return RockFinder2
*/
public function addRelation($name, $data, $rows = null) {
// by default we set the rows restriction to the column name
// if you don't want that set it to FALSE or to a custom name
if($rows === null) $rows = $name;
// check if name already exists
if(array_key_exists($name, $this->_relations)) {
throw new WireException("A relation with name $name already exists");
}
// init relation variable
$relation = $data;
// check data
if(is_array($data)) {
// data is provided as simple array
// we convert it to a RockFinder2 instance
$relation = $this->wire(new RockFinder2);
$relation->setData($data);
}
// modify RockFinder2 instance
if(!$relation instanceof RockFinder2) {
// $relation must be instance of RockFinder2
throw new WireException("Invalid data type for relation $name");
}
// save relation info
$relation->rows = $rows;
// save relation to array
$this->_relations[$name] = $relation;
}
/**
* Load data of all relations
* @param array $maindata
* @param bool $debug
* @return void
*/
public function loadRelationsData($maindata, $debug) {
foreach($this->_relations as $name=>$relation) {
// quickfix to prevent multiple loading of relations
// todo: why is this method executed twice?
if($relation->loaded) return;
/** @var RockFinder2 $relation */
$relation->debug = $this->debug;
// get relation info
$rows = $relation->rows;
// get id restrictions
if(strpos($rows, 'self:') === 0) {
// the keyword SELF means that we limit the relation to a resultset
// where only rows are returned that have an ID of the main finder in
// the column that is specified as self:yourcolumnname
$field = str_replace('self:', '', $rows);
// get ids from main dataset
$ids = $this->getColData('id', $maindata);
if(!count($ids)) {
// if no matching ids where found we return an empty resultset
// for this relation
$relation->query->where("_field_$field.data IS NULL");
}
else {
$ids = implode(",", $ids);
$relation->query->where("_field_$field.data IN ($ids)");
}
}
elseif($rows) {
// if ids restriction is a column of the main finder get ids from its data
$colname = $rows;
$ids = $this->getColData($colname, $maindata);
// if no ids where found we return an empty
if(!count($ids)) {
$relation->loaded = true;
$this->relations[$name] = [];
return;
}
sort($ids); // performance pro or con?
// add ids to query
$ids = implode(",", $ids);
$relation->query->where("pages.id IN ($ids)");
}
// log this request
if($relation->debug) {
$this->log("Relation {$relation->name} SQL: " . $relation->getSQL());
}
// load data
$data = $relation->getData($debug);
$relation->loaded = true;
$this->relations[$name] = $data;
}
}
/**
* Get column data
* @param string $column
* @param array $data
* @return array
*/
public function getColData($column, $data = null) {
if($data === null) $data = $this->getData()->data;
$arr = [];
foreach($data as $item) {
$item = (array)$item;
$items = explode(",", $item[$column]);
foreach($items as $i) $arr[] = $i;
}
$arr = array_unique($arr);
$arr = array_filter($arr);
return $arr;
}
/**
* Add column to finder
* @param mixed $column
* @param mixed $type
* @param mixed $alias
* @return void
*/
private function addColumn($column, $type = null, $alias = null) {
if(!$type) $type = $this->getType($column);
if(!$alias) $alias = $column;
$query = $this->query;
// add this column to columns array
$colname = (string)$column;
if($this->columns->has($colname)) {
// if the column does already exist we append a unique id
// this can happen when requesting title and value of an options field
// https://i.imgur.com/woxCx78.png
$colname .= "_".uniqid();
}
$col = $this->wire(new WireData);
$col->name = $colname;
$col->alias = $alias;
$this->columns->add($col);
// get column type definition
$col = $this->getCol($type);
if(!$col OR !is_callable($col)) {
$col = $this->getCol(); // get default coldef
}
// invoke callable
$col->__invoke((object)[
'query' => $query,
'column' => $column,
'alias' => $alias,
'type' => $type,
]);
}
/**
* Add a RockFinder to join
*
* Basic usage:
*
* $foo = new RockFinder2();
* $foo->find("template=foo");
* $foo->addColumns([..., bar]);
*
* $bar = new RockFinder2();
* $bar->find('template=bar');
* $bar->addColumns([...]);
* $foo->join($bar, 'bar');
*
* Usage of custom joins:
*
* $finder->join(
* 'project-client', // finder name to join
* [
* 'clients', // joined data table alias
* 'id', // column to base join on
* '`join_invoice`.`project`', // column to execute join on
* ],
* ['client', 'client:title'] // columns to add to SELECT
* );
*
* @param string|RockFinder $finder
* @param string $column column to join on or custom join command (AS foo ON foo.id = bar.id)
* @param array $aliases aliases for columns or columns to select on custom joins
*
* @return void;
*/
public function join($finder, $column, $aliases = []) {
// check finder
if(is_string($finder)) $finder = $this->getByName($finder);
if(!$finder instanceof RockFinder2) throw new WireException("First parameter must be a RockFinder2");
// setup columns
$columns = $finder->columns;
// get column from array
$sql = str_replace("\n", "\n ", $finder->getSQL());
if(is_array($column)) {
// custom join
$table = $column[0]; // eg foo
$col = $column[1]; // eg id
$join = $column[2]; // eg bar.id
$this->query->leftjoin("($sql) AS `$table` ON `$table`.`$col` = $join");
foreach($aliases as $colname=>$alias) {
if(is_int($colname)) $colname = $alias;
$this->query->select("`$table`.`$colname` AS `$alias`");
}
}
else {
$col = $this->columns->get($column);
if(!$col) {
// if the column is an array it is a custom join
// otherwise we throw an error that the column does not exist
throw new WireException("Column $column not found");
}
if(!$this->fields->get($col->name)) {
throw new WireException("Field \"{$col->name}\" does not exist so the join can not be performed");
}
$this->query->leftjoin("($sql) AS `join_{$col->name}` ON `join_{$col->name}`.id = _field_{$col->name}.data");
foreach($columns as $c) {
$alias = "{$col->alias}:{$c->alias}";
if(array_key_exists($c->name, $aliases)) $alias = $aliases[$c->name];
$this->query->select("GROUP_CONCAT(DISTINCT `join_$column`.`{$c->alias}`) AS `$alias`");
$this->columns->add($c);
}
}
}
/**
* For backwards compatibility
*/
public function addJoin(...$args) { return $this->join(...$args); }
/**
* Get column type from column name
*
* @param string $column
* @return string
*/
public function ___getType($column) {
if(!$this->wire->RockFinder2) {
throw new WireException("You need to call \$modules->get('RockFinder2') for frontend usage!");
}
// is this column part of the pages table?
$columns = $this->wire->RockFinder2->baseColumns;
if(in_array($column, $columns)) return 'BaseColumn';
// is it a pw field?
$field = $this->fields->get($column);
if($field) {
// file and image fields
if($field->type instanceof FieldtypeFile) return 'FieldMulti';
if($field->type instanceof FieldtypePage) return 'FieldMulti';
if($field->type instanceof FieldtypeOptions) return 'FieldMulti';
// by default we take it as text field
return 'FieldText';
}
else return 'FieldNotFound';
}
/**
* Hookable getCol method for column definitions
* @return Closure
*/
public function ___getCol($type = null) {}
/**
* Get column types via hook
*
* Caution: Make sure tu use getTableAlias() on all your queries! See notes
* of the method for explanation.
*
* @param HookEvent $event;
* @return void;
*/
public function addColumnTypes($event) {
$type = $event->arguments('type');
switch($type) {
// column of the pages table
case 'BaseColumn':
$event->return = function($data) {
$data->query->select("`{$data->column}` AS `{$data->alias}`");
};
return;
// default pw field
case 'FieldText':
$event->return = function($data) {
$table = $this->getTable($data->column);
$tablealias = $this->getTableAlias($data->column);
$data->query->leftjoin("`$table` AS `$tablealias` ON $tablealias.pages_id=pages.id");
$data->query->select("`$tablealias`.data AS `$data->alias`");
};
return;
// pw file/image field
case 'FieldMulti':
$event->return = function($data) {
$table = $this->getTable($data->column);
$tablealias = $this->getTableAlias($data->column);
$data->query->leftjoin("`$table` AS `$tablealias` ON $tablealias.pages_id=pages.id");
$data->query->select("GROUP_CONCAT(DISTINCT `$tablealias`.data ORDER BY `$tablealias`.sort SEPARATOR ',') AS `$data->alias`");
};
return;
// pw options field, get direct selected title of option
// multilang not supported!
case 'FieldOptionsTitle':
$event->return = function($data) {
$table = $this->getTable($data->column);
$tablealias = $this->getTableAlias($data->column);
$data->query->leftjoin("`{$table}` AS `{$tablealias}` ON `{$tablealias}`.`pages_id` = `pages`.`id`");
$data->query->leftjoin("`fields` AS `_fields_{$data->alias}` ON `_fields_{$data->alias}`.`name` = '{$data->column}'");
$data->query->leftjoin("`fieldtype_options` AS `_options_{$data->alias}` ON `_options_{$data->alias}`.`option_id` = `{$tablealias}`.`data` AND `_options_{$data->alias}`.`fields_id` = `_fields_{$data->column}`.`id`");
$data->query->select("GROUP_CONCAT(`_options_{$data->alias}`.`title`) AS `{$data->alias}`");
};
return;
// pw options field, get direct selected value (by DavidKarich)
case 'FieldOptionsValue':
$event->return = function($data) {
$table = $this->getTable($data->column);
$tablealias = $this->getTableAlias($data->column);
$data->query->leftjoin("`{$table}` AS `{$tablealias}` ON `{$tablealias}`.`pages_id` = `pages`.`id`");
$data->query->leftjoin("`fields` AS `_fields_{$data->alias}` ON `_fields_{$data->alias}`.`name` = '{$data->column}'");
$data->query->leftjoin("`fieldtype_options` AS `_options_{$data->alias}` ON `_options_{$data->alias}`.`option_id` = `{$tablealias}`.`data` AND `_options_{$data->alias}`.`fields_id` = `_fields_{$data->alias}`.`id`");
$data->query->select("GROUP_CONCAT(`_options_{$data->alias}`.`value`) AS `{$data->alias}`");
};
return;
// pw field range slider (by DavidKarich)
case 'FieldRange':
$event->return = function($data) {
$table = $this->getTable($data->column);
$tablealias = $this->getTableAlias($data->column);
$data->query->leftjoin("`$table` AS `$tablealias` ON $tablealias.`pages_id` = `pages`.`id`");
$data->query->select("CONCAT(`$tablealias`.`data`, ',', `$tablealias`.`data_max`) AS `$data->alias`");
};
return;
// default pw field
case 'FieldNotFound':
$event->return = function($data) {
$data->query->select("'Field not found' AS `$data->alias`");
};
return;
// default fallback
default:
$event->return = function($data) {
$data->query->select("'No column type found for type {$data->type}' AS `{$data->alias}`");
};
return;
}
}
/**
* Get table name for this column
* @param string $column
* @return string
*/
public function getTable($column) {
return "field_$column";
}
/**
* Get table alias name for this column