searchlib.php 42.7 KB
Newer Older
Martyn Smith's avatar
Martyn Smith committed
1
2
3
4
5
<?php
/**
 *
 * @package    mahara
 * @subpackage core
6
 * @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.
Martyn Smith's avatar
Martyn Smith committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 * @copyright  (C) portions from Moodle, (C) Martin Dougiamas http://dougiamas.com
 */

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

/**
 * Given a query string and limits, return an array of matching users using the
 * search plugin defined in config.php
 *
 * @param string  The query string
 * @param integer How many results to return
 * @param integer What result to start at (0 == first result)
 * @return array  A data structure containing results looking like ...
 *         $results = array(
 *               count   => integer, // total number of results
 *               limit   => integer, // how many results are returned
 *               offset  => integer, // starting from which result
 *               results => array(   // the result records
 *                   array(
28
29
30
31
32
33
34
 *                       id            => integer,
 *                       username      => string,
 *                       institution   => string,
 *                       firstname     => string,
 *                       lastname      => string,
 *                       preferredname => string,
 *                       email         => string,
Martyn Smith's avatar
Martyn Smith committed
35
36
 *                   ),
 *                   array(
37
38
39
40
41
42
43
 *                       id            => integer,
 *                       username      => string,
 *                       institution   => string,
 *                       firstname     => string,
 *                       lastname      => string,
 *                       preferredname => string,
 *                       email         => string,
Martyn Smith's avatar
Martyn Smith committed
44
45
46
47
48
 *                   ),
 *                   array(...),
 *               ),
 *           );
 */
49
function search_user($query_string, $limit, $offset = 0, $data = array()) {
Martyn Smith's avatar
Martyn Smith committed
50
    $plugin = get_config('searchplugin');
51
    safe_require('search', $plugin);
52
    $results = call_static_method(generate_class_name('search', $plugin), 'search_user', $query_string, $limit, $offset, $data);
53

54
    if ($results['data']) {
55
56
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
57
            $result['url']  = profile_url($result);
58
59
60
61
        }
    }

    return $results;
62
63
}

64
65
66
67
68
69
70
71
72
73
74
75
76
/*
*   The elastic search plug-in is for now only used in the "Universal Search" page.
*   Search is performed using the internal plug-in in all other case.
*   This might change in the future.
*/
function search_all($query_string, $limit, $offset = 0, $data = array(), $type = null) {
    if (record_exists('search_installed', 'name', 'elasticsearch', 'active', 1)) {
        safe_require('search', 'elasticsearch');
        $plugin = 'elasticsearch';
        $results = call_static_method(generate_class_name('search', $plugin), 'search_all', $query_string, $limit, $offset, $data, $type);
        return $results;
    }
}
77

78

79
/*
80
81
82
83
84
85
86
87
88
89
90
 * Institutional admin queries:
 *
 * These are only used to populate user lists on the Institution
 * Members page.  They may return users who are not in the same
 * institution as the logged in institutional admin, so they should
 * return names only, not email addresses.
 */

function get_institutional_admin_search_results($search, $limit) {
    $institution = new StdClass;
    $institution->name = $search->institution;
91
    foreach (array('member', 'requested', 'invitedby', 'lastinstitution') as $p) {
92
93
94
95
        $institution->{$p} = $search->{$p};
    }
    $results = institutional_admin_user_search($search->query, $institution, $limit);
    if ($results['count']) {
96
97
98
99
        foreach ($results['data'] as &$r) {
            $r['name'] = $r['firstname'] . ' ' . $r['lastname'] . ' (' . $r['username'] . ')';
            if (!empty($r['studentid'])) {
                $r['name'] .= ' (' . $r['studentid'] . ')';
100
            }
101
102
103
104
105
106
107
108
        }
    }
    return $results;
}

function institutional_admin_user_search($query, $institution, $limit) {
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);
109
    return call_static_method(generate_class_name('search', $plugin), 'institutional_admin_search_user',
110
111
112
113
                              $query, $institution, $limit);
}


114
115
116
117
118
/**
 * Pull two-word phrases out of a query for matching against first,last names.
 *
 * This function comes from Drupal's search module, with some small changes.
 */
119

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
function parse_name_query($text) {
  $words = array();
  $fullnames = array();

  // Tokenize query string
  preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' '. $text, $matches, PREG_SET_ORDER);

  if (count($matches) < 1) {
    return NULL;
  }

  // Classify tokens
  foreach ($matches as $match) {
    // Strip off phrase quotes
    if ($match[1]{0} == '"') {
      $phrase = preg_replace('/\s\s+/', ' ', strtolower(substr($match[1], 1, -1)));
136
      $phraselist = explode(' ', $phrase);
137
138
139
140
141
142
143
144
145
146
147
148
      if (count($phraselist) == 2) {
        $fullnames[] = $phraselist;
      } else {
        $words = array_merge($words, array($phrase));
      }
    } else {
      $words = array_merge($words, array(strtolower($match[1])));
    }
  }
  return array($words, $fullnames);

}
149

150
function get_admin_user_search_results($search, $offset, $limit) {
151
152
153
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);

