lib.php 83.8 KB
Newer Older
1
2
3
4
5
6
<?php
/**
 *
 * @package    mahara
 * @subpackage search-elasticsearch
 * @author     Catalyst IT Ltd
7
8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
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
 *
 */
defined('INTERNAL') || die();
// Required because we use the PluginSearchInternal class for some functions
require_once(get_config('docroot') . 'search/internal/lib.php');

function __autoload_elastica ($class) {

    if (substr($class, 0, 8) == 'Elastica') {
        $file = get_config('libroot') . 'elastica/lib/' . str_replace('\\', '/', $class) . '.php';
        if (file_exists($file)) {
            require_once($file);
        }
    }
    else if (substr($class, 0, 18) == 'ElasticsearchType_') {
        $file = __DIR__ . '/type/' . $class . '.php';
        if (file_exists($file)) {
            require_once($file);
        }
    }
}
spl_autoload_register('__autoload_elastica');

defined('INTERNAL') || die();

/**
 * The internal search plugin which searches against the
 * Mahara database.
 */
class PluginSearchElasticsearch extends PluginSearch {

    /**
     * This function indicates whether the plugin should take the raw $query string
     * when its group_search_user function is called, or whether it should get the
     * parsed query string.
     *
     * @return boolean
     */
    public static function can_process_raw_group_search_user_queries() {
        // We're just going to pass our data on to PluginSearchInternal, and that needs the raw query
        return true;
    }

    /**
     * Returns search results for users in a particular group
     *
     * It's called by and tightly coupled with get_group_user_search_results() in searchlib.php. Look there for
     * the exact meaning of its parameters and expected return values.
     *
     * Since I haven't had the time to figure them out, we'll just use PluginSearchInternal's version.
     */
60
61
    public static function group_search_user($group, $queries, $constraints, $offset, $limit, $membershiptype, $order, $friendof, $sortoptionidx=null) {
        return PluginSearchInternal::group_search_user($group, $queries, $constraints, $offset, $limit, $membershiptype, $order, $friendof, $sortoptionidx);
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    }

    /**
     * Returns search results for users in a particular institution
     *
     * We are going to pass this on to PluginSearchInternal to handle returning the correct results
     * in the correct format.
     */
    public static function institutional_admin_search_user($query, $institution, $limit) {
        return PluginSearchInternal::institutional_admin_search_user($query, $institution, $limit);
    }

    /**
     * This function determines whether the plugin is currently available to be chosen
     * as the sitewide search plugin (i.e. get_config('searchplugin'))
     */
    public static function is_available_for_site_setting() {
79
        return true;
80
81
    }

82
83
84
85
86
87
88
89
90
91
92
93
94
95
    /**
     * This function determines if we can connect to the supplied host and port
     */
    public static function can_connect() {
        $host = get_config_plugin('search', 'elasticsearch', 'host');
        $port = get_config_plugin('search', 'elasticsearch', 'port');
        $fp = @fsockopen($host, $port, $errno, $errstr, 5);
        if ($fp) {
            fclose($fp);
            return true;
        }
        return false;
    }

96
97
98
99
100
101
102
103
104
    /**
     * This function determines whether the plugin allows a search box to display for
     * non-logged in users - only useful if results returned by search are allowed to
     * be seen by the public
     */
    public static function publicform_allowed() {
        return true;
    }

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    /**
     * Generates the search form used in the page headers
     * @return string
     */
    public static function header_search_form() {
        require_once('pieforms/pieform.php');

        return pieform(array(
                'name'                => 'usf',
                'action'              => get_config('wwwroot') . 'search/elasticsearch/index.php',
                'renderer'            => 'oneline',
                'autofocus'           => false,
                'validate'            => false,
                'presubmitcallback'   => '',
                'elements'            => array(
                        'query' => array(
                                'type'           => 'text',
                                'defaultvalue'   => get_string('pagetitle', 'search.elasticsearch'),
123
                                'title'          => get_string('pagetitle', 'search.elasticsearch'),
124
                                'class'          => 'emptyonfocus',
125
                                'hiddenlabel'    => true,
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
                        ),
                        'submit' => array(
                                'type' => 'submit',
                                'value' => get_string('go'),
                        )
                )
        ));
    }

    public static function can_be_disabled() {
        return true;
    }

    public static function has_config() {
        return true;
    }

