searchlib.php 22.2 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
    safe_require('artefact', 'internal');
Martyn Smith's avatar
Martyn Smith committed
69

70
71
72
73
74
75
    $publicfields = array_keys(ArtefactTypeProfile::get_public_fields());
    if (empty($publicfields)) {
        $publicfields = array('preferredname');
    }
    $fieldlist = "('" . join("','", $publicfields) . "')";

76
    $results = call_static_method(generate_class_name('search', $plugin), 'search_user', $query_string, $limit, $offset, $data);
77

78
    if ($results['data']) {
Francois Marier's avatar
Francois Marier committed
79
        $userlist = '('.join(',', array_map(create_function('$u','return (int)$u[\'id\'];'), $results['data'])).')';
80
81
82
83
84

        $public_fields = get_records_sql_array('
            SELECT 
                u.id, a.artefacttype, a.title
            FROM
85
86
                {usr} u
                LEFT JOIN {artefact} a ON u.id=a.owner AND a.artefacttype IN ' . $fieldlist . '
87
88
89
90
91
92
93
94
95
            WHERE
                u.id IN ' . $userlist . '
            ORDER BY u.firstname, u.lastname, u.id, a.artefacttype',
            array()
        );

        $public_fields_byuser = array();
        if (!empty($public_fields)) {
            foreach ($public_fields as $field) {
96
97
98
99
                // This will be null if the user does not have a field marked public
                if ($field->artefacttype !== null) {
                    $public_fields_byuser[$field->id][$field->artefacttype] = $field->title;
                }
100
101
102
103
104
105
106
107
108
109
            }
        }
        
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
            if (isset($public_fields_byuser[$result['id']])) {
                foreach ($public_fields_byuser[$result['id']] as $field => $value) {
                    $result[$field] = $value;
                }
            }
110
111
112
            if (isset($result['country'])) {
                $result['country'] = get_string('country.' . $result['country']);
            }
113
114
115
116
117
        }

    }

    return $results;
118
119
}

120

121
122
123
124
125
126
127
128
129
130
131
132
133

/* 
 * 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;
134
    foreach (array('member', 'requested', 'invitedby') as $p) {
135
136
137
138
        $institution->{$p} = $search->{$p};
    }
    $results = institutional_admin_user_search($search->query, $institution, $limit);
    if ($results['count']) {
139
140
141
142
        foreach ($results['data'] as &$r) {
            $r['name'] = $r['firstname'] . ' ' . $r['lastname'] . ' (' . $r['username'] . ')';
            if (!empty($r['studentid'])) {
                $r['name'] .= ' (' . $r['studentid'] . ')';
143
            }
144
145
146
147
148
149
150
151
152
153
154
155
156
        }
    }
    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);
}


157
158
159
160
161
/**
 * 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.
 */
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
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);

}
192

193
function get_admin_user_search_results($search, $offset, $limit, $sortby, $sortdir) {
194
195
    // In admin search, the search string is interpreted as either a
    // name search or an email search depending on its contents
Richard Mansfield's avatar
Richard Mansfield committed
196
    $queries = array();
197
    $constraints = array();
198
    if (!empty($search->query)) {
199
200
201
202
203
204
205
206
207
208
209
210
        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',
211
212
213
                                   'string' => $word);
                $queries[] = array('field' => 'username',
                                   'type' => 'contains',
214
215
216
217
218
                                   'string' => $word);
            }
        }
        foreach ($fullnames as $n) {
            $constraints[] = array('field' => 'firstname',
219
                                   'type' => 'contains',
220
221
                                   'string' => $n[0]);
            $constraints[] = array('field' => 'lastname',
222
                                   'type' => 'contains',
223
                                   'string' => $n[1]);
224
225
        }
    }
Richard Mansfield's avatar
Richard Mansfield committed
226
227
228
229
230
231
232
233
234
235
    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);
    }