154
    $constraints = array();
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190

    if ($plugin == 'internal') {
        // For the internal plugin, just pass the raw query through as a string, it
        // is parsed in the plugin.
        $queries = $search->query;
    }
    else {
        // In admin search, the search string is interpreted as either a
        // name search or an email search depending on its contents
        $queries = array();
        if (!empty($search->query)) {
            list($words, $fullnames) = parse_name_query($search->query);
            foreach ($words as $word) {
                if (strpos($word, '@') !== false) {
                    $queries[] = array(
                        'field' => 'email',
                        'type' => 'contains',
                        'string' => $word
                    );
                }
                else {
                    $queries[] = array(
                        'field' => 'firstname',
                        'type' => 'contains',
                        'string' => $word
                    );
                    $queries[] = array(
                        'field' => 'lastname',
                        'type' => 'contains',
                        'string' => $word
                    );
                    $queries[] = array(
                        'field' => 'username',
                        'type' => 'contains',
                        'string' => $word
                    );
191
192
193
194
195
                    $queries[] = array(
                        'field' => 'preferredname',
                        'type' => 'contains',
                        'string' => $word
                    );
196
197
198
199
200
201
202
203
204
205
206
207
208
                }
            }
            foreach ($fullnames as $n) {
                $constraints[] = array(
                    'field' => 'firstname',
                    'type' => 'contains',
                    'string' => $n[0]
                );
                $constraints[] = array(
                    'field' => 'lastname',
                    'type' => 'contains',
                    'string' => $n[1]
                );
209
            }
210
211
        }
    }
212

213
214
215
216
217
218
219
220
    if (!empty($search->authname)) {
        $constraints[] = array(
            'field' => 'authname',
            'type' => 'equals',
            'string' => $search->authname
        );
    }

Richard Mansfield's avatar
Richard Mansfield committed
221
222
223
224
225
226
227
228
229
230
    if (!empty($search->f)) {
        $constraints[] = array('field' => 'firstname',
                               'type' => 'starts',
                               'string' => $search->f);
    }
    if (!empty($search->l)) {
        $constraints[] = array('field' => 'lastname',
                               'type' => 'starts',
                               'string' => $search->l);
    }
231
    if (!empty($search->loggedin) && $search->loggedin !== 'any') {
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
        if ($search->loggedin == 'never') {
            $constraints[] = array('field'  => 'lastlogin',
                                   'type'   => 'equals',
                                   'string' => null);
        }
        else if ($search->loggedin == 'ever') {
            $constraints[] = array('field'  => 'lastlogin',
                                   'type'   => 'notequals',
                                   'string' => null);
        }
        else if ($search->loggedin == 'since') {
            $constraints[] = array('field'  => 'lastlogin',
                                   'type'   => 'greaterthan',
                                   'string' => $search->loggedindate);
        }
        else if ($search->loggedin == 'notsince') {
            $constraints[] = array('field'  => 'lastlogin',
                                   'type'   => 'lessthanequal',
                                   'string' => $search->loggedindate);
        }

    }
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
    // Filter by export queue items
    if (!empty($search->exportqueue)) {
        $exportqueueusers = get_column_sql('SELECT usr FROM {export_queue}');
        if (empty($exportqueueusers)) {
            // use a fake id number so that the query's in function will return no results
            $exportqueueusers = array(-1);
        }
        $constraints[] = array(
            'field'  => 'exportqueue',
            'type'   => 'in',
            'string' => array_unique($exportqueueusers),
        );
    }
    // Filter by archived submissions
    if (!empty($search->archivedsubmissions)) {
        $archivesubmissionsusers = get_column_sql('SELECT usr FROM {export_archive} e JOIN {archived_submissions} a ON a.archiveid = e.id');
        if (empty($archivesubmissionsusers)) {
            // use a fake id number so that the query's in function will return no results
            $archivesubmissionsusers = array(-1);
        }
        $constraints[] = array(
            'field'  => 'archivesubmissions',
            'type'   => 'in',
            'string' => array_unique($archivesubmissionsusers),
        );
    }
280
    // Filter by duplicate emails