    public static function get_config_options() {

        if (get_config('searchplugin') == 'elasticsearch') {
            $smarty = smarty_core();
            $smarty->assign('notice', get_string('noticeenabled', 'search.elasticsearch', get_config('wwwroot').'admin/site/options.php?fs=searchsettings'));
            $enabledhtml = $smarty->fetch('Search:elasticsearch:confignotice.tpl');
            unset($smarty);
        }
        else {
            $smarty = smarty_core();
            $smarty->assign('notice', get_string('noticenotenabled', 'search.elasticsearch', get_config('wwwroot').'admin/site/options.php?fs=searchsettings'));
            $enabledhtml = $smarty->fetch('Search:elasticsearch:configwarning.tpl');
            unset($smarty);
        }
157
158
159
160
161
162
        if (!self::can_connect()) {
            $smarty = smarty_core();
            $smarty->assign('notice', get_string('noticenotactive', 'search.elasticsearch', get_config_plugin('search', 'elasticsearch', 'host'), get_config_plugin('search', 'elasticsearch', 'port')));
            $enabledhtml .= $smarty->fetch('Search:elasticsearch:configwarning.tpl');
            unset($smarty);
        }
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

        $config = array(
            'elements' => array(
                'enablednotice' => array(
                    'type'         => 'html',
                    'value'        => $enabledhtml,
                ),
                'host' => array(
                    'title'        => get_string('host', 'search.elasticsearch'),
                    'description'  => get_string('hostdescription', 'search.elasticsearch'),
                    'type'         => 'html',
                    'value'        => get_config_plugin('search', 'elasticsearch', 'host'),
                    'help'         => true,
                ),
                'port' => array(
                    'title'        => get_string('port', 'search.elasticsearch'),
                    'description'  => get_string('portdescription', 'search.elasticsearch'),
                    'type'         => 'html',
                    'value'        => get_config_plugin('search', 'elasticsearch', 'port'),
                    'help'         => true,
                ),
                'username' => array(
                    'title'        => get_string('username', 'search.elasticsearch'),
                    'description'  => get_string('usernamedescription', 'search.elasticsearch'),
                    'type'         => 'html',
                    'value'        => (
                            get_config_plugin('search', 'elasticsearch', 'username')
                            ? get_config_plugin('search', 'elasticsearch', 'username')
                            : get_string('confignotset', 'search.elasticsearch')
                    ),
                    'help'         => true,
                ),
                'password' => array(
                    'title'        => get_string('password', 'search.elasticsearch'),
                    'description'  => get_string('passworddescription', 'search.elasticsearch'),
                    'type'         => 'html',
                    'value'        => (
                            get_config_plugin('search', 'elasticsearch', 'password')
                            ? get_string('passwordlength', 'search.elasticsearch', strlen(get_config_plugin('search', 'elasticsearch', 'password')))
                            : get_string('confignotset', 'search.elasticsearch')
                    ),
                    'help'         => true,
                ),
                'indexname' => array(
                    'title'        => get_string('indexname', 'search.elasticsearch'),
                    'description'  => get_string('indexnamedescription', 'search.elasticsearch'),
                    'type'         => 'html',
                    'value'        => get_config_plugin('search', 'elasticsearch', 'indexname'),
                    'help'         => true,
                ),
                'bypassindexname' => array(
                    'title'        => get_string('bypassindexname', 'search.elasticsearch'),
                    'description'  => get_string('bypassindexnamedescription', 'search.elasticsearch'),
                    'type'         => 'html',
                    'help'         => true,
                    'value'        => (
                            get_config_plugin('search', 'elasticsearch', 'bypassindexname')
                            ? get_config_plugin('search', 'elasticsearch', 'bypassindexname')
                            : get_string('confignotset', 'search.elasticsearch')
                    ),
                ),
                'analyzer' => array(
                    'title'        => get_string('analyzer', 'search.elasticsearch'),
                    'description'  => get_string('analyzerdescription', 'search.elasticsearch'),
                    'type'         => 'html',
                    'value'        => get_config_plugin('search', 'elasticsearch', 'analyzer'),
                    'help'         => true,
                ),
                'types' =>  array(
                    'title'        => get_string('types', 'search.elasticsearch'),
                    'description'  => get_string('typesdescription', 'search.elasticsearch'),
                    'type'         => 'html',
                    'size'         => '80',
                    'value' => get_config_plugin('search', 'elasticsearch', 'types'),
                    'help'         => true,
                ),
                'cronlimit' => array(
                    'title'        => get_string('cronlimit', 'search.elasticsearch'),
                    'description'  => get_string('cronlimitdescription', 'search.elasticsearch'),
                    'type'         => 'text',
                    'defaultvalue' => get_config_plugin('search', 'elasticsearch', 'cronlimit'),
                ),
            ),
        );

        $types = explode(',', get_config_plugin('search', 'elasticsearch', 'types'));


        // if artefact => show list of artefacttype
        if (in_array('artefact', $types)) {

            $rs = get_recordset_sql('SELECT DISTINCT name AS artefacttype FROM {artefact_installed_type} ORDER BY name ASC');
            $artefacttypes = explode(',', get_config_plugin('search', 'elasticsearch', 'artefacttypes'));
            // the following artefacttypes are excluded because the info is already in the usr table
            $artefacttypes_toexclude = array('firstname', 'lastname', 'preferredname', 'email');
            // to be valid, artefact types need a hierarchy
            $artefacttypesmap_array = self::elasticsearchartefacttypesmap_to_array();

            $types_checkbox = array();
            foreach (recordset_to_array($rs) as $record) {
                $types_checkbox[] = array(
                                        'title'        => $record->artefacttype,
                                        'value'        => $record->artefacttype,
                                        'defaultvalue' => in_array($record->artefacttype, $artefacttypes) ? true : false,
                                        'disabled'     => in_array($record->artefacttype, $artefacttypes_toexclude) OR
                                                            !in_array($record->artefacttype, array_keys($artefacttypesmap_array)) ? true : false,
                                    );
            }

            $config['elements']['artefacttypes'] = array(
                'type'         => 'checkboxes',
                'title'        => get_string('artefacttypelegend', 'search.elasticsearch'),
                'description'  => get_string('artefacttypedescription', 'search.elasticsearch'),
                'elements'     => $types_checkbox,
            );

            $config['elements']['artefacttypesmap'] = array(
                'type'         => 'textarea',
                'rows'         => 10,
                'cols'         => 100,
                'title'        => get_string('artefacttypemaplegend', 'search.elasticsearch'),
                'description'  => get_string('artefacttypemapdescription', 'search.elasticsearch'),
                'defaultvalue' => implode("\n", $artefacttypesmap_array),
            );

        }


        if (count($types) > 0) {
            $item_by_type_in_queue = array();
293
            $rs = get_records_sql_array('SELECT type, count(*) AS total FROM {search_elasticsearch_queue} GROUP BY type', array());
294
295
            if ($rs) {
                foreach ($rs as $record) {
296
                    $item_by_type_in_queue[$record->type] = $record->total;
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
                }
            }

            // Create the buttons that let an admin reset individual sub-indexes.
            $resetelements = array();
            // TODO: Make single-searchtype reset work properly. For now we'll just comment it out, leaving only
            // "reset all" available.
            $resetelements['resetdescription'] = array(
                'type' => 'html',
                'value' => get_string('resetdescription','search.elasticsearch')
            );
            foreach ($types as $type) {
                $key = $type;
                $keyreset = $type . 'reset';
                $count_in_queue = isset($item_by_type_in_queue[$type]) ? ' (' . $item_by_type_in_queue[$type] . ')' : '(0)';
                $resetelements[$keyreset] =  array(
                    'title' => $type,
                    'type' => 'html',
                    'value' => $count_in_queue,
//                    'title'        =>   $type . $count_in_queue,
//                    'type'         => 'submit',
318
//                    'defaultvalue' => get_string('reset', 'search.elasticsearch'),
319
320
321
322
323
324
                );
            }
            // And on the end, a special one to reset all the indexes.
            $resetelements['allreset'] = array(
                'title' => get_string('resetallindexes', 'search.elasticsearch'),
                'type' => 'submit',
325
                'defaultvalue' => get_string('reset', 'search.elasticsearch'),
326
327
328
329
330
331
332
333
334
335
336
337
338
            );

            $config['elements']['resetindex'] = array(
                'type' => 'fieldset',
                'legend' => get_string('resetlegend', 'search.elasticsearch'),
                'elements' => $resetelements,
                'collapsible' => true
            );
        }

        return $config;
    }

339
340
341
342
343
344
345
    public function validate_config_options($form, $values) {
        // First check that there isn't an elasticsearch cron indexing the site
        if (get_record('config', 'field', '_cron_lock_search_elasticsearch_cron')) {
            $form->set_error(null, get_string('indexingrunning', 'search.elasticsearch'));
        }
    }

346
347
348
349
350
351
352
353
354
355
    public function save_config_options($values) {
        set_config_plugin('search', 'elasticsearch', 'cronlimit', $values['cronlimit']);

        // Changes in artefact types:
        //       - we need to add the newly selected artefact types (for indexing)
        //       - we need to removed artefact types that have been unchecked (to remove them from the index)
        // I wanted to use the "delete by query" feature of Elastic search (http://www.elasticsearch.org/guide/reference/api/delete-by-query/)
        // but it was not very reliable. According to the docs:  it is not recommended to delete "large chunks of the data in an index".
        // So I decided to remove data by Id.

356
        set_config_plugin('search', 'elasticsearch', 'artefacttypesmap', $values['artefacttypesmap']);
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
        // to be valid, artefact types need a hierarchy
        $artefacttypesmap_array = self::elasticsearchartefacttypesmap_to_array();
        $values['artefacttypes'] = array_intersect($values['artefacttypes'], array_keys($artefacttypesmap_array));

        $types = explode(',', $values['types']);
        if (in_array('artefact', $types)) {
            $artefacttypes_old = explode(',', get_config_plugin('search', 'elasticsearch', 'artefacttypes'));
            $result = array_diff($artefacttypes_old, $values['artefacttypes']) + array_diff($values['artefacttypes'], $artefacttypes_old);
            // result now contains the artefacttypes that have been checked and unchecked
            foreach ($result as $artefacttype) {
                ElasticsearchIndexing::requeue_searchtype_contents('artefact', $artefacttype);
            }
            set_config_plugin('search', 'elasticsearch', 'artefacttypes', implode(',', $values['artefacttypes']));
        }

        // If they chose to reset all the indexes, do that.
        if (isset($values['allreset'])) {
374
375
376
377
            // set the cron lock before beginning re index to stop the cron indexing at same time
            $start = time();
            insert_record('config', (object) array('field' => '_cron_lock_search_elasticsearch_cron', 'value' => $start));

378
379
380
            self::reset_all_searchtypes();
            // Send the first batch of records to the elasticsearch server now, for instant gratification
            self::index_queued_items();
381
382
383

            // free the cron lock
            delete_records('config', 'field', '_cron_lock_search_elasticsearch_cron', 'value', $start);
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
        }
        // TODO: Make single-searchtype reset work properly. For now we'll just comment this out in hopes
        // it will aid a future developer.
//         else {
//             // If they clicked any "reset index" button, then reset only that index.
//             // We'll  loop through the index types, in order to check for the form detail for each one
//             $types = explode(',', $values['types']);
//             foreach ($types as $type) {
//                 // Check whether they chose to reset the index on this type
//                 $type = trim($type);
//                 $keyreset = $type . 'reset';
//                 if (isset($values[$keyreset]) AND $values[$keyreset] == 'reset') {
//                     // Queues every matching record for this index type
//                     ElasticsearchIndexing::requeue_searchtype_contents($type);
//                 }
//                 // Reset the mappings for (only) this type
//                 self::set_mapping($type);
//                 ElasticsearchIndexing::create_triggers($type);
//             }
//         }

        return true;
    }

    /**
     * This function gets called when the sitewide search plugin is switched to
     * this one. It's the chance for the plugin to do any post-configuration
     * initialization it might need. (The same stuff you'd probably do after
     * changing the plugin's configuration via its extension config page.)
     *
     */
    public static function initialize_sitewide() {
416
417
418
419
420
        if (self::can_connect()) {
            self::reset_all_searchtypes();
            return true;
        }
        return false;
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
    }

    /**
     * This function gets called when the sitewide search plugin is switched
     * away from this one.
     *
     * We'll use this opportunity to disable the triggers and clear out the queue
     * table. Otherwise, it will forever swell since we're no longer running
     * the cron.
     */
    public static function cleanup_sitewide() {
        $enabledtypes = explode(',', get_config_plugin('search', 'elasticsearch', 'types'));
        // (re)create the mappings and the overall site index
        foreach ($enabledtypes as $type) {
            ElasticsearchIndexing::drop_triggers($type);
        }
        ElasticSearchIndexing::drop_trigger_functions();
        delete_records('search_elasticsearch_queue');
    }

    /**
     * Resets all the searchtypes in the following ways:
     *  - Deletes and re-creates the elasticsearch index on the server
     *  - Re-creates the trigger functions
     *    - This will also drop the triggers for all types (even those that aren't in use)
     *  - Creates all triggers for those types that are in use
     *  - Tells the elasticsearch server to drop and re-create the index
     *  - Tells the elasticsearch server to re-create the "mapping" for each type
     *  - Loads every record for that type into the queue table, for the cron to chug away at them
     */
    public static function reset_all_searchtypes() {
        ElasticSearchIndexing::create_index();
        ElasticsearchIndexing::create_trigger_functions();
        $enabledtypes = explode(',', get_config_plugin('search', 'elasticsearch', 'types'));
        // (re)create the mappings and the overall site index
        foreach ($enabledtypes as $type) {
            ElasticsearchIndexing::create_triggers($type);
            ElasticsearchIndexing::requeue_searchtype_contents($type);
            self::set_mapping($type);
        }
    }

    public static function postinst($prevversion) {
        if ($prevversion == 0) {
            set_config_plugin('search', 'elasticsearch', 'host', '127.0.0.1');
            set_config_plugin('search', 'elasticsearch', 'port', '9200');
            set_config_plugin('search', 'elasticsearch', 'indexname', 'mahara');
            set_config_plugin('search', 'elasticsearch', 'analyzer', 'mahara_analyzer');
            set_config_plugin('search', 'elasticsearch', 'types', 'usr,interaction_instance,interaction_forum_post,group,view,artefact');

            $elasticsearchartefacttypesmap = file_get_contents(__DIR__ . '/elasticsearchartefacttypesmap.txt');
            set_config_plugin('search', 'elasticsearch', 'artefacttypesmap', $elasticsearchartefacttypesmap);
        }
    }

