searchlib.php 22.5 KB
Newer Older
Martyn Smith's avatar
Martyn Smith committed
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
5
 * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
Martyn Smith's avatar
Martyn Smith committed
6
 *
Francois Marier's avatar
Francois Marier committed
7
8
9
10
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
Martyn Smith's avatar
Martyn Smith committed
11
 *
Francois Marier's avatar
Francois Marier committed
12
13
14
15
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
Martyn Smith's avatar
Martyn Smith committed
16
 *
Francois Marier's avatar
Francois Marier committed
17
18
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
Martyn Smith's avatar
Martyn Smith committed
19
20
21
 *
 * @package    mahara
 * @subpackage core
22
 * @author     Catalyst IT Ltd
Martyn Smith's avatar
Martyn Smith committed
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
Martyn Smith's avatar
Martyn Smith committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 * @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(
44
45
46
47
48
49
50
 *                       id            => integer,
 *                       username      => string,
 *                       institution   => string,
 *                       firstname     => string,
 *                       lastname      => string,
 *                       preferredname => string,
 *                       email         => string,
Martyn Smith's avatar
Martyn Smith committed
51
52
 *                   ),
 *                   array(
53
54
55
56
57
58
59
 *                       id            => integer,
 *                       username      => string,
 *                       institution   => string,
 *                       firstname     => string,
 *                       lastname      => string,
 *                       preferredname => string,
 *                       email         => string,
Martyn Smith's avatar
Martyn Smith committed
60
61
62
63
64
 *                   ),
 *                   array(...),
 *               ),
 *           );
 */
65
function search_user($query_string, $limit, $offset = 0, $data = array()) {
Martyn Smith's avatar
Martyn Smith committed
66
    $plugin = get_config('searchplugin');
67
    safe_require('search', $plugin);
68
    $results = call_static_method(generate_class_name('search', $plugin), 'search_user', $query_string, $limit, $offset, $data);
69

70
    if ($results['data']) {
71
72
73
74
75
76
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
        }
    }

    return $results;
77
78
}

79

80
81
82
83
84
85
86
87
88
89
90
91
92

/* 
 * 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;
93
    foreach (array('member', 'requested', 'invitedby', 'lastinstitution') as $p) {
94
95
96
97
        $institution->{$p} = $search->{$p};
    }
    $results = institutional_admin_user_search($search->query, $institution, $limit);
    if ($results['count']) {
98
99
100
101
        foreach ($results['data'] as &$r) {
            $r['name'] = $r['firstname'] . ' ' . $r['lastname'] . ' (' . $r['username'] . ')';
            if (!empty($r['studentid'])) {
                $r['name'] .= ' (' . $r['studentid'] . ')';
102
            }
103
104
105
106
107
108
109
110
111
112
113
114
115
        }
    }
    return $results;
}

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


116
117
118
119
120
/**
 * 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.
 */
121

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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)));
      $phraselist = split(' ', $phrase);
      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);

}
151

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

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

    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
                    );
193
194
195
196
197
                    $queries[] = array(
                        'field' => 'preferredname',
                        'type' => 'contains',
                        'string' => $word
                    );
198
199
200
201
202
203
204
205
206
207
208
209
210
                }
            }
            foreach ($fullnames as $n) {
                $constraints[] = array(
                    'field' => 'firstname',
                    'type' => 'contains',
                    'string' => $n[0]
                );
                $constraints[] = array(
                    'field' => 'lastname',
                    'type' => 'contains',
                    'string' => $n[1]
                );
211
            }
212
213
        }
    }
214

Richard Mansfield's avatar
Richard Mansfield committed
215
216
217
218
219
220
221
222
223
224
    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);
    }
225

226
227
    // Filter by viewable institutions:
    global $USER;
228
229
    if (!$USER->get('admin') && !$USER->get('staff')) {
        $allowed = array_merge($USER->get('admininstitutions'), $USER->get('staffinstitutions'));
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
        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,
            );
246
        }
247
    } else if (!empty($search->institution) && $search->institution != 'all') {
Richard Mansfield's avatar
Richard Mansfield committed
248
249
250
        $constraints[] = array('field' => 'institution',
                               'type' => 'equals',
                               'string' => $search->institution);
251
    }
252
    
253
254
    $results = call_static_method(
        generate_class_name('search', $plugin), 'admin_search_user',
255
        $queries, $constraints, $offset, $limit, $search->sortby, $search->sortdir
256
257
    );