281
    if (!empty($search->duplicateemail)) {
282
283
284
285
286
287
288
        $duplicateemailartefacts = get_column_sql('
            SELECT id
            FROM {artefact}
            WHERE
                artefacttype = \'email\'
                AND LOWER(title) IN (
                    SELECT LOWER(title)
289
                    FROM {artefact}
290
291
292
293
294
295
296
297
298
299
300
301
302
303
                    WHERE artefacttype = \'email\'
                    GROUP BY LOWER(title)
                    HAVING count(id) > 1
                )');
        if ($duplicateemailartefacts === false || !is_array($duplicateemailartefacts)) {
            $duplicateemailartefacts = array();
        }
        $constraints[] = array(
            'field'  => 'duplicateemail',
            'type'   => 'in',
            'string' => $duplicateemailartefacts
        );
    }

304
305
    // Filter by viewable institutions:
    global $USER;
306
307
    if (!$USER->get('admin') && !$USER->get('staff')) {
        $allowed = array_merge($USER->get('admininstitutions'), $USER->get('staffinstitutions'));
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        if (empty($search->institution)) {
            $search->institution = 'all';
        }
        if ($search->institution == 'all' || !isset($allowed[$search->institution])) {
            $constraints[] = array(
                'field'  => 'institution',
                'type'   => 'in',
                'string' => $allowed,
            );
        }
        else {
            $constraints[] = array(
                'field'  => 'institution',
                'type'   => 'equals',
                'string' => $search->institution,
            );
324
        }
325
    } else if (!empty($search->institution) && $search->institution != 'all') {
Richard Mansfield's avatar
Richard Mansfield committed
326
327
328
        $constraints[] = array('field' => 'institution',
                               'type' => 'equals',
                               'string' => $search->institution);
329
    }
330

331
332
    $results = call_static_method(
        generate_class_name('search', $plugin), 'admin_search_user',
333
        $queries, $constraints, $offset, $limit, $search->sortby, $search->sortdir
334
335
    );

336
    if ($results['count']) {
337
338
339
        $isadmin = $USER->get('admin');
        $admininstitutions = $USER->get('admininstitutions');

340
341
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
342
343
344
            if (!empty($result['institutions'])) {
                $result['institutions'] = array_combine($result['institutions'],$result['institutions']);
            }
345

346
            // Show all user's emails
347
            if (!empty($search->duplicateemail)) {
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
                $selectstr = 'title, (CASE WHEN id IN (' . join(',', array_map('db_quote', $duplicateemailartefacts)) . ') THEN 1 ELSE 0 END) AS duplicated';
            }
            else {
                $selectstr = 'title';
            }
            $emails = get_records_sql_array('
                SELECT ' . $selectstr . '
                FROM {artefact} a
                WHERE a.artefacttype = ?
                    AND a.owner = ?',
                array('email', $result['id']));
            if (is_array($emails)) {
                for ($i = 0; $i < count($emails); $i++) {
                    // Move primary email to the beginning of $emails
                    if ($emails[0]->title == $result['email']) {
                        break;
                    }
                    if ($emails[$i]->title == $result['email']) {
                        $e = $emails[0];
                        $emails[0] = $emails[$i];
                        $emails[$i] = $e;
                        break;
370
371
                    }
                }
372
                $emails[0]->primary = 1;
373
            }
374
375
376
377
            else {
                $emails = array();
            }
            $result['email'] = $emails;
378
379
380
381
382
383
384
            if ($isadmin) {
                continue;
            }

            // Remove email address when viewed by staff
            if (!$hideemail = (empty($admininstitutions) || empty($result['institutions']))) {
                $commoninstitutions = array_intersect($admininstitutions, $result['institutions']);
385
                $hideemail = $hideemail || empty($commoninstitutions);
386
387
388
389
            }
            if ($hideemail) {
                unset($result['email']);
            }
390
        }
391
    }
392

393
    return $results;
394
395
396
}