    public static function elasticsearchartefacttypesmap_to_array() {
        $artefacttypesmap_array = explode("\n", get_config_plugin('search', 'elasticsearch', 'artefacttypesmap'));
        $tmp = array();
        foreach ($artefacttypesmap_array as $key => $value) {
            $tmpkey = explode("|", $value);
            if (count($tmpkey) == 3) {
                $tmp[$tmpkey[0]] = $value;
            }
        }
        ksort($tmp, SORT_STRING);
        return $tmp;
    }


    public static function get_cron() {
        return array(
            (object)array(
                'callfunction' => 'cron',
                'hour'         => '*',
                'minute'       => '*/5',
            ),
        );
    }

    public static function cron() {

        // Only run the cron if this plugin is the active search plugin
        if (get_config('searchplugin') !== 'elasticsearch') {
            return;
        }

        // store the last time the function was executed: eg: 2013-04-11 16:45:30
        $timestamp = date('Y-m-d H:i:s');
        $last_run = get_config_plugin('search', 'elasticsearch', 'lastrun');
        if (isset($last_run)) {
            ElasticsearchIndexing::add_to_queue_access($last_run, $timestamp);
        }

        set_config_plugin('search', 'elasticsearch', 'lastrun', $timestamp);
        // process the queue
        self::index_queued_items();

    }

    /**
     * Creates the "mapping" for this searchtype, on the elasticsearch server
     *
     * TODO: it would be good to be able to make elasticsearch just delete the contents of one
     * searchtype, perhaps identified by its mapping? But I haven't been able to figure out how
     * to do that, so instead you can only delete the whole index at once.
     * @param string $type
     */
    private static function set_mapping($type) {
        // usr,interaction_instance,interaction_forum_post,view,group,artefact
        $ES_class = 'ElasticsearchType_' . $type;
        if ($ES_class::$mappingconf === false) {
            return false;
        }

        $elasticaClient = self::make_client();
        $elasticaIndex = $elasticaClient->getIndex(self::get_write_indexname());
        $elasticaAnalyzer = get_config_plugin('search', 'elasticsearch', 'analyzer');
        if (!isset($elasticaAnalyzer)) {
            $elasticaAnalyzer = 'mahara_analyzer';
        }

        // Load type
        $elasticaType = $elasticaIndex->getType($type);

        // Define mapping
        $mapping = new \Elastica\Type\Mapping();
        $mapping->setType($elasticaType);
        // we use mahara_analyzer created through elastica
        $mapping->setParam('index_analyzer', $elasticaAnalyzer);
        $mapping->setParam('search_analyzer', $elasticaAnalyzer);

        // Define boost field
        //$mapping->setParam('_boost', array('name' => '_boost', 'null_value' => 1.0));

        // Set mapping
        $mapping->setProperties($ES_class::$mappingconf);

        // Send mapping to type
        $mapping->send();
    }


    /**
     * Sends records from the queue table into the elasticsearch server
     */
    public static function index_queued_items() {

        $limitnum = intval(get_config_plugin('search', 'elasticsearch', 'cronlimit'));
        if ($limitnum <= 0) {
            $limitfrom = $limitnum = '';
        }
        else {
            $limitfrom = 0;
        }
        $records = get_records_array('search_elasticsearch_queue', '', 'id', '', '*', $limitfrom, $limitnum);

        if (!$records) {
            return;
        }

        $elasticaClient = self::make_client();
        $indexname = self::get_write_indexname();
        $elasticaIndex = $elasticaClient->getIndex($indexname);

        $artefacttypesmap_array = self::elasticsearchartefacttypesmap_to_array();

        foreach ($records as $record) {
            $deleteitem = false;
            $tmp = null;
            $ES_class = 'ElasticsearchType_' . $record->type;
            if ($record->type == 'artefact') {
                $tmp['db'] = $ES_class::getRecordById($record->type, $record->itemid, $artefacttypesmap_array);
            }
            else {
                $tmp['db'] = $ES_class::getRecordById($record->type, $record->itemid);
            }

            // If the record has been physically deleted from the DB or if its artefacttype is not selected
            if ($tmp['db'] == false) {
                $deleteitem = true;
            }
            else {
                $item = new $ES_class($tmp['db']);
                $deleteitem = $item->getisDeleted();
            }

            // Remove item from index
            if ($deleteitem == true) {
                $tmp = $elasticaClient->deleteIds(array($record->itemid), $indexname, $record->type);
            }
            // Index item
            else {
                $elasticaType = $elasticaIndex->getType($record->type);
                $doc = new \Elastica\Document($record->itemid, $item->getMapping());
                $elasticaType->addDocument($doc);
            }
            delete_records('search_elasticsearch_queue', 'id', $record->id);
        }
        // Refresh Index
        $elasticaIndex->refresh();

    }

    public static function search_all ($query_string, $limit, $offset = 0, $options=array(), $mainfacetterm = null, $subfacet = null) {
        global $USER;
        return ElasticsearchPseudotype_all::search($query_string, $limit, $offset, $options, $mainfacetterm, $USER);
    }

    public static function search_user($query_string, $limit, $offset = 0, $data=array()) {
        return PluginSearchInternal::search_user($query_string, $limit, $offset, $data);
    }

    public static function search_group($query_string, $limit, $offset=0, $type='member', $category='') {
        // Given the results depends on the user the SQL search makes more sense here than Elastic Search
        // So  I'll just call the PluginSearchInternal related function
        return PluginSearchInternal::search_group($query_string, $limit, $offset, $type, $category);
    }

    public static function self_search($query_string, $limit, $offset, $type = 'all') {
        // call the PluginSearchInternal related function
        return PluginSearchInternal::self_search($query_string, $limit, $offset, $type);
    }

    public static function admin_search_user($query_string, $constraints, $offset, $limit,
                                             $sortfield, $sortdir) {

        // We need to fudge some stuff before sending it on, because get_admin_user_search_results()
        // in lib/searchlib.php has some hard-coded special functionality for the internal search plugin
        if (is_array($query_string) && count($query_string)>0) {
            $query_string = $query_string[0]['string'];
        }
        else {
            $query_string = "";
        }

        return PluginSearchInternal::admin_search_user($query_string, $constraints, $offset, $limit,
                                             $sortfield, $sortdir);

   }

   /**
    * Creates an \Elastica\Client object, filling in the host and
    * port with the values from the elasticsearch plugin's admin screen.
    * If you wanted to make other changes to how we connect to elasticsearch,
    * this would be a good place to do it.
    *
    * @return \Elastica\Client
    */
   public static function make_client() {
       $config = array();
       $config['host'] = get_config_plugin('search', 'elasticsearch', 'host');
       $config['port'] = get_config_plugin('search', 'elasticsearch', 'port');
       if ($username = get_config_plugin('search', 'elasticsearch', 'username')) {
           $password = get_config_plugin('search', 'elasticsearch', 'password');
           // Thank you Wikipedia: http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side
           $authheader = 'Basic ' . base64_encode("{$username}:{$password}");
           $config['headers'] = array('Authorization'=>$authheader);
       }
       return new \Elastica\Client($config);
   }


   /**
    * Return the name of the index to use for writing. Basically, this is bypassindexname
    * if that is supplied, and indexname if not.
    *
    * @return string
    */
   public static function get_write_indexname() {
       // If they provided bypassindexname, then use that, otherwise use indexname.
       // The purpose of bypassindexname is to allow a site to reindex data into a new
       // index, while still using the old index for searching.
       $indexname = get_config_plugin('search', 'elasticsearch', 'bypassindexname');
       if (!$indexname) {
           $indexname = get_config_plugin('search', 'elasticsearch', 'indexname');
       }
       return $indexname;
   }