236
237
238
    // Filter by viewable institutions:
    global $USER;
    if (!$USER->get('admin')) {
239
240
241
        if (empty($search->institution) && empty($search->institution_requested)) {
            $search->institution_requested = 'all';
        }
242
        $allowed = $USER->get('admininstitutions');
243
        foreach (array('institution', 'institution_requested') as $p) {
244
245
            if (!empty($search->{$p})) {
                if ($search->{$p} == 'all' || !isset($allowed[$search->{$p}])) {
246
247
                    $constraints[] = array('field' => $p,
                                           'type' => 'in',
248
                                           'string' => $allowed);
249
250
251
252
253
254
                } else {
                    $constraints[] = array('field' => $p,
                                           'type' => 'equals',
                                           'string' => $search->{$p});
                }
            }
255
        }
256
    } else if (!empty($search->institution) && $search->institution != 'all') {
Richard Mansfield's avatar
Richard Mansfield committed
257
258
259
        $constraints[] = array('field' => 'institution',
                               'type' => 'equals',
                               'string' => $search->institution);
260
    }
261
    
262
    $results = admin_user_search($queries, $constraints, $offset, $limit, $sortby, $sortdir);
263
264
265
    if ($results['count']) {
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
266
267
268
            if (!empty($result['institutions'])) {
                $result['institutions'] = array_combine($result['institutions'],$result['institutions']);
            }
269
        }
270
271
    }
    return $results;
272
273
274
275
276
277
278
}


function build_admin_user_search_results($search, $offset, $limit, $sortby, $sortdir) {
    global $USER;

    $results = get_admin_user_search_results($search, $offset, $limit, $sortby, $sortdir);
279

280
281
282
283
284
285
286
287
288
    $params = array();
    foreach ($search as $k => $v) {
        if (!empty($v)) {
            $params[] = $k . '=' . $v;
        }
    }
    $searchurl = get_config('wwwroot') . 'admin/users/search.php?' . join('&amp;', $params)
        . '&amp;limit=' . $limit;

289
290
    $usernametemplate = '<a href="' . get_config('wwwroot')
        . '{if $USER->is_admin_for_user($r.id)}admin/users/edit.php?id={$r.id}{else}user/view.php?id={$r.id}{/if}">{$r.username|escape}</a>';
291

292
293
    $cols = array(
        'icon'        => array('name'     => '',
294
                               'template' => '<img src="{profile_icon_url user=$r maxwidth=40 maxheight=40}" alt="' . get_string('profileimage') . '" />',
295
                               'class'    => 'center'),
296
297
298
        'firstname'   => array('name'     => get_string('firstname')),
        'lastname'    => array('name'     => get_string('lastname')),
        'username'    => array('name'     => get_string('username'),
299
                               'template' => $usernametemplate),
300
301
        'email'       => array('name'     => get_string('email')),
    );
302

303
304
305
    $institutions = get_records_assoc('institution', '', '', '', 'name,displayname');
    if (count($institutions) > 1) {
        $cols['institution'] = array('name'     => get_string('institution'),
306
                                     'template' => '{auto_escape off}{if empty($r.institutions)}{$institutions.mahara->displayname}{else}{foreach from=$r.institutions item=i}<div>{$institutions[$i]->displayname}</div>{/foreach}{/if}{if !empty($r.requested)}{foreach from=$r.requested item=i}<div class="pending">{str tag=requestto section=admin} {$institutions[$i]->displayname}{if $USER->is_institutional_admin("$i")} (<a href="{$WWWROOT}admin/users/addtoinstitution.php?id={$r.id}&institution={$i}">{str tag=confirm section=admin}</a>){/if}</div>{/foreach}{/if}{if !empty($r.invitedby)}{foreach from=$r.invitedby item=i}<div class="pending">{str tag=invitedby section=admin} {$institutions[$i]->displayname}</div>{/foreach}{/if}{/auto_escape}');
307
308
    }

309
    $smarty = smarty_core();
310
    $smarty->assign_by_ref('results', $results);
311
    $smarty->assign_by_ref('institutions', $institutions);
312
    $smarty->assign('USER', $USER);
313
314
315
316
317
318
319
    $smarty->assign('searchurl', $searchurl);
    $smarty->assign('sortby', $sortby);
    $smarty->assign('sortdir', $sortdir);
    $smarty->assign('pagebaseurl', $searchurl . '&sortby=' . $sortby . '&sortdir=' . $sortdir);
    $smarty->assign('cols', $cols);
    $smarty->assign('ncols', count($cols));
    return $smarty->fetch('searchresulttable.tpl');
320
321
322
}