397
function build_admin_user_search_results($search, $offset, $limit) {
398
    global $USER, $THEME;
399

400
    $wantedparams = array('query', 'f', 'l', 'sortby', 'sortdir', 'loggedin', 'loggedindate', 'duplicateemail', 'institution', 'authname');
401
402
    $params = array();
    foreach ($search as $k => $v) {
403
404
405
        if (!in_array($k, $wantedparams)) {
            continue;
        }
406
407
408
409
        if (!empty($v)) {
            $params[] = $k . '=' . $v;
        }
    }
410
    $searchurl = get_config('wwwroot') . 'admin/users/search.php?' . join('&', $params) . '&limit=' . $limit;
411

412
413
    $results = get_admin_user_search_results($search, $offset, $limit);

414
    $pagination = build_pagination(array(
415
416
417
418
            'id' => 'admin_usersearch_pagination',
            'class' => 'center',
            'url' => $searchurl,
            'count' => $results['count'],
419
            'setlimit' => true,
420
            'limit' => $limit,
Eugene Venter's avatar
Eugene Venter committed
421
422
            'jumplinks' => 8,
            'numbersincludeprevnext' => 2,
423
424
            'offset' => $offset,
            'datatable' => 'searchresults',
425
            'searchresultsheading' => 'resultsheading',
426
427
428
            'jsonscript' => 'admin/users/search.json.php',
    ));

Naomi Guyer's avatar
Naomi Guyer committed
429
430


431
    $cols = array(
Naomi Guyer's avatar
Naomi Guyer committed
432
433
434
435
436
437
438
        'select' =>  array(
            'mergefirst' => true,
            'headhtml' => '<div class="btn-group" role="group"><a class="btn btn-xs btn-default" href="" id="selectall">' . get_string('All') . '</a>&nbsp;<a class="btn active btn-xs btn-default" href="" id="selectnone">' . get_string('none') . '</a></div>',
            'template' => 'admin/users/searchselectcolumn.tpl',
            'class'    => 'nojs-hidden with-checkbox',
            'accessible' => get_string('bulkselect'),
        ),
439
        'icon' => array(
Naomi Guyer's avatar
Naomi Guyer committed
440
            'mergelast' => true,
441
            'template' => 'admin/users/searchiconcolumn.tpl',
442
            'accessible' => get_string('profileicon'),
443
444
445
446
        ),
        'firstname' => array(
            'name'     => get_string('firstname'),
            'sort'     => true,
447
            'template' => 'admin/users/searchfirstnamecolumn.tpl',
448
449
450
451
        ),
        'lastname' => array(
            'name'     => get_string('lastname'),
            'sort'     => true,
452
            'template' => 'admin/users/searchlastnamecolumn.tpl',
453
        ),
454
455
456
457
        'preferredname' => array(
            'name'     => get_string('displayname'),
            'sort'     => true,
        ),
458
459
460
        'username' => array(
            'name'     => get_string('username'),
            'sort'     => true,
461
            'template' => 'admin/users/searchusernamecolumn.tpl',
462
463
        ),
        'email' => array(
464
            'name'     => get_string('emails'),
465
            'sort'     => true,
466
            'help'     => true,
467
            'class'    => 'form-inline-align-bottom',
468
469
            'helplink' => get_help_icon('core', 'admin', 'usersearch', 'email'),
            'template' => 'admin/users/searchemailcolumn.tpl',
470
        ),
471
    );
472

473
474
    $institutions = get_records_assoc('institution', '', '', '', 'name,displayname');
    if (count($institutions) > 1) {
475
476
        $cols['institution'] = array(
            'name'     => get_string('institution'),
477
            'sort'     => false,
478
            'template' => 'admin/users/searchinstitutioncolumn.tpl',
479
        );
480
481
    }

482
483
484
485
486
    $cols['authname'] = array(
            'name'     => get_string('authentication'),
            'sort'     => true,
    );

487
488
489
490
491
492
    $cols['lastlogin'] = array(
        'name'      => get_string('lastlogin', 'admin'),
        'sort'      => true,
        'template'  => 'strftimedatetime.tpl',
    );

493

494

495
496
    if (!$USER->get('admin') && !$USER->is_institutional_admin()) {
        unset($cols['email']);
497
        if (!get_config('staffreports')) {
498
499
500
501
            $cols['select']['headhtml'] = '';
            $cols['select']['template'] = null;
            $cols['select']['class'] = 'nojs-hidden';
            $cols['select']['accessible'] = '';
502
        }
503
    }
504
    else if (!$USER->get('admin') && $results['data']) {
505
506
507
508
509
510
511
        foreach ($results['data'] as &$r) {
            if (!isset($r['email'])) {
                $r['email'] = '- ' . get_string('emailaddresshidden', 'admin') . ' -';
            }
        }
    }

512
    $smarty = smarty_core();
513
514
    $smarty->assign('results', $results);
    $smarty->assign('institutions', $institutions);
515
    $smarty->assign('USER', $USER);
516
    $smarty->assign('limit', $limit);
517
    $smarty->assign('limitoptions', array(10, 50, 100, 200, 500));
518
519
    $smarty->assign('cols', $cols);
    $smarty->assign('ncols', count($cols));
520
521
522
523
524
525
    $html = $smarty->fetch('searchresulttable.tpl');
    return array($html, $cols, $pagination, array(
        'url' => $searchurl,
        'sortby' => $search->sortby,
        'sortdir' => $search->sortdir
    ));
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
/**
 * Returns the search results for the export queue
 *
 * @param array  $search            The parameters we want to search against
 * @param int    $offset            What result to start showing paginated results from
 * @param int    $limit             How many results to show
 *
 * @return array  A data structure containing results (see top of file).
 */

function build_admin_export_queue_results($search, $offset, $limit) {
    global $USER;

    $wantedparams = array('query', 'sortby', 'sortdir', 'institution');
    $params = array();
    foreach ($search as $k => $v) {
        if (!in_array($k, $wantedparams)) {
            continue;
        }
        if (!empty($v)) {
            $params[] = $k . '=' . $v;
        }
    }
    $searchurl = get_config('wwwroot') . 'admin/users/exportqueue.php?' . join('&', $params) . '&limit=' . $limit;

    // Use get_admin_user_search_results() as it hooks into the same
    // funky stuff the user search box query does on user/search.php page.
    $search->exportqueue = true;
    $results = get_admin_user_search_results($search, $offset, $limit);
    // Now that we have the users we need to match them up with their export_queue data
    if (!empty($results['count'])) {
        foreach ($results['data'] as $key => $data) {
            $used = array();
            $exportdata = get_records_sql_assoc('
                SELECT *, ' . db_format_tsfield('e.starttime', 'started') . ',
                          ' . db_format_tsfield('e.ctime', 'added') . '
                FROM {export_queue} e
                JOIN {export_queue_items} ei
                ON e.id = ei.exportqueueid
                AND e.usr = ?
                AND e.id = ?
                GROUP BY e.id, ei.id
                ORDER BY collection, view', array($data['id'], $data['eid']));
            $exportdataall = false;
            if (empty($exportdata)) {
                // Try checking if it an 'all' export
                $exportdataall = get_record_sql("SELECT *, " . db_format_tsfield('starttime', 'started') . ", " . db_format_tsfield('ctime', 'added') . "
                                                 FROM {export_queue} WHERE id = ? AND type = ?", array($data['eid'], 'all'));
            }
            if (empty($exportdataall) && empty($exportdata)) {
                // we have a problem with this row so will mark as failed
                $results['data'][$key]['status'] = get_string('exportfailed', 'admin', format_date($data['status']));
                $results['data'][$key]['statustype'] = $statustype = 'failed';
                continue;
            }
            // To get the main content title/url/type/id we look at the first row of the exportdata.
            if ($exportdataall) {
                $firstitem = $exportdataall;
                $contentdata = new stdClass();
                $contentdata->title = get_string('allmydata', 'export');
                $contentdata->type = 'all';
                $results['data'][$key]['contentdata'] = $contentdata;
            }
            else {
                $firstitem = reset($exportdata);
                if (!empty($firstitem->type)) {
                    $contentdata = new stdClass();
                    $contentdata->title = get_string('exporting' . $firstitem->type, 'export');
                    $contentdata->type = $firstitem->type;
                    $results['data'][$key]['contentdata'] = $contentdata;
                }
                else {
                    $results['data'][$key]['contentdata'] = get_export_contentdata($firstitem);
                }
            }
            // To get the status we check if the starttime is set
            if (empty($firstitem->starttime)) {
                $status = get_string('exportpending', 'admin', format_date($firstitem->added));
                $statustype = 'pending';
            }
            else if (!empty($firstitem->starttime)) {
                $status = get_string('exportfailed', 'admin', format_date($firstitem->started));
                $statustype = 'failed';
            }
            $results['data'][$key]['status'] = $status;
            $results['data'][$key]['statustype'] = $statustype;

            // Add on the raw exportdata allowing us to show the titles of all pages / artefacts
            // @todo allow all the titles to be displayed in an expanding box/area
            $results['data'][$key]['exportdata'] = $exportdata;
        }
    }

    $pagination = build_pagination(array(
            'id' => 'admin_exportqueue_pagination',
            'class' => 'center',
            'url' => $searchurl,
            'count' => $results['count'],
            'setlimit' => true,
            'limit' => $limit,
            'jumplinks' => 8,
            'numbersincludeprevnext' => 2,
            'offset' => $offset,
            'datatable' => 'searchresults',
            'searchresultsheading' => 'resultsheading',
            'jsonscript' => 'admin/users/exportqueue.json.php',
    ));

    $cols = array(
        'icon' => array(
            'template' => 'admin/users/searchiconcolumn.tpl',
            'class'    => 'center',
            'accessible' => get_string('profileicon'),
        ),
        'firstname' => array(
            'name'     => get_string('firstname'),
            'sort'     => true,
            'template' => 'admin/users/searchfirstnamecolumn.tpl',
        ),
        'lastname' => array(
            'name'     => get_string('lastname'),
            'sort'     => true,
            'template' => 'admin/users/searchlastnamecolumn.tpl',
        ),
        'preferredname' => array(
            'name'     => get_string('displayname'),
            'sort'     => true,
        ),
        'username' => array(
            'name'     => get_string('username'),
            'sort'     => true,
            'template' => 'admin/users/searchusernamecolumn.tpl',
        ),
        'contentname' => array(
            'name'     => get_string('exportcontentname', 'admin'),
            'sort'     => false,
            'template' => 'admin/users/searchexportcontentcolumn.tpl',
        ),
        'status' => array(
            'name'     => get_string('status'),
            'sort'     => true,
            'template' => 'admin/users/searchexportstatuscolumn.tpl',
        ),
        'exportselect' => array(
672
            'headhtml' => get_string('requeue', 'export') . '<br><div class="btn-group" role="group"><a class="btn btn-xs btn-default" href="" id="selectallexport">' . get_string('All') . '</a>&nbsp;<a class="btn btn-xs btn-default" href="" id="selectnoneexport">' . get_string('none') . '</a></div>',
673
            'template' => 'admin/users/searchselectcolumnexport.tpl',
674
            'class'    => 'nojs-hidden-table-cell with-checkbox',
675
676
677
            'accessible' => get_string('bulkselect'),
        ),
        'deleteselect' => array(
678
            'headhtml' => get_string('delete') . '<br><div class="btn-group" role="group"><a class="btn btn-xs btn-default" href="" id="selectalldelete">' . get_string('All') . '</a>&nbsp;<a class="btn btn-xs btn-default" href="" id="selectnonedelete">' . get_string('none') . '</a></div>',
679
            'template' => 'admin/users/searchselectcolumnexportdelete.tpl',
680
            'class'    => 'nojs-hidden-table-cell with-checkbox',
681
682
683
684
685
            'accessible' => get_string('bulkselect'),
        ),
    );

    $smarty = smarty_core();
686
    $smarty->assign('results', $results);
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
    $smarty->assign('USER', $USER);
    $smarty->assign('limit', $limit);
    $smarty->assign('limitoptions', array(10, 50, 100, 200, 500));
    $smarty->assign('cols', $cols);
    $smarty->assign('ncols', count($cols));
    $html = $smarty->fetch('searchresulttable.tpl');
    if ($html != '') {
        $html .= $smarty->fetch('searchresulttablebuttons.tpl');
    }

    return array($html, $cols, $pagination, array(
        'url' => $searchurl,
        'sortby' => $search->sortby,
        'sortdir' => $search->sortdir
    ));
}

/**
 * Returns the search results for the archived submissions
 *
 * @param array  $search            The parameters we want to search against
 * @param int    $offset            What result to start showing paginated results from
 * @param int    $limit             How many results to show
 *
 * @return array  A data structure containing results (see top of file).
 */

function build_admin_archived_submissions_results($search, $offset, $limit) {
    global $USER;

    $wantedparams = array('query', 'sortby', 'sortdir', 'institution');
    $params = array();
    foreach ($search as $k => $v) {
        if (!in_array($k, $wantedparams)) {
            continue;
        }
        if (!empty($v)) {
            $params[] = $k . '=' . $v;
        }
    }
    $searchurl = get_config('wwwroot') . 'admin/groups/archives.php?' . join('&', $params) . '&limit=' . $limit;

    // Use get_admin_user_search_results() as it hooks into the same
    // funky stuff the user search box query does on user/search.php page.
    $search->archivedsubmissions = true;

    $results = get_admin_user_search_results($search, $offset, $limit);
    // Now that we have the users we need to do some last minute alterations
    if (!empty($results['count'])) {
        foreach ($results['data'] as $key => $data) {
            // alter the archivectime to be human readable
            $results['data'][$key]['archivectime'] = format_date($data['archivectime']);
            // make sure the archive file is still on server at the path 'filepath' (not moved or deleted by server admin)
            $results['data'][$key]['filemissing'] = (!file_exists($data['filepath'] . $data['filename'])) ? true : false;
            // make the deleted group name more human readable
            $results['data'][$key]['groupdeleted'] = false;
            if (preg_match('/^(.*?)(\.deleted\.)(.*)$/', $data['submittedto'], $matches)) {
                $results['data'][$key]['groupdeleted'] = true;
                $results['data'][$key]['submittedto'] = $matches[1] . ' (' . get_string('deleted') . ' ' . format_date($matches[3]) . ')';
            }
        }
    }

    $pagination = build_pagination(array(
            'id' => 'admin_exportqueue_pagination',
            'class' => 'center',
            'url' => $searchurl,
            'count' => $results['count'],
            'setlimit' => true,
            'limit' => $limit,
            'jumplinks' => 8,
            'numbersincludeprevnext' => 2,
            'offset' => $offset,
            'datatable' => 'searchresults',
            'searchresultsheading' => 'resultsheading',
            'jsonscript' => 'admin/groups/archives.json.php',
    ));

    $cols = array(
        'submittedto' => array(
            'name'     => get_string('submittedto', 'admin'),
            'sort'     => true,
            'template' => 'admin/groups/submittedtocontentcolumn.tpl',
        ),
        'specialid' => array(
            'name'     => get_string('ID', 'admin'),
            'sort'     => true,
        ),
        'icon' => array(
            'template' => 'admin/users/searchiconcolumn.tpl',
            'class'    => 'center',
            'accessible' => get_string('profileicon'),
        ),
        'firstname' => array(
            'name'     => get_string('firstname'),
            'sort'     => true,
            'template' => 'admin/users/searchfirstnamecolumn.tpl',
        ),
        'lastname' => array(
            'name'     => get_string('lastname'),
            'sort'     => true,
            'template' => 'admin/users/searchlastnamecolumn.tpl',
        ),
        'preferredname' => array(
            'name'     => get_string('displayname'),
            'sort'     => true,
        ),
        'username' => array(
            'name'     => get_string('username'),
            'sort'     => true,
            'template' => 'admin/users/searchusernamecolumn.tpl',
        ),
        'filetitle' => array(
            'name'     => get_string('filenameleap', 'admin'),
            'sort'     => true,
            'template' => 'admin/groups/leap2acontentcolumn.tpl',
        ),
        'archivectime' => array(
            'name'     => get_string('archivedon', 'admin'),
            'sort'     => true,
        ),
    );

    $smarty = smarty_core();
811
    $smarty->assign('results', $results);
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
    $smarty->assign('USER', $USER);
    $smarty->assign('limit', $limit);
    $smarty->assign('limitoptions', array(10, 50, 100, 200, 500));
    $smarty->assign('cols', $cols);
    $smarty->assign('ncols', count($cols));
    $html = $smarty->fetch('searchresulttable.tpl');

    return array($html, $cols, $pagination, array(
        'url' => $searchurl,
        'sortby' => $search->sortby,
        'sortdir' => $search->sortdir
    ));
}

/**
 * Return the title, type and id of the item based on which is more important
 *
 * Takes an array containing ids on either or all of these items with ranking
 * preference in this order:
 * - collection
 * - view
 * and returns the title, type, and id of which ever one is present and is highest ranked
 *
 * @param array  $item An array containing any or all of 'collection', 'view' ids
 * @return array The title/url/type/id information on the most senior one found.
 */
function get_export_contentdata($item) {
    // first make sure we have an array
    if (is_object($item)) {
        $item = (array)$item;
    }

    $record = new stdClass();
    $record->title = '';
    $record->url = null;
    $record->type = null;
    $record->id = 0;
    if (!empty($item['collection'])) {
        require_once('collection.php');
        $collection = new Collection($item['collection']);
        $views = $collection->get('views');
        $record->title = $collection->get('name');
        $record->url = $views['views'][0]->fullurl;
        $record->type = 'collection';
        $record->id = $item['collection'];
    }
    else if (!empty($item['view'])) {
        require_once('view.php');
        $view = new View($item['view']);
        $record->title = $view->get('title');
        $record->url = get_config('wwwroot') . 'view/view.php?id=' . $item['view'];
        $record->type = 'view';
        $record->id = $item['view'];
    }
    return $record;
}
868

869
870
871
872
873
/**
 * Returns search results for users in a particular group
 *
 * The search term is applied against first and last names of the users in the group
 *
874
875
876
877
878
879
 * @param int    $group             The group to build results for
 * @param string $query             A search string to filter by
 * @param int    $offset            What result to start showing paginated results from
 * @param int    $limit             How many results to show
 * @param array  $membershiptype    User membershiptype
 * @param bool   $random            Set to true if you want the result to be ordered by random, default false
880
 * @param int    $friendof          Only return friends of this user
881
 *
882
 */
883
function get_group_user_search_results($group, $query, $offset, $limit, $membershiptype, $order=null, $friendof=null, $sortoptionidx=null) {
884
885
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);
886
    $searchclass = generate_class_name('search', $plugin);
887

888
    $constraints = array();
889
    if (call_static_method($searchclass, 'can_process_raw_group_search_user_queries')) {
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
        // Pass the raw query string through to group_search_user; parsing of the
        // query depends on the plugin configuration.
        $queries = $query;
    }
    else {
        $queries = array();
        if (!empty($query)) {
            list($words, $fullnames) = parse_name_query($query);
            foreach ($words as $word) {
                $queries[] = array(
                    'field'  => 'firstname',
                    'type'   => 'contains',
                    'string' => $word
                );
                $queries[] = array(
                    'field'  => 'lastname',
                    'type'   => 'contains',
                    'string' => $word
                );
            }
            foreach ($fullnames as $n) {
                $constraints[] = array(
                    'field'  => 'firstname',
                    'type'   => 'contains',
                    'string' => $n[0]
                );
                $constraints[] = array(
                    'field'  => 'lastname',
                    'type'   => 'contains',
                    'string' => $n[1]
                );
            }
922
923
924
        }
    }

925
    $results = call_static_method(
926
927
        $searchclass,
        'group_search_user',
928
        $group, $queries, $constraints, $offset, $limit, $membershiptype, $order, $friendof, $sortoptionidx
929
930
    );

931
932
    if ($results['count']) {
        $userids = array_map(create_function('$a', 'return $a["id"];'), $results['data']);
933
        $introductions = get_records_sql_assoc("SELECT \"owner\", description
934
935
            FROM {artefact}
            WHERE artefacttype = 'introduction'
Francois Marier's avatar
Francois Marier committed
936
            AND \"owner\" IN (" . implode(',', db_array_to_ph($userids)) . ')',
937
938
939
            $userids);
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
940
            $result['introduction'] = isset($introductions[$result['id']]) ? $introductions[$result['id']]->description : '';
941
            if (isset($result['jointime'])) {
942
                $result['jointime'] = format_date($result['jointime'], 'strftimedate');
943
            }
944
945
946
947
948
949
        }
    }
    return $results;
}


950
951
952
953
954
955
956
/**
 * Given a query string and limits, return an array of matching groups using the
 * search plugin defined in config.php
 *
 * @param string  The query string
 * @param integer How many results to return
 * @param integer What result to start at (0 == first result)
957
958
 * @param string  Category the group belongs to
 * @param string  The institution the group belongs
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
 * @return array  A data structure containing results looking like ...
 *         $results = array(
 *               count   => integer, // total number of results
 *               limit   => integer, // how many results are returned
 *               offset  => integer, // starting from which result
 *               results => array(   // the result records
 *                   array(
 *                       id            => integer,
 *                       name          => string,
 *                       owner         => integer,
 *                       description   => string,
 *                       ctime         => string,
 *                       mtime         => string,
 *                   ),
 *                   array(
 *                       id            => integer,
 *                       name          => string,
 *                       owner         => integer,
 *                       description   => string,
 *                       ctime         => string,
 *                       mtime         => string,
 *                   ),
 *                   array(...),
 *               ),
 *           );
 */
985
function search_group($query_string, $limit, $offset = 0, $type = 'member', $groupcategory = '', $institution='all') {
986
987
988
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);

989
    return call_static_method(generate_class_name('search', $plugin), 'search_group', $query_string, $limit, $offset, $type, $groupcategory, $institution);
Nigel McNie's avatar
Nigel McNie committed
990
}
991
992
993
994
995
996
997