   /**
    * Builds the "results" table seen on the universal search results page
    * @param unknown_type $data
    */
   public static function build_results_html(&$data) {

       $smarty = smarty_core();
       $smarty->assign('data', isset($data['data']) ? $data['data'] : null);

       $params = array();
       if (isset($data['query'])) {
           $params['query'] = $data['query'];
       }
       if (isset($data['selected'])) {
           $params['mainfacetterm'] = $data['selected'];
       }
       if (isset($data['content-filter-selected'])) {
           $params['secfacetterm'] = $data['content-filter-selected'];
       }
       if (isset($data['owner-filter-selected'])) {
           $params['owner'] = $data['owner-filter-selected'];
       }
       if (isset($data['tagsonly'])) {
           $params['tagsonly'] = $data['tagsonly'];
       }
       if (isset($data['sort'])) {
           $params['sort'] = $data['sort'];
       }
       if (isset($data['license'])) {
           $params['license'] = $data['license'];
       }
       if (!isset($data['count'])) {
           $data['count'] = 0;
       }
       if (!isset($data['limit'])) {
           $data['limit'] = 0;
       }
       if (!isset($data['offset'])) {
           $data['offset'] = 0;
       }
       $smarty->assign('offset', $data['offset']);

       $resultcounttextsingular = get_string('record', 'search.elasticsearch');
       $resultcounttextplural = get_string('records', 'search.elasticsearch');

       if (isset($data['facets'])) {
           $smarty->assign('facets', $data['facets']);
       }
       if (isset($data['content-filter'])) {
           $smarty->assign('contentfilter', $data['content-filter']);
       }
       if (isset($data['content-filter-selected'])) {
           $smarty->assign('contentfilterselected', $data['content-filter-selected']);
       }
       if (isset($data['owner-filter'])) {
           $smarty->assign('ownerfilter', $data['owner-filter']);
       }
       if (isset($data['owner-filter-selected'])) {
           $smarty->assign('owner', $data['owner-filter-selected']);
       }
       if (isset($data['tagsonly'])) {
           $smarty->assign('tagsonly', $data['tagsonly']);
       }
       if (isset($data['selected'])) {
           $smarty->assign('selected', $data['selected']);
       }
       if (isset($data['sort'])) {
           $smarty->assign('sort', $data['sort']);
       }
       if (isset($data['limit'])) {
           $smarty->assign('limit', $data['limit']);
       }
       if (isset($data['offset'])) {
           $smarty->assign('offset', $data['offset']);
       }
       if (isset($data['license'])) {
           $smarty->assign('license', $data['license']);
       }
       if (isset($data['totalresults'])) {
           $smarty->assign('totalresults', $data['totalresults']);
       }

       // Only show licence if Text or Media tab is selected and license metadata site config is set
       if (isset($data['license_on']) && isset($data['license_options']) && isset($data['selected']) && ($data['selected'] == 'Media' || $data['selected'] == 'Text')) {
           $smarty->assign('license_on', $data['license_on']);
           $smarty->assign('license_options', $data['license_options']);
       }


       if (isset($data['type'])) {
           $smarty->assign('type', $data['type']);
       }
       $smarty->assign('query', $params['query']);

       $data['tablerows'] = $smarty->fetch('Search:elasticsearch:searchresults.tpl');

       $pagination = build_pagination(array(
               'id' => 'elasticsearch_pagination',
               'url' => get_config('wwwroot') . 'search/elasticsearch/index.php?' . http_build_query($params),
               'jsonscript' => 'search/elasticsearch/json/elasticsearch.php',
               'datatable' => 'universalsearchresult',
               'count' => $data['count'],
               'setlimit' => $data['limit'],
               'limit' => $data['limit'],
               'offset' => $data['offset'],
               'jumplinks' => 6,
               'numbersincludeprevnext' => 2,
               'resultcounttextsingular' => $resultcounttextsingular,
               'resultcounttextplural' => $resultcounttextplural,
               'extradata' => array('page' => 'index'),
       ));
       $data['pagination'] = $pagination['html'];
       $data['pagination_js'] = $pagination['javascript'];
   }

    /**
     * Fix the $query string for things that can break elasticsearch.
     * @param string $query
     *
     * @return string
     */
    public function clean_query($query) {
        $query = stripslashes($query); // to remove any backslashes
        $badchars = array(
            '"',
            '[',
            ']',
            '{',
            '}',
            '~',
            '^',
            '(',
            ')',
            '-',
            '+',
            '/',
            '!',
            ':'
        );
        foreach ($badchars as $bad) {
840
841
            // Replace with a space.
            $query = preg_replace('/\\'.$bad.'/',' ',$query);
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
        }
        return $query;
    }
}

/**
 *    This class encapsulates the ACL filters
 */
class ElasticsearchFilterAcl extends \Elastica\Filter\BoolOr
{

    private $user;

    public function __construct($user) {

        $this->user = $user;

        //    No ACL          (artefacts that don't implement ACL)
        $elasticaFilterNoACL = new \Elastica\Filter\Missing('access.general');
        $this->addFilter($elasticaFilterNoACL);

        //    GENERAL         (public - loggedin - friends)
        //        public
        $elasticaFilterGeneral = new \Elastica\Filter\Term(array('access.general' => 'public'));
        $this->addFilter($elasticaFilterGeneral);

        //        loggedin
        if ($this->user->is_logged_in()) {
            $elasticaFilterGeneral = new \Elastica\Filter\Term(array('access.general' => 'loggedin'));
            $this->addFilter($elasticaFilterGeneral);

            //        friends: pass a list of friends => check if access.general = friends and the owner is a friend of the current user
            if ($friends = $this->getFriendsList()) {
                $elasticaFilterAnd  = new \Elastica\Filter\BoolAnd();
                $elasticaFilterGeneral = new \Elastica\Filter\Term(array('access.general' => 'friends'));
                $elasticaFilterAnd->addFilter($elasticaFilterGeneral);
                $elasticaFilterGeneral = new \Elastica\Filter\Terms('owner', $friends);
                $elasticaFilterAnd->addFilter($elasticaFilterGeneral);
                $this->addFilter($elasticaFilterAnd);
            }

        }

        //    INSTITUTIONS     (array of institutions that have access to the artefact)
        $user_institutions = array_keys($this->user->get('institutions'));
        if ($user_institutions && count($user_institutions) > 0) {
            $elasticaFilterInstitutions = new \Elastica\Filter\Terms('access.institutions', $user_institutions);
            $this->addFilter($elasticaFilterInstitutions);
        }

        //     GROUPS             (array of groups that have access to the artefact) groups [all/admin/member]
        if ($groups = $this->getGroupsList()) {
            $roles = $this->getExistingRoles();
            foreach($roles AS $role){
                if (isset($groups[$role]) && count($groups[$role])) {
                    $elasticaFilterGroup[$role] = new \Elastica\Filter\Terms('access.groups.'.$role, $groups[$role]);
                    $this->addFilter($elasticaFilterGroup[$role]);
                }
            }
        }
        //     USRS             (array of user ids that have access to the artefact)
        if ($this->user->is_logged_in()) {
            // if owner
            $elasticaFilterOwner = new \Elastica\Filter\Term(array('owner' => $this->user->get('id')));
            $this->addFilter($elasticaFilterOwner);
            // in access.usrs list
            $elasticaFilterUsr = new \Elastica\Filter\Term(array('access.usrs' => $this->user->get('id')));
            $this->addFilter($elasticaFilterUsr);
        }



    }

    private function getFriendsList(){
        $list = array();
        $friends = get_friends($this->user->get('id'), 0, 0);
        if ($friends && array_key_exists('data', $friends) && is_array($friends['data'])) {
            foreach ($friends['data'] as $friend) {
                $list[] = $friend->id;
            }
        }
        return $list;
    }

    private function getGroupsList(){
        $list = array();
        $groups = group_get_user_groups($this->user->get('id'));
        foreach ($groups as $group) {
            $list[$group->role][] = $group->id;
            $list['member'][] = $group->id;
        }
        return $list;
    }

    private function getExistingRoles(){
        $rs = get_recordset_sql('SELECT DISTINCT role FROM {grouptype_roles}');
        $roles = array('all');
        foreach (recordset_to_array($rs) as $record) {
            $roles[] = $record->role;
        }
        return $roles;
    }
}


/**
 * Represents one of the "types" that elasticsearch can search against. These are "types"
 * in the elasticsearch sense: http://www.elasticsearch.org/guide/reference/api/search/indices-types/
 *
 * The currently active types are stored in the "search->elasticsearch->types" config variable.
 *
 * This isn't quite a fully fleshed-out Mahara plugin type, although it is an expandable area.
 * One noteable limitation is that under the current implementation, the type name must match
 * up exactly with a Mahara table. Though since all the operations are read-only, you could
 * work around that with a view.
 */
abstract class ElasticsearchType
{
    /**
     * @var string The name of this search type. Should match the name of the class, and the name of a DB table
     */
    public static $type = null;

    protected $item_to_index;
    protected $mapping;
968
969
970

    private static $mysqltriggeroperations = array('insert', 'update', 'delete');

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
    /**
     *   $conditions was originally used to filter only active, non deleted records to insert into the queue,
     *   but as we will now use it to determine if the record has to be indexed or removed from the index.
     */
    protected $conditions;
    protected $isDeleted;
    public static $mappingconf = false;
    public static $mainfacetterm = false;   // The main facet will not be based on the index type but on a custom grouping
    public static $subfacetterm = false;

    public function __construct($data){

        $this->item_to_index = $data;
        $this->setMapping();
        $this->isDeleted = false;
        $this->setisDeleted();

    }

    public function setMapping(){
        foreach ($this->mapping as $key => $value) {
            $this->mapping[$key] = $this->item_to_index->$key;
        }
    }

    public function getMapping(){
        return $this->mapping;
    }

    /**
     *   set if the record has to be indexed or removed from the index
     */
    public function setisDeleted(){

        if (count($this->conditions) > 0) {
            foreach ($this->conditions as $key => $value) {
                if ($this->item_to_index->$key != $value) {
                    $this->isDeleted = true;
                }
            }
        }
    }

    /**
     *   check if the record has to be indexed or removed from the index
     */
    public function getisDeleted(){
        return $this->isDeleted;
    }

    /**
     *   get the info from the DB for indexing
     */
    public static function getRecordById($type, $id){
        $record = get_record($type, 'id', $id);
        if ($record) {
            $record->ctime = self::checkctime($record->ctime);
            $record->mainfacetterm = static::$mainfacetterm;
        }
        return $record;
    }

    /**
     *   get the info from the DB for display
     */
    public static function getRecordDataById($type, $id){
        return get_record($type, 'id', $id);
    }