258
    if ($results['count']) {
259
260
261
        $isadmin = $USER->get('admin');
        $admininstitutions = $USER->get('admininstitutions');

262
263
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
264
265
266
            if (!empty($result['institutions'])) {
                $result['institutions'] = array_combine($result['institutions'],$result['institutions']);
            }
267
268
269
270
271
272
273
274
275
276
277
278
            if ($isadmin) {
                continue;
            }

            // Remove email address when viewed by staff
            if (!$hideemail = (empty($admininstitutions) || empty($result['institutions']))) {
                $commoninstitutions = array_intersect($admininstitutions, $result['institutions']);
                $hideemail |= empty($commoninstitutions);
            }
            if ($hideemail) {
                unset($result['email']);
            }
279
        }
280
    }
281

282
    return $results;
283
284
285
}


286
function build_admin_user_search_results($search, $offset, $limit) {
287
    global $USER, $THEME;
288

289
290
291
292
293
294
    $params = array();
    foreach ($search as $k => $v) {
        if (!empty($v)) {
            $params[] = $k . '=' . $v;
        }
    }
295
    $searchurl = get_config('wwwroot') . 'admin/users/search.php?' . join('&', $params) . '&limit=' . $limit;
296

297
298
299
300
301
302
303
304
    $results = get_admin_user_search_results($search, $offset, $limit);

    $results['pagination'] = build_pagination(array(
            'id' => 'admin_usersearch_pagination',
            'class' => 'center',
            'url' => $searchurl,
            'count' => $results['count'],
            'limit' => $limit,
Eugene Venter's avatar
Eugene Venter committed
305
306
            'jumplinks' => 8,
            'numbersincludeprevnext' => 2,
307
308
309
310
311
            'offset' => $offset,
            'datatable' => 'searchresults',
            'jsonscript' => 'admin/users/search.json.php',
    ));

312
    $cols = array(
313
        'icon' => array(
314
            'template' => 'admin/users/searchiconcolumn.tpl',
315
316
317
318
319
320
321
322
323
324
            'class'    => 'center',
        ),
        'firstname' => array(
            'name'     => get_string('firstname'),
            'sort'     => true,
        ),
        'lastname' => array(
            'name'     => get_string('lastname'),
            'sort'     => true,
        ),
325
326
327
328
        'preferredname' => array(
            'name'     => get_string('displayname'),
            'sort'     => true,
        ),
329
330
331
        'username' => array(
            'name'     => get_string('username'),
            'sort'     => true,
332
            'template' => 'admin/users/searchusernamecolumn.tpl',
333
334
335
336
337
        ),
        'email' => array(
            'name'     => get_string('email'),
            'sort'     => true,
        ),
338
    );
339

340
341
    $institutions = get_records_assoc('institution', '', '', '', 'name,displayname');
    if (count($institutions) > 1) {
342
343
        $cols['institution'] = array(
            'name'     => get_string('institution'),
344
            'sort'     => false,
345
            'template' => 'admin/users/searchinstitutioncolumn.tpl',
346
        );
347
348
    }

349
350
351
352
353
354
    $cols['select'] = array(
        'headhtml' => '<a href="" id="selectall">' . get_string('All') . '</a>&nbsp;<a href="" id="selectnone">' . get_string('none') . '</a>',
        'template' => 'admin/users/searchselectcolumn.tpl',
        'class'    => 'center nojs-hidden-table-cell',
    );

355
356
    if (!$USER->get('admin') && !$USER->is_institutional_admin()) {
        unset($cols['email']);
357
358
359
        if (!get_config('staffreports')) {
            unset($cols['select']);
        }
360
    }
361
    else if (!$USER->get('admin') && $results['data']) {
362
363
364
365
366
367
368
        foreach ($results['data'] as &$r) {
            if (!isset($r['email'])) {
                $r['email'] = '- ' . get_string('emailaddresshidden', 'admin') . ' -';
            }
        }
    }

369
    $smarty = smarty_core();
370
    $smarty->assign_by_ref('results', $results);
371
    $smarty->assign_by_ref('institutions', $institutions);
372
    $smarty->assign('USER', $USER);
373
    $smarty->assign('searchurl', $searchurl);
374
375
    $smarty->assign('sortby', $search->sortby);
    $smarty->assign('sortdir', $search->sortdir);
376
    $smarty->assign('limitoptions', array(10, 50, 100, 200, 500));
377
378
379
    $smarty->assign('cols', $cols);
    $smarty->assign('ncols', count($cols));
    return $smarty->fetch('searchresulttable.tpl');
380
381
382
}