function search_selfsearch($query_string, $limit, $offset, $type = 'all') {
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);

    return call_static_method(generate_class_name('search', $plugin), 'self_search', $query_string, $limit, $offset, $type);
}
998

999
1000
1001
1002
1003
function get_portfolio_types_from_param($filter) {
    if (is_null($filter) || $filter == 'all') {
        return null;
    }
    if ($filter == 'view') {
1004
1005
1006
1007
        return array('view' => true, 'collection' => false, 'artefact' => false);
    }
    if ($filter == 'collection') {
        return array('view' => false, 'collection' => true, 'artefact' => false);
1008
1009
    }
    require_once(get_config('docroot') . 'artefact/lib.php');
1010
    return array('view' => false, 'collection' => false, 'artefact' => artefact_get_types_from_filter($filter));
1011
1012
1013
}

function get_portfolio_items_by_tag($tag, $owner, $limit, $offset, $sort='name', $type=null, $returntags=true) {
1014
1015
1016
1017
1018
1019
1020
1021
    // For now, can only be used to search a user's portfolio
    if (empty($owner->id) || empty($owner->type)) {
        throw new SystemException('get_views_and_artefacts_by_tag: invalid owner');
    }
    if ($owner->type != 'user') {
        throw new SystemException('get_views_and_artefacts_by_tag only implemented for users');
    }

1022
1023
    $types = get_portfolio_types_from_param($type);

1024
1025
1026
    $plugin = 'internal';
    safe_require('search', $plugin);

1027
1028
1029
    $result = call_static_method(generate_class_name('search', $plugin), 'portfolio_search_by_tag', $tag, $owner, $limit, $offset, $sort, $types, $returntags);
    $result->filter = $result->type = $type ? $type : 'all';
    return $result;
1030
1031
}