    /**
     * Build the access object
     */
    public static function access_process($records) {

        // For general: 3 levels public > loggedin > friends (this is accesstype in view_access). Objectionable is excluded for now
        // general will be set to the less restrictive of the 3 options
        $levels = array('friends', 'loggedin', 'public');
        $types = array('usr', 'group', 'institution');
        $access = array('general' => 'none'); // access is by default denied to everyone

        if (!$records) {
            return $access;
        }

        foreach ($records as $record) {
            if (isset($record->accesstype) and in_array($record->accesstype, $levels)) {
                if (array_search($record->accesstype, $levels) >= array_search($access['general'], $levels)) {
                    $access['general'] =  $record->accesstype;
                }
            }
            // If accesstype is null, only 1 of the 3 properties institution, group, usr is set
            else if (!isset($record->accesstype)) {
                foreach ($types as $type) {
                    if (isset($record->$type)) {
                        // If type is group, role can be null (all), admin, or member
                        if ($type == 'group') {
                            $role = isset($record->role) ? $record->role : 'all';
                            $access[$type . 's'][$role][] = $record->$type;
1069
1070
1071
1072
1073
                            if ($role == 'all') {
                                // add member and admin roles. 'all' does not seem to find them.
                                $access[$type . 's']['member'][] = $record->$type;
                                $access[$type . 's']['admin'][] = $record->$type;
                            }
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
                        }
                        else
                            $access[$type . 's'][] = $record->$type;
                    }
                }
            }
        }

        if ($access['general'] == 'loggedin' OR  $access['general'] == 'public') {
            $access = array('general' => $access['general']);
        }

        return $access;
    }

    /**
     * check that the date format is Y-m-d H:i:s - some dates have the following format 2011-07-29 16:13:56.017725
     */
    public static function checkctime($ctime){
        if (!preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) ([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/', $ctime)) {
            $ctime = date('Y-m-d H:i:s', strtotime($ctime));
        }
        return $ctime;
    }

    /**
     * Executes the SQL to create any triggers needed by this search type
     */
    public static function create_triggers() {
        $type = $this::$type;
1104
1105
1106
        if (is_postgres()) {
            $sql = "DROP FUNCTION IF EXISTS {search_elasticsearch_{$type}}() CASCADE;";
            execute_sql($sql);
1107

1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
            $sql = "CREATE TRIGGER {search_elasticsearch_{$type}} BEFORE INSERT OR UPDATE OR DELETE ON {{$type}}
                FOR EACH ROW EXECUTE PROCEDURE {search_elasticsearch_queue_trigger}()";
            execute_sql($sql);
        }
        else {
            foreach (self::$mysqltriggeroperations as $operation) {
                $sql = "DROP TRIGGER IF EXISTS {search_elasticsearch_{$type}_{$operation}};";
                execute_sql($sql);

                $oldid = ($operation == 'insert' ? 'null' : 'OLD.id');
                $newid = ($operation == 'delete' ? 'null' : 'NEW.id');
                $tablename = get_config('dbprefix') . ($type);

                // For inserts, the NEW.id is not available until AFTER the record is insereted.
                $triggertime = ($operation == 'insert' ? 'AFTER' : 'BEFORE');
                $sql = "CREATE TRIGGER {search_elasticsearch_{$type}_{$operation}} {$triggertime} {$operation} ON {{$type}}
                    FOR EACH ROW CALL {search_elasticsearch_queue_trigger}('{$tablename}', '{$operation}', {$oldid}, {$newid})";
                execute_sql($sql);
            }
        }
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
    }
}

/**
 * This class isn't really an ElasticsearchType, although in spirit it's similar. It's used only for the purpose of the "search all"
 * function
 */
class ElasticsearchPseudotype_all
{

    /**
     *   To respect the design, 3 searches will be executed:
     *       1st:    retrieves the main facet (Text / Media / Portfolio / Users / Group) and the count for each of them
     *       2nd:    - retrieves the results of the first non empty facet term for display in the tab
     *               - retrieves the secondary facet to enable / disable the filter items
     *       3nd:    - retrieves the results with all filters applied
     * @param unknown $query_string
     * @param unknown $limit
     * @param unknown $offset
     * @param unknown $options
     * @param unknown $mainfacetterm
     * @param unknown $USER
     * @return multitype:number boolean unknown Ambigous <boolean, NULL> Ambigous <boolean, unknown> multitype:multitype:string number   Ambigous <string, unknown> |multitype:multitype:
     */
    public static function search($query_string, $limit, $offset, $options, $mainfacetterm, $USER) {

        $result = array(
                'count'   => 0,
                'limit'   => $limit,
                'offset'  => $offset,
                'data'    => false,
                'selected' => (isset($mainfacetterm) && strlen($mainfacetterm)> 0) ? $mainfacetterm : false,
                'totalresults' => 0,
                'facets'  => array(
                        array('term' => "Text", 'count' => 0, 'display' => "Text"),
                        array('term' => "Media", 'count' => 0, 'display' => "Media"),
                        array('term' => "Portfolio", 'count' => 0, 'display' => "Portfolio"),
                        array('term' => "User", 'count' => 0, 'display' => "Users"),
                        array('term' => "Group", 'count' => 0, 'display' => "Group"),
                ),
                'content-filter'  => array(
                        array('term' => "all", 'count' => 0, 'display' => "All"),
                        array('term' => "Audio", 'count' => 0, 'display' => "Audio"),
                        array('term' => "Comment", 'count' => 0, 'display' => "Comment"),
                        array('term' => "Document", 'count' => 0, 'display' => "Document"),
                        array('term' => "Folder", 'count' => 0, 'display' => "Folder"),
                        array('term' => "Forum", 'count' => 0, 'display' => "Forum"),
                        array('term' => "Forumpost", 'count' => 0, 'display' => "Forum post"),
                        array('term' => "Image", 'count' => 0, 'display' => "Image"),
                        array('term' => "Journal", 'count' => 0, 'display' => "Journal"),
                        array('term' => "Journalentry", 'count' => 0, 'display' => "Journal entry"),
                        array('term' => "Note", 'count' => 0, 'display' => "Note"),
                        array('term' => "Plan", 'count' => 0, 'display' => "Plan"),
                        array('term' => "Profile", 'count' => 0, 'display' => "Profile"),
                        array('term' => "Resume", 'count' => 0, 'display' => "Résumé"),
                        array('term' => "Video", 'count' => 0, 'display' => "Video"),
                        array('term' => "Wallpost", 'count' => 0, 'display' => "Wall post"),
                        array('term' => "Collection", 'count' => 0, 'display' => "Collection"),
                        array('term' => "Page", 'count' => 0, 'display' => "Page"),
                ),
                'content-filter-selected' => (isset($options['secfacetterm']) && strlen($options['secfacetterm'])> 0) ? $options['secfacetterm'] : 'all',
                'owner-filter'  => array(
                        array('term' => "all", 'count' => 0, 'display' => "All"),
                        array('term' => "me", 'count' => 0, 'display' => "Me"),
                        array('term' => "others", 'count' => 0, 'display' => "Others"),
                ),
                'owner-filter-selected' => (isset($options['owner']) && strlen($options['owner'])> 0) ? $options['owner'] : 'all',
                'tagsonly' => (isset($options['tagsonly']) && ($options['tagsonly'] == true)) ? true : Null,
                'sort' => (isset($options['sort']) && strlen($options['sort'])> 0) ? $options['sort'] : 'score',
                'license' => (isset($options['license']) && strlen($options['license'])> 0) ? $options['license'] : 'all',
        );

        if (strlen($query_string) <= 0) {
            return $result;
        }

        //      1- Get main facet
        // ------------------------------------------------------------------------------------------

        $records = array();

        $elasticaClient = PluginSearchElasticsearch::make_client();
        $elasticaIndex = $elasticaClient->getIndex(get_config_plugin('search', 'elasticsearch', 'indexname'));

        $elasticaQueryString = new \Elastica\Query\QueryString();
        $elasticaAnalyzer = get_config_plugin('search', 'elasticsearch', 'analyzer');
        $elasticaQueryString->setAnalyzer($elasticaAnalyzer);
        $elasticaQueryString->setDefaultOperator('AND');
        $elasticaQueryString->setQuery($query_string);
        // if tags only => set fields to tags
        if ($result['tagsonly'] === true) {
            $elasticaQueryString->setFields(array('tags'));
        }

        // Create the $elasticaQuery object
        $elasticaQuery = new \Elastica\Query();
        $elasticaQuery->setFrom($offset);
        $elasticaQuery->setLimit($limit);
        $elasticaQuery->setQuery($elasticaQueryString);

        $elasticaFilterAnd  = new \Elastica\Filter\BoolAnd();

        // Apply ACL filters
        $elasticaFilterACL   = new ElasticsearchFilterAcl($USER);
        $elasticaFilterAnd->addFilter($elasticaFilterACL);
        $elasticaQuery->setFilter($elasticaFilterAnd);

        // Define a new facet: mainFacetTerm  - WARNING: don't forget to apply the same filter to the facet
        $elasticaFacet  = new \Elastica\Facet\Terms('mainFacetTerm');
        $elasticaFacet->setField('mainfacetterm');
        $elasticaFacet->setOrder('count');
        $elasticaFacet->setFilter($elasticaFilterAnd);
        $elasticaQuery->addFacet($elasticaFacet);

        $elasticaResultSet  = $elasticaIndex->search($elasticaQuery);
        $result['totalresults']    = $elasticaResultSet->getTotalHits();

        $elasticaFacets = $elasticaResultSet->getFacets();

        $facets = self::process_facets($elasticaFacets['mainFacetTerm']['terms']);
        if (count($facets) == 0) {
            return $result;
        }
        array_walk($result['facets'], 'self::process_tabs', $facets);
        if ($result['selected'] === false || $facets[$result['selected']] == 0) {
            $result['selected'] = self::get_selected_facet($result['facets']);
        }


        //      2- Retrieve results of selected facet
        // ------------------------------------------------------------------------------------------

        $elasticaFilterType = new \Elastica\Filter\Term(array('mainfacetterm' => $result['selected']));
        $elasticaFilterAnd->addFilter($elasticaFilterType);
        $elasticaQuery->setFilter($elasticaFilterAnd);

        // Define a new facet: secFacetTerm  - WARNING: don't forget to apply the same filter to the facet
        $elasticaFacet  = new \Elastica\Facet\Terms('secFacetTerm');
        $elasticaFacet->setField('secfacetterm');
        $elasticaFacet->setOrder('count');
        $elasticaFacet->setFilter($elasticaFilterAnd);
        $elasticaQuery->addFacet($elasticaFacet);

        // Sorting
        // Sorting is defined on a per field level, so we must make sure the field exists in the mapping
        $sort = explode('_', $result['sort']);
        if ($sort[0] == 'score') {
            $sort[0] = '_score';
        }
1277
1278
1279
1280
1281
1282
        // set the second column to sort by the score (to break any 'ties').
        $elasticaQuery->setSort(array(
            array($sort[0] => array('order' => (isset($sort[1]) ? $sort[1] : 'desc'))),
            array('_score' => array('order' => 'desc')),
            )
        );
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377

        $elasticaResultSet  = $elasticaIndex->search($elasticaQuery);
        $result['count']    = $elasticaResultSet->getTotalHits();

        $elasticaFacets = $elasticaResultSet->getFacets();
        $facets = $elasticaFacets['secFacetTerm']['terms'];
        $facets = self::process_facets($elasticaFacets['secFacetTerm']['terms']);
        array_walk($result['content-filter'], 'self::process_tabs', $facets);
        // set the count of "all" to the total hits
        $result['content-filter'][0]['count'] = $result['count'];


        //      3- Apply filters and retrieve final results
        // ------------------------------------------------------------------------------------------

        // Apply Content filter if different from "all"
        if ($result['content-filter-selected'] != 'all') {
            $elasticaFilterContent = new \Elastica\Filter\Term(array('secfacetterm' => $result['content-filter-selected']));
            $elasticaFilterAnd->addFilter($elasticaFilterContent);
        }
        // Apply Owner filter if different from "all"
        if ($result['owner-filter-selected'] != 'all') {
            $uid = $USER->get('id');
            $elasticaFilterOwner = new \Elastica\Filter\Term(array('owner' => $uid));
            if ($result['owner-filter-selected'] == 'others') {
                $elasticaFilterOwner = new \Elastica\Filter\BoolNot($elasticaFilterOwner);
            }
            $elasticaFilterAnd->addFilter($elasticaFilterOwner);
        }
        // Apply license filter if different from "all"
        if ($result['license'] != 'all') {
            $elasticaFilterLicense = new \Elastica\Filter\Term(array('license' => $result['license']));
            $elasticaFilterAnd->addFilter($elasticaFilterLicense);
        }

        $elasticaQuery->setFilter($elasticaFilterAnd);
        $elasticaResultSet  = $elasticaIndex->search($elasticaQuery);
        $elasticaResults    = $elasticaResultSet->getResults();
        $result['count']    = $elasticaResultSet->getTotalHits();

        foreach ($elasticaResults as $elasticaResult) {
            $tmp = array();
            $tmp['type'] = $elasticaResult->getType();
            $ES_class = 'ElasticsearchType_' . $tmp['type'];
            $tmp = $tmp + $elasticaResult->getData();
            // Get all the data from the DB table
            $dbrec = $ES_class::getRecordDataById($tmp['type'], $tmp['id']);
            if ($dbrec) {
                $tmp['db'] = $dbrec;
                $tmp['db']->deleted = false;
            }
            else {
                // If the record has been deleted, so just pass the cached data
                // from the search result. Let the template decide how to handle
                // it.
                $tmp['db'] = (object) $tmp;
                $tmp['db']->deleted = true;
            }
            $records[] = $tmp;
        }

        $result['data'] = $records;

        return $result;
    }