383
384
385
386
387
/**
 * 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
 *
388
389
390
391
392
393
 * @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
394
 * @param int    $friendof          Only return friends of this user
395
 *
396
 */
397
function get_group_user_search_results($group, $query, $offset, $limit, $membershiptype, $order=null, $friendof=null) {
398
399
400
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);

401
    $constraints = array();
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
    if ($plugin == 'internal') {
        // 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]
                );
            }
435
436
437
        }
    }

438
439
    $results = call_static_method(
        generate_class_name('search', $plugin), 'group_search_user',
440
        $group, $queries, $constraints, $offset, $limit, $membershiptype, $order, $friendof
441
442
    );

443
444
    if ($results['count']) {
        $userids = array_map(create_function('$a', 'return $a["id"];'), $results['data']);
Francois Marier's avatar
Francois Marier committed
445
        $introductions = get_records_sql_assoc("SELECT \"owner\", title
446
447
            FROM {artefact}
            WHERE artefacttype = 'introduction'
Francois Marier's avatar
Francois Marier committed
448
            AND \"owner\" IN (" . implode(',', db_array_to_ph($userids)) . ')',
449
450
451
452
            $userids);
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
            $result['introduction'] = isset($introductions[$result['id']]) ? $introductions[$result['id']]->title : '';
453
454
455
            if (isset($result['jointime'])) {
                $result['jointime'] = strftime(get_string('strftimedate'), $result['jointime']);
            }
456
457
458
459
460
461
        }
    }
    return $results;
}


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
/**
 * 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)
 * @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(...),
 *               ),
 *           );
 */
495
function search_group($query_string, $limit, $offset = 0, $type = 'member', $groupcategory = '') {
496
497
498
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);

499
    return call_static_method(generate_class_name('search', $plugin), 'search_group', $query_string, $limit, $offset, $type, $groupcategory);
Nigel McNie's avatar
Nigel McNie committed
500
}
501
502
503
504
505
506
507

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);
}
508

509
510
511
512
513
514
515
516
517
518
519
520
function get_portfolio_types_from_param($filter) {
    if (is_null($filter) || $filter == 'all') {
        return null;
    }
    if ($filter == 'view') {
        return array('view' => true, 'artefact' => false);
    }
    require_once(get_config('docroot') . 'artefact/lib.php');
    return array('view' => false, 'artefact' => artefact_get_types_from_filter($filter));
}

function get_portfolio_items_by_tag($tag, $owner, $limit, $offset, $sort='name', $type=null, $returntags=true) {
521
522
523
524
525
526
527
528
    // 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');
    }

529
530
    $types = get_portfolio_types_from_param($type);

531
532
533
    $plugin = 'internal';
    safe_require('search', $plugin);

534
535
536
    $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;
537
538
}

539
540
541
function get_search_plugins() {
    $searchpluginoptions = array();

542
    if ($searchplugins = plugins_installed('search')) {
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
        foreach ($searchplugins as $plugin) {
            $searchpluginoptions[$plugin->name] = $plugin->name;

            $config_path = get_config('docroot') . 'search/' . $plugin->name . '/version.php';
            if (is_readable($config_path)) {
                $config = new StdClass;
                require_once($config_path);
                if (isset($config->name)) {
                    $searchpluginoptions[$plugin->name] = $config->name;
                }
            }
        }
    }

    return $searchpluginoptions;
}
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

/**
 * 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'))) {
584
        throw new SystemException('Invalid search filter');
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
    }

    $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
605
        $count += count_records_sql('SELECT COUNT("owner") FROM {usr_friend_request}
606
            JOIN {usr} u ON (u.id = requester AND u.deleted = 0)
Francois Marier's avatar
Francois Marier committed
607
            WHERE "owner" = ?',
608
609
610
            array($userid)
        );

Francois Marier's avatar
Francois Marier committed
611
        array_push($sql, 'SELECT requester AS id, 1 AS status FROM {usr_friend_request} WHERE "owner" = ?
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
        ');
    }

    $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,
    );
}