1032
1033
1034
function get_search_plugins() {
    $searchpluginoptions = array();

1035
    if ($searchplugins = plugins_installed('search')) {
1036
        foreach ($searchplugins as $plugin) {
1037
1038
1039
1040
1041
            safe_require_plugin('search', $plugin->name, 'lib.php');
            if (!call_static_method(generate_class_name('search', $plugin->name), 'is_available_for_site_setting')) {
                continue;
            }

1042
1043
1044
1045
            $searchpluginoptions[$plugin->name] = $plugin->name;

            $config_path = get_config('docroot') . 'search/' . $plugin->name . '/version.php';
            if (is_readable($config_path)) {
1046
                $config = new stdClass();
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
                require_once($config_path);
                if (isset($config->name)) {
                    $searchpluginoptions[$plugin->name] = $config->name;
                }
            }
        }
    }

    return $searchpluginoptions;
}
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081

/**
 * Given a filter string and limits, return an array of matching friends.
 *
 * @param string  The filter string
 * @param integer How many results to return
 * @param integer What result to start at (0 == first result)
 * @return array  A data structure containing results looking like ...
 *         $results = array(
 *               count   => integer, // total number of results
 *               limit   => integer, // how many results are returned
 *               offset  => integer, // starting from which result
 *               results => array(   // the result records
 *                   array(
 *                       id            => integer, //user id
 *                   ),
 *                   array(...),
 *               ),
 *           );
 */