    public static function process_facets($data) {
        $tmp = array();
        foreach ($data as $key => $value) {
            $tmp[$value['term']] = $value['count'];
        }
        return $tmp;
    }

    public static function process_tabs(&$item, $key, $data) {
        if (isset($data[$item['term']])) {
            $item['count'] = $data[$item['term']];
        }
    }

    public static function get_selected_facet($data) {
        foreach ($data as $key => $value) {
            if ($value['count'] > 0) {
                return $value['term'];
            }
        }
    }
}


/**
 * A class that holds static functions relating to Indexing
 */
class ElasticsearchIndexing {

1378
1379
1380
    // mysql tables require a trigger for each operation - insert, update, delete.
    private static $mysqltriggeroperations = array('insert', 'update', 'delete');

1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
    /**
     * Creates the Index on the elasticsearch server itself, first dropping if it already
     * exists.
     */
    public static function create_index() {
        $esclient = PluginSearchElasticsearch::make_client();
        $elasticaIndex = $esclient->getIndex(PluginSearchElasticsearch::get_write_indexname());
        // Create the index, deleting it first if it already exists
        $elasticaIndex->create(
            array(
1391
1392
1393
1394
// Uncomment the following if you want to overwrite the number of shards/replicas set by ElasticSearch's
// default, or the settings specified in elasticsearch.yml file.
//                'number_of_shards' => 5,
//                'number_of_replicas' => 1,
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
                'analysis' => array(
                    'analyzer' => array(
                        'mahara_analyzer' => array(
                            'type' => 'custom',
                            'tokenizer' => 'pattern', // define token separators as any non-alphanumeric character
                            'filter' => array('standard', 'lowercase', 'stop', 'maharaSnowball'),
                            'char_filter' => array('maharaHtml'),
                        ),
                    ),
                    'filter' => array(
                        'maharaSnowball' => array(
                            'type' => 'snowball',
                            'language' => 'English',
                        )
                    ),
                    'char_filter' => array(
                        'maharaHtml' => array(
                            'type' => 'html_strip',
                            'read_ahead' => '1024',
                        )
                    ),
                )
            ),
            true
        );
    }

    /**
     * Clears the indexing queue table for this searchtype, and then re-loads it with every matching item in the
     * database.
     * @param string $type The elasticsearch search type
     * @param string $artefacttype (Optional) If the search type is Artefact, this is the artefact subtype
     */
    public static function requeue_searchtype_contents($type, $artefacttype = null) {

        $condition = '';
        $insert_sql = "INSERT INTO {search_elasticsearch_queue} (itemid, type) SELECT id, '" . $type . "' FROM {" . $type . "}";
        if ($type == 'view') {
            $insert_sql .= ' WHERE (id != 0 AND (owner != 0 OR "group" !=0))';
        }
        else if ($type == 'usr') {
            $insert_sql .= ' WHERE id != 0';
        }
        if ($type == 'artefact') {
            $condition = " AND artefacttype IN ";
            $condition .= isset($artefacttype) ? "('$artefacttype')" : self::artefacttypes_filter_string();

            $insert_sql = "INSERT INTO {search_elasticsearch_queue} (itemid, type, artefacttype)
                            SELECT id, 'artefact', artefacttype FROM {artefact} WHERE " . substr($condition, 4);
        }

        $sql = "DELETE FROM {search_elasticsearch_queue} WHERE type = ? $condition";
        execute_sql($sql, array($type));

        execute_sql($insert_sql);
    }


    /**
     *   Check if access changed between the last time the function was called (view_access table) and
     *   add items to the queue
     */
    public static function add_to_queue_access($last_run, $timestamp) {

        $artefacttypes_str = self::artefacttypes_filter_string();

        execute_sql("
            INSERT INTO {search_elasticsearch_queue} (itemid, type)
            SELECT view, 'view'
            FROM {view_access} WHERE startdate BETWEEN '{$last_run}' AND '{$timestamp}'
            OR stopdate BETWEEN  '{$last_run}' AND '{$timestamp}'
            ;"
        );

        execute_sql("
            INSERT INTO {search_elasticsearch_queue} (itemid, type, artefacttype)
            SELECT var.artefact, 'artefact', a.artefacttype
            FROM {view_access} vac
            INNER JOIN {view_artefact} var ON var.view = vac.view
            INNER JOIN {artefact} a ON var.artefact = a.id
            WHERE
                (
                    vac.startdate BETWEEN '{$last_run}' AND '{$timestamp}'
                    OR vac.stopdate BETWEEN  '{$last_run}' AND '{$timestamp}'
                )
                AND a.artefacttype IN {$artefacttypes_str}
            ;"
        );
    }