323
function admin_user_search($queries, $constraints, $offset, $limit, $sortfield, $sortdir) {
324
    $plugin = get_config('searchplugin');
325
    safe_require('search', $plugin);
Richard Mansfield's avatar
Richard Mansfield committed
326
    return call_static_method(generate_class_name('search', $plugin), 'admin_search_user', 
327
                              $queries, $constraints, $offset, $limit, $sortfield, $sortdir);
328
329
330
}


331
332
333
334
335
336
337
338
339
/**
 * 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
 *
 * @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
340
341
 * @param array  $extra  User membershiptype
 *
342
 */
343
function get_group_user_search_results($group, $query, $offset, $limit, $membershiptype) {
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    $queries = array();
    $constraints = 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]);
        }
    }

366
    $results = group_user_search($group, $queries, $constraints, $offset, $limit, $membershiptype);
367
368
    if ($results['count']) {
        $userids = array_map(create_function('$a', 'return $a["id"];'), $results['data']);
Francois Marier's avatar
Francois Marier committed
369
        $introductions = get_records_sql_assoc("SELECT \"owner\", title
370
371
            FROM {artefact}
            WHERE artefacttype = 'introduction'
Francois Marier's avatar
Francois Marier committed
372
            AND \"owner\" IN (" . implode(',', db_array_to_ph($userids)) . ')',
373
374
375
376
            $userids);
        foreach ($results['data'] as &$result) {
            $result['name'] = display_name($result);
            $result['introduction'] = isset($introductions[$result['id']]) ? $introductions[$result['id']]->title : '';
377
378
379
            if (isset($result['jointime'])) {
                $result['jointime'] = strftime(get_string('strftimedate'), $result['jointime']);
            }
380
381
382
383
384
385
        }
    }
    return $results;
}


386
function group_user_search($group, $queries, $constraints, $offset, $limit, $membershiptype) {
387
388
389
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);
    return call_static_method(generate_class_name('search', $plugin), 'group_search_user', 
390
                              $group, $queries, $constraints, $offset, $limit, $membershiptype);
391
392
}

393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/**
 * 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(...),
 *               ),
 *           );
 */
426
function search_group($query_string, $limit, $offset = 0, $type = 'member') {
427
428
429
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);

430
    return call_static_method(generate_class_name('search', $plugin), 'search_group', $query_string, $limit, $offset, $type);
Nigel McNie's avatar
Nigel McNie committed
431
}
432
433
434
435
436
437
438

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

440
441
442
443
444
445
446
447
448
449
450
451
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) {
452
453
454
455
456
457
458
459
    // 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');
    }

460
461
    $types = get_portfolio_types_from_param($type);

462
463
464
    $plugin = 'internal';
    safe_require('search', $plugin);

465
466
467
    $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;
468
469
}

470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
function get_search_plugins() {
    $searchpluginoptions = array();

    if ($searchplugins = get_records_array('search_installed')) {
        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;
}
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535

/**
 * 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'))) {
        throw new Exception();
    }

    $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
536
        $count += count_records_sql('SELECT COUNT("owner") FROM {usr_friend_request}
537
            JOIN {usr} u ON (u.id = requester AND u.deleted = 0)
Francois Marier's avatar
Francois Marier committed
538
            WHERE "owner" = ?',
539
540
541
            array($userid)
        );

Francois Marier's avatar
Francois Marier committed
542
        array_push($sql, 'SELECT requester AS id, 1 AS status FROM {usr_friend_request} WHERE "owner" = ?
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
        ');
    }

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