searchlib.php 20.9 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
193
194
195
196
197
198
199
200
201
202
203
204
205

    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
                    );
                }
            }
            foreach ($fullnames as $n) {
                $constraints[] = array(
                    'field' => 'firstname',
                    'type' => 'contains',
                    'string' => $n[0]
                );
                $constraints[] = array(
                    'field' => 'lastname',
                    'type' => 'contains',
                    'string' => $n[1]
                );
206
            }
207
208
        }
    }
209

Richard Mansfield's avatar
Richard Mansfield committed
210
211
212
213
214
215
216
217
218
219
    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);
    }
220

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

253
254
255
    if ($results['count']) {
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
256
257
258
            if (!empty($result['institutions'])) {
                $result['institutions'] = array_combine($result['institutions'],$result['institutions']);
            }
259
        }
260
    }
261

262
    return $results;
263
264
265
}


266
function build_admin_user_search_results($search, $offset, $limit) {
267
    global $USER, $THEME;
268

269
270
271
272
273
274
    $params = array();
    foreach ($search as $k => $v) {
        if (!empty($v)) {
            $params[] = $k . '=' . $v;
        }
    }
275
    $searchurl = get_config('wwwroot') . 'admin/users/search.php?' . join('&', $params) . '&limit=' . $limit;
276

277
278
279
280
281
282
283
284
285
286
287
288
289
    $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,
            'offset' => $offset,
            'datatable' => 'searchresults',
            'jsonscript' => 'admin/users/search.json.php',
    ));

290
    $cols = array(
291
        'icon' => array(
292
            'template' => 'admin/users/searchiconcolumn.tpl',
293
294
295
296
297
298
299
300
301
302
303
304
305
            'class'    => 'center',
        ),
        'firstname' => array(
            'name'     => get_string('firstname'),
            'sort'     => true,
        ),
        'lastname' => array(
            'name'     => get_string('lastname'),
            'sort'     => true,
        ),
        'username' => array(
            'name'     => get_string('username'),
            'sort'     => true,
306
            'template' => 'admin/users/searchusernamecolumn.tpl',
307
308
309
310
311
        ),
        'email' => array(
            'name'     => get_string('email'),
            'sort'     => true,
        ),
312
    );
313

314
315
    $institutions = get_records_assoc('institution', '', '', '', 'name,displayname');
    if (count($institutions) > 1) {
316
317
        $cols['institution'] = array(
            'name'     => get_string('institution'),
318
            'sort'     => false,
319
            'template' => 'admin/users/searchinstitutioncolumn.tpl',
320
        );
321
322
    }

323
324
325
326
327
328
    $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',
    );

329
    $smarty = smarty_core();
330
    $smarty->assign_by_ref('results', $results);
331
    $smarty->assign_by_ref('institutions', $institutions);
332
    $smarty->assign('USER', $USER);
333
    $smarty->assign('searchurl', $searchurl);
334
335
    $smarty->assign('sortby', $search->sortby);
    $smarty->assign('sortdir', $search->sortdir);
336
    $smarty->assign('limitoptions', array(10, 50, 100, 200, 500));
337
338
339
    $smarty->assign('cols', $cols);
    $smarty->assign('ncols', count($cols));
    return $smarty->fetch('searchresulttable.tpl');
340
341
342
}


343
344
345
346
347
/**
 * 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
 *
348
349
350
351
352
353
 * @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
354
 *
355
 */
356
function get_group_user_search_results($group, $query, $offset, $limit, $membershiptype, $order=null) {
357
358
359
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);

360
    $constraints = array();
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
    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]
                );
            }
394
395
396
        }
    }

397
398
399
400
401
    $results = call_static_method(
        generate_class_name('search', $plugin), 'group_search_user',
        $group, $queries, $constraints, $offset, $limit, $membershiptype, $order
    );

402
403
    if ($results['count']) {
        $userids = array_map(create_function('$a', 'return $a["id"];'), $results['data']);
Francois Marier's avatar
Francois Marier committed
404
        $introductions = get_records_sql_assoc("SELECT \"owner\", title
405
406
            FROM {artefact}
            WHERE artefacttype = 'introduction'
Francois Marier's avatar
Francois Marier committed
407
            AND \"owner\" IN (" . implode(',', db_array_to_ph($userids)) . ')',
408
409
410
411
            $userids);
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
            $result['introduction'] = isset($introductions[$result['id']]) ? $introductions[$result['id']]->title : '';
412
413
414
            if (isset($result['jointime'])) {
                $result['jointime'] = strftime(get_string('strftimedate'), $result['jointime']);
            }
415
416
417
418
419
420
        }
    }
    return $results;
}


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
/**
 * 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(...),
 *               ),
 *           );
 */
454
function search_group($query_string, $limit, $offset = 0, $type = 'member', $groupcategory = '') {
455
456
457
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);

458
    return call_static_method(generate_class_name('search', $plugin), 'search_group', $query_string, $limit, $offset, $type, $groupcategory);
Nigel McNie's avatar
Nigel McNie committed
459
}
460
461
462
463
464
465
466

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

468
469
470
471
472
473
474
475
476
477
478
479
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) {
480
481
482
483
484
485
486
487
    // 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');
    }

488
489
    $types = get_portfolio_types_from_param($type);

490
491
492
    $plugin = 'internal';
    safe_require('search', $plugin);

493
494
495
    $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;
496
497
}

498
499
500
function get_search_plugins() {
    $searchpluginoptions = array();

501
    if ($searchplugins = plugins_installed('search')) {
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
        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;
}
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

/**
 * 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'))) {
543
        throw new SystemException('Invalid search filter');
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
    }

    $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
564
        $count += count_records_sql('SELECT COUNT("owner") FROM {usr_friend_request}
565
            JOIN {usr} u ON (u.id = requester AND u.deleted = 0)
Francois Marier's avatar
Francois Marier committed
566
            WHERE "owner" = ?',
567
568
569
            array($userid)
        );

Francois Marier's avatar
Francois Marier committed
570
        array_push($sql, 'SELECT requester AS id, 1 AS status FROM {usr_friend_request} WHERE "owner" = ?
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
        ');
    }

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