    /**
     * Delete the trigger functions used by elasticsearch. Since we're deleting by
     * CASCADE, this will also delete the triggers which use these functions
     */
    public static function drop_trigger_functions() {
1490
1491
1492
        if (is_postgres()) {
            $sql = 'DROP FUNCTION IF EXISTS {search_elasticsearch_queue_trigger}() CASCADE;';
            execute_sql($sql);
1493

1494
1495
            $sql = 'DROP FUNCTION IF EXISTS {search_elasticsearch_queue_artefact_trigger}() CASCADE;';
            execute_sql($sql);
1496

1497
1498
1499
1500
1501
1502
            $sql = 'DROP FUNCTION IF EXISTS {search_elasticsearch_queue2_trigger}() CASCADE;';
            execute_sql($sql);
        }
        else {
            $sql = 'DROP PROCEDURE IF EXISTS {search_elasticsearch_queue_trigger};';
            execute_sql($sql);
1503

1504
1505
1506
1507
1508
1509
            $sql = 'DROP PROCEDURE IF EXISTS {search_elasticsearch_queue_artefact_trigger};';
            execute_sql($sql);

            $sql = 'DROP PROCEDURE IF EXISTS {search_elasticsearch_queue2_trigger};';
            execute_sql($sql);
        }
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
    }

    /**
     * Creates trigger functions used by elasticsearch. These detect indexable records being inserted, deleted, or updated, and put
     * records in search_elasticsearch_queue to tell the cron job to pass them on to the elasticsearch server.
     *
     * Note that these functions won't do anything until you call create_trigger(). The same trigger function is used
     * for multiple triggers, which is the reason why it's in this separate PHP function.
     *
     * NOTE that calling this function deletes ALL the elasticsearch triggers, because it deletes the trigger
     * functions, and that cascades to deleting the triggers that use them. So make sure you recreate the
     * triggers you want to retain, after you call this function.
     */
    public static function create_trigger_functions() {
        // Delete the trigger functions first.
        // NOTE: This also deletes ALL the elasticsearch triggers.
        self::drop_trigger_functions();

        $artefacttypes_str = self::artefacttypes_filter_string();

        // We'll use this to trim the prefix from table names before inserting them into
        // search_elasticsearch_queue.type
1532
1533
        $dbprefix = get_config('dbprefix');
        $prefixlength = strlen($dbprefix);
1534
        if ($prefixlength) {
1535
            $tablewithoutprefix = (is_postgres() ? "RIGHT(TG_TABLE_NAME, -{$prefixlength})" : "SUBSTRING(tablename, " . ($prefixlength + 1) . ")");
1536
1537
        }
        else {
1538
            $tablewithoutprefix= (is_postgres() ? 'TG_TABLE_NAME' : "tablename");
1539
1540
1541
1542
1543
1544
1545
1546
        }

        //----------------------------------------------------------------------------------------------------
        // search_elasticsearch_queue_trigger
        // For the usr, interaction_instance, interaction_forum_post, group, and view types
        //  - Set it to monitor the table the type is named after
        //  - On an INSERT, UPDATE, or DELETE, just inserts the record ID and the name of the type in the queue table
        //  - When you modify a view, you also insert a record for every artefact in that view
1547
1548
1549
1550
1551
1552
1553
        if (is_postgres()) {
            $sql = 'CREATE FUNCTION {search_elasticsearch_queue_trigger}() RETURNS trigger AS $search_elasticsearch_queue_trigger$
                BEGIN
                    IF (TG_OP=\'DELETE\') THEN
                        IF NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = OLD.id AND type = '.$tablewithoutprefix.') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type) VALUES (OLD.id, '.$tablewithoutprefix.');
                        END IF;
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
                        IF (TG_TABLE_NAME=\'' . $dbprefix . 'view\') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type)
                            SELECT u.id, \'usr\' AS type FROM {usr} u
                            INNER JOIN {view} v ON v.owner = u.id
                            WHERE v.type = \'profile\'
                                AND v.id = OLD.id
                                AND NOT EXISTS (
                                    SELECT q.id FROM {search_elasticsearch_queue} q
                                    WHERE q.type = \'usr\' AND q.itemid = u.id
                                );
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
                            INSERT INTO {search_elasticsearch_queue} (itemid, type)
                            SELECT va.artefact, \'artefact\' AS type
                            FROM {view_artefact} va
                            INNER JOIN {artefact} a ON va.artefact = a.id
                            WHERE va.view = OLD.id
                                AND va.artefact NOT IN (SELECT itemid FROM {search_elasticsearch_queue} WHERE type = \'artefact\')
                                AND a.artefacttype IN ' . $artefacttypes_str .';
                        END IF;
                        RETURN OLD;
                    ELSE
                        IF NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = NEW.id AND type = ' . $tablewithoutprefix . ') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type) VALUES (NEW.id, ' . $tablewithoutprefix . ');
                        END IF;
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
                        IF (TG_TABLE_NAME=\'' . $dbprefix . 'view\') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type)
                            SELECT u.id, \'usr\' AS type FROM {usr} u
                            INNER JOIN {view} v ON v.owner = u.id
                            WHERE v.type = \'profile\'
                                AND v.id = NEW.id
                                AND NOT EXISTS (
                                    SELECT q.id FROM {search_elasticsearch_queue} q
                                    WHERE q.type = \'usr\' AND q.itemid = u.id
                                );
1587
1588
1589
1590
1591
                            INSERT INTO {search_elasticsearch_queue} (itemid, type)
                            SELECT va.artefact, \'artefact\' AS type
                            FROM {view_artefact} va
                            INNER JOIN {artefact} a ON va.artefact = a.id
                            WHERE va.view = NEW.id
1592
1593
                            AND va.artefact NOT IN (SELECT itemid FROM {search_elasticsearch_queue} WHERE type = \'artefact\')
                            AND a.artefacttype IN ' . $artefacttypes_str .';
1594
1595
                        END IF;
                        RETURN NEW;
1596
                    END IF;
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
                END;
                $search_elasticsearch_queue_trigger$ LANGUAGE plpgsql;';
        }
        else {
            $sql = 'CREATE PROCEDURE {search_elasticsearch_queue_trigger}
                        (tablename varchar(64), operation varchar(10), oldid bigint, newid bigint)
                BEGIN
                    IF (operation=\'delete\') THEN
                        IF NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = oldid AND type = '.$tablewithoutprefix.') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type) VALUES (oldid, '.$tablewithoutprefix.');
                        END IF;
                        IF (tablename=\'' . $dbprefix . 'view\') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type)
1610
1611
1612
1613
1614
1615
1616
1617
1618
                            SELECT u.id, \'usr\' AS type FROM {usr} u
                            INNER JOIN {view} v ON v.owner = u.id
                            WHERE v.type = \'profile\'
                                AND v.id = oldid
                                AND NOT EXISTS (
                                    SELECT q.id FROM {search_elasticsearch_queue} q
                                    WHERE q.type = \'usr\' AND q.itemid = u.id
                                );
                            INSERT INTO {search_elasticsearch_queue} (itemid, type)
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
                            SELECT va.artefact, \'artefact\' AS type
                            FROM {view_artefact} va
                            INNER JOIN {artefact} a ON va.artefact = a.id
                            WHERE va.view = oldid
                                AND va.artefact NOT IN (SELECT itemid FROM {search_elasticsearch_queue} WHERE type = \'artefact\')
                                AND a.artefacttype IN ' . $artefacttypes_str .';
                        END IF;
                    ELSE
                        IF NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = newid AND type = ' . $tablewithoutprefix . ') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type) VALUES (newid, ' . $tablewithoutprefix . ');
                        END IF;
                        IF (tablename=\'' . $dbprefix . 'view\') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type)
1632
1633
1634
1635
1636
1637
1638
1639
1640
                            SELECT u.id, \'usr\' AS type FROM {usr} u
                            INNER JOIN {view} v ON v.owner = u.id
                            WHERE v.type = \'profile\'
                                AND v.id = newid
                                AND NOT EXISTS (
                                    SELECT q.id FROM {search_elasticsearch_queue} q
                                    WHERE q.type = \'usr\' AND q.itemid = u.id
                                );
                            INSERT INTO {search_elasticsearch_queue} (itemid, type)
1641
1642
1643
1644
1645
1646
1647
                            SELECT va.artefact, \'artefact\' AS type
                            FROM {view_artefact} va
                            INNER JOIN {artefact} a ON va.artefact = a.id
                            WHERE va.view = newid
                            AND va.artefact NOT IN (SELECT itemid FROM {search_elasticsearch_queue} WHERE type = \'artefact\')
                            AND a.artefacttype IN ' . $artefacttypes_str .';
                        END IF;
1648
                    END IF;
1649
1650
                END';
        }
1651
1652
1653
1654
1655
1656
1657
1658
        execute_sql($sql);

        //----------------------------------------------------------------------------------------------------
        // search_elasticsearch_queue_artefact_trigger
        // For the artefact type
        //   - Set it to monitor the artefact table
        //   - The main difference from the search_elasticsearch_queue_trigger, is that it also populates the
        //     artefacttype column in the queue table.
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
        if (is_postgres()) {
            $sql = 'CREATE FUNCTION {search_elasticsearch_queue_artefact_trigger}() RETURNS trigger AS $search_elasticsearch_queue_artefact_trigger$
                BEGIN
                    IF (TG_OP=\'DELETE\') THEN
                        IF (OLD.artefacttype IN ' . $artefacttypes_str . ') AND NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = OLD.id AND type = ' . $tablewithoutprefix . ') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type, artefacttype) VALUES (OLD.id, ' . $tablewithoutprefix . ', OLD.artefacttype);
                        END IF;
                        RETURN OLD;
                    ELSE
                        IF (NEW.artefacttype IN ' . $artefacttypes_str . ') AND NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = NEW.id AND type = '.$tablewithoutprefix.') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type, artefacttype) VALUES (NEW.id, '.$tablewithoutprefix.', NEW.artefacttype);
                        END IF;
                        RETURN NEW;
1672
                    END IF;
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
                END;
                $search_elasticsearch_queue_artefact_trigger$ LANGUAGE plpgsql;';
        }
        else {
            $sql = 'CREATE PROCEDURE {search_elasticsearch_queue_artefact_trigger}
                        (tablename varchar(64), operation varchar(10), oldid bigint, oldartefacttype varchar(255), newid bigint, newartefacttype varchar(255))
                BEGIN
                    IF (operation=\'delete\') THEN
                        IF (oldartefacttype IN ' . $artefacttypes_str . ') AND NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = oldid AND type = ' . $tablewithoutprefix . ') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type, artefacttype) VALUES (oldid, ' . $tablewithoutprefix . ', oldartefacttype);
                        END IF;
                    ELSE
                        IF (newartefacttype IN ' . $artefacttypes_str . ') AND NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = newid AND type = ' . $tablewithoutprefix . ') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type, artefacttype) VALUES (newid, ' . $tablewithoutprefix . ', newartefacttype);
                        END IF;