function search_friend($filter, $limit, $offset) {
    global $USER;
    $userid = $USER->get('id');

    if (!in_array($filter, array('all','current','pending'))) {
1082
        throw new SystemException('Invalid search filter');
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
    }

    $sql = array();
    $count = 0;

    if (in_array($filter, array('all', 'current'))) {
        $count += count_records_sql('SELECT COUNT(usr1) FROM {usr_friend}
            JOIN {usr} u1 ON (u1.id = usr1 AND u1.deleted = 0)
            JOIN {usr} u2 ON (u2.id = usr2 AND u2.deleted = 0)
            WHERE usr1 = ? OR usr2 = ?',
            array($userid, $userid)
        );

        array_push($sql, 'SELECT usr2 AS id, 2 AS status FROM {usr_friend} WHERE usr1 = ?
        ');
        array_push($sql, 'SELECT usr1 AS id, 2 AS status FROM {usr_friend} WHERE usr2 = ?
        ');
    }

    if (in_array($filter, array('all', 'pending'))) {
Francois Marier's avatar
Francois Marier committed
1103
        $count += count_records_sql('SELECT COUNT("owner") FROM {usr_friend_request}
1104
            JOIN {usr} u ON (u.id = requester AND u.deleted = 0)
Francois Marier's avatar
Francois Marier committed
1105
            WHERE "owner" = ?',
1106
1107
1108
            array($userid)
        );

Francois Marier's avatar
Francois Marier committed
1109
        array_push($sql, 'SELECT requester AS id, 1 AS status FROM {usr_friend_request} WHERE "owner" = ?
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
        ');
    }

    $data = get_column_sql('SELECT f.id FROM (' . join('UNION ', $sql) . ') f
        JOIN {usr} u ON (f.id = u.id AND u.deleted = 0)
        ORDER BY status, firstname, lastname, u.id
        LIMIT ?
        OFFSET ?', array_merge(array_pad($values=array(), count($sql), $userid), array($limit, $offset)));

    foreach ($data as &$result) {
        $result = array('id' => $result);
    }

    return array(
    'count'   => $count,
    'limit'   => $limit,
    'offset'  => $offset,
    'data'    => $data,
    );
}