1688
                    END IF;
1689
1690
                END';
        }
1691
1692
1693
1694
1695
1696
        execute_sql($sql);

        //----------------------------------------------------------------------------------------------------
        // search_elasticsearch_queue2_trigger
        //   - For the view_artefact table
        //   - Whenever that table is modified, add a record into the queue table for the artefact mentioned
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
        if (is_postgres()) {
            $sql = 'CREATE FUNCTION {search_elasticsearch_queue2_trigger}() RETURNS trigger AS $search_elasticsearch_queue2_trigger$
                BEGIN
                    IF (TG_OP=\'DELETE\') THEN
                        IF NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = OLD.artefact AND type = \'artefact\') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type) VALUES (OLD.artefact, \'artefact\');
                        END IF;
                        RETURN OLD;
                    ELSE
                        IF NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = NEW.artefact AND type = \'artefact\') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type) VALUES (NEW.artefact, \'artefact\');
                        END IF;
                        RETURN NEW;
1710
                    END IF;
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
                END;
                $search_elasticsearch_queue2_trigger$ LANGUAGE plpgsql;';
        }
        else {
            $sql = 'CREATE PROCEDURE {search_elasticsearch_queue2_trigger}
                        (tablename varchar(64), operation varchar(10), oldartefact bigint, newartefact bigint)
                BEGIN
                    IF (operation=\'delete\') THEN
                        IF NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = oldartefact AND type = \'artefact\') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type) VALUES (oldartefact, \'artefact\');
                        END IF;
                    ELSE
                        IF NOT EXISTS (SELECT 1 FROM {search_elasticsearch_queue} WHERE itemid = newartefact AND type = \'artefact\') THEN
                            INSERT INTO {search_elasticsearch_queue} (itemid, type) VALUES (newartefact, \'artefact\');
                        END IF;
1726
                    END IF;
1727
1728
                END';
        }
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
        execute_sql($sql);
    }

    /**
     * Drop the triggers for a Mahara search type.
     *
     * @param string $type the Mahara searchtype to drop the trigger(s) for
     */
    public static function drop_triggers($type) {
        // The artefact type uses different trigger functions than the other types
        if ($type == 'artefact') {
1740
1741
1742
            if (is_postgres()) {
                $sql = "DROP FUNCTION IF EXISTS {search_elasticsearch_{$type}}() CASCADE;";
                execute_sql($sql);
1743

1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
                $sql = "DROP FUNCTION IF EXISTS {search_elasticsearch_view_artefact}() CASCADE;";
                execute_sql($sql);
            }
            else {
                // need to drop 3 triggers for INSERT, UPDATE and DELETE
                foreach (self::$mysqltriggeroperations as $operation) {
                    $sql = "DROP TRIGGER IF EXISTS {search_elasticsearch_{$type}_{$operation}};";
                    execute_sql($sql);

                    $sql = "DROP TRIGGER IF EXISTS {search_elasticsearch_view_artefact_{$operation}};";
                    execute_sql($sql);
                }
            }
1757
1758
        }
        else {
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
            if (is_postgres()) {
                $sql = "DROP FUNCTION IF EXISTS {search_elasticsearch_{$type}}() CASCADE;";
                execute_sql($sql);
            }
            else {
                // need to drop 3 triggers for INSERT, UPDATE and DELETE
                foreach (self::$mysqltriggeroperations as $operation) {
                    $sql = "DROP TRIGGER IF EXISTS {search_elasticsearch_{$type}_{$operation}}";
                    execute_sql($sql);
                }
            }
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
        }
    }

    /**
     * Creates the trigger for a Mahara search type. The actual trigger function was created by create_trigger_functions();
     * If we were to make the ElasticsearchType into a more fully fleshed-out plugin, we'd want to devolve
     * this to the plugin itself.
     *
     * @param string $type The Mahara searchtype to (re) create the trigger for
     */
    public static function create_triggers($type) {
        self::drop_triggers($type);
        // The artefact type uses different trigger functions than the other types
        if ($type == 'artefact') {
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
            if (is_postgres()) {
                $sql = "CREATE TRIGGER {search_elasticsearch_{$type}} BEFORE INSERT OR UPDATE OR DELETE ON {{$type}}
                        FOR EACH ROW EXECUTE PROCEDURE {search_elasticsearch_queue_artefact_trigger}()";
                execute_sql($sql);

                $sql = "CREATE TRIGGER {search_elasticsearch_view_artefact} BEFORE INSERT OR UPDATE OR DELETE ON {view_artefact}
                        FOR EACH ROW EXECUTE PROCEDURE {search_elasticsearch_queue2_trigger}()";
                execute_sql($sql);
            }
            else {
                foreach (self::$mysqltriggeroperations as $operation) {
                    $oldid = ($operation == 'insert' ? 'null' : 'OLD.id');
                    $newid = ($operation == 'delete' ? 'null' : 'NEW.id');
                    $oldartefacttype = ($operation == 'insert' ? 'null' : 'OLD.artefacttype');
                    $newartefacttype = ($operation == 'delete' ? 'null' : 'NEW.artefacttype');
                    $oldartefact = ($operation == 'insert' ? 'null' : 'OLD.artefact');
                    $newartefact = ($operation == 'delete' ? 'null' : 'NEW.artefact');
                    // For inserts, the NEW.id is not available until AFTER the record is insereted.
                    $triggertime = ($operation == 'insert' ? 'AFTER' : 'BEFORE');
                    // To remove confusion, include the table prefix if it exists as we'll be
                    // passing the actual table name to the stored procedure.
                    $tablename = get_config('dbprefix') . $type;
                    $viewtablename = get_config('dbprefix') . 'view_artefact';

                    // create 3 triggers on the artefact table.
                    $sql = "CREATE TRIGGER {search_elasticsearch_{$type}_{$operation}} {$triggertime} {$operation} ON {{$type}}
                            FOR EACH ROW CALL {search_elasticsearch_queue_artefact_trigger}('{$tablename}', '{$operation}', {$oldid}, {$oldartefacttype}, {$newid}, {$newartefacttype})";
                    execute_sql($sql);

                    // create 3 triggers on the view_artefact table.
                    $sql = "CREATE TRIGGER {search_elasticsearch_view_artefact_{$operation}} {$triggertime} {$operation} ON {view_artefact}
                            FOR EACH ROW CALL {search_elasticsearch_queue2_trigger}('{$viewtablename}', '{$operation}', {$oldartefact}, {$newartefact})";
                    execute_sql($sql);
                }
            }
1819
1820
        }
        else {
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
            if (is_postgres()) {
                $sql = "CREATE TRIGGER {search_elasticsearch_{$type}} BEFORE INSERT OR UPDATE OR DELETE ON {{$type}}
                    FOR EACH ROW EXECUTE PROCEDURE {search_elasticsearch_queue_trigger}()";
                execute_sql($sql);
            }
            else {
                // create the 3 triggers on the table.
                foreach (self::$mysqltriggeroperations as $operation) {
                    $oldid = ($operation == 'insert' ? 'null' : 'OLD.id');
                    $newid = ($operation == 'delete' ? 'null' : 'NEW.id');
                    // For inserts, the NEW.id is not available until AFTER the record is insereted.
                    $triggertime = ($operation == 'insert' ? 'AFTER' : 'BEFORE');
                    // To remove confusion, include the table prefix if it exists as we'll be
                    // passing the actual table name to the stored procedure.
                    $tablename = get_config('dbprefix') . ($type);

                    $sql = "CREATE TRIGGER {search_elasticsearch_{$type}_{$operation}} {$triggertime} {$operation} ON {{$type}}
                            FOR EACH ROW CALL {search_elasticsearch_queue_trigger}('{$tablename}', '{$operation}', {$oldid}, {$newid})";
                    execute_sql($sql);
                }
            }
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
        }
    }

    public static function artefacttypes_filter_string() {

        $artefacttypes = explode(',', get_config_plugin('search', 'elasticsearch', 'artefacttypes'));
                $artefacttypes_str = '';
                foreach ($artefacttypes as $artefacttype) {
                $artefacttypes_str .= '\'' . $artefacttype . '\', ';
        }
        $artefacttypes_str = '(' . substr($artefacttypes_str, 0, strlen($artefacttypes_str)-2) . ')';

        return $artefacttypes_str;

    }
}