searchlib.php 19.4 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
 * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
Martyn Smith's avatar
Martyn Smith committed
5
 *
Francois Marier's avatar
Francois Marier committed
6
7
8
9
 * 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
10
 *
Francois Marier's avatar
Francois Marier committed
11
12
13
14
 * 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
15
 *
Francois Marier's avatar
Francois Marier committed
16
17
 * 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
18
19
20
 *
 * @package    mahara
 * @subpackage core
21
 * @author     Catalyst IT Ltd
Martyn Smith's avatar
Martyn Smith committed
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
23
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
Martyn Smith's avatar
Martyn Smith committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 * @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(
43
44
45
46
47
48
49
 *                       id            => integer,
 *                       username      => string,
 *                       institution   => string,
 *                       firstname     => string,
 *                       lastname      => string,
 *                       preferredname => string,
 *                       email         => string,
Martyn Smith's avatar
Martyn Smith committed
50
51
 *                   ),
 *                   array(
52
53
54
55
56
57
58
 *                       id            => integer,
 *                       username      => string,
 *                       institution   => string,
 *                       firstname     => string,
 *                       lastname      => string,
 *                       preferredname => string,
 *                       email         => string,
Martyn Smith's avatar
Martyn Smith committed
59
60
61
62
63
 *                   ),
 *                   array(...),
 *               ),
 *           );
 */
64
function search_user($query_string, $limit, $offset = 0, $data = array()) {
Martyn Smith's avatar
Martyn Smith committed
65
    $plugin = get_config('searchplugin');
66
    safe_require('search', $plugin);
67
    safe_require('artefact', 'internal');
Martyn Smith's avatar
Martyn Smith committed
68

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

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

77
    if ($results['data']) {
78
79
80
81
82
83
        $userlist = '('.join(',', array_map(create_function('$u','return $u[\'id\'];'), $results['data'])).')';

        $public_fields = get_records_sql_array('
            SELECT 
                u.id, a.artefacttype, a.title
            FROM
84
85
                {usr} u
                LEFT JOIN {artefact} a ON u.id=a.owner AND a.artefacttype IN ' . $fieldlist . '
86
87
88
89
90
91
92
93
94
            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) {
95
96
97
98
                // 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;
                }
99
100
101
102
103
104
105
106
107
108
            }
        }
        
        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;
                }
            }
109
110
111
            if (isset($result['country'])) {
                $result['country'] = get_string('country.' . $result['country']);
            }
112
113
114
115
116
        }

    }

    return $results;
117
118
}

119

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

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


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

}
191

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


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

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

279
280
281
282
283
284
285
286
287
    $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;

288
289
290
291
292
293
294
295
296
297
    $usernametemplate = '<a href="' . get_config('wwwroot') . 'admin/users/edit.php?id={$r.id}">{$r.username|escape}</a>';
    if (!$USER->get('admin')) {
        // Only create the edit link if the returned user belongs to an institution that the viewer administers
        $cond = array();
        foreach ($USER->get('admininstitutions') as $i) {
            $cond[] = 'isset($r.institutions.' . $i . ')';
        }
        $usernametemplate = '{if ' . join('||', $cond) . '}' . $usernametemplate . '{else}{$r.username}{/if}';
    }

298
299
    $cols = array(
        'icon'        => array('name'     => '',
300
301
                               'template' => '<img src="' . get_config('wwwroot') . 'thumb.php?type=profileicon&maxwidth=40&maxheight=40&id={$r.id}" alt="' . get_string('profileimage') . '" />',
                               'class'    => 'center'),
302
303
304
        'firstname'   => array('name'     => get_string('firstname')),
        'lastname'    => array('name'     => get_string('lastname')),
        'username'    => array('name'     => get_string('username'),
305
                               'template' => $usernametemplate),
306
307
        'email'       => array('name'     => get_string('email')),
    );
308

309
310
311
    $institutions = get_records_assoc('institution', '', '', '', 'name,displayname');
    if (count($institutions) > 1) {
        $cols['institution'] = array('name'     => get_string('institution'),
312
                                     'template' => '{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}');
313
314
    }

315
    $smarty = smarty_core();
316
    $smarty->assign_by_ref('results', $results);
317
    $smarty->assign_by_ref('institutions', $institutions);
318
    $smarty->assign('USER', $USER);
319
320
321
322
323
324
325
    $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');
326
327
328
}


329
function admin_user_search($queries, $constraints, $offset, $limit, $sortfield, $sortdir) {
330
    $plugin = get_config('searchplugin');
331
    safe_require('search', $plugin);
Richard Mansfield's avatar
Richard Mansfield committed
332
    return call_static_method(generate_class_name('search', $plugin), 'admin_search_user', 
333
                              $queries, $constraints, $offset, $limit, $sortfield, $sortdir);
334
335
336
}


337
338
339
340
341
342
343
344
345
/**
 * 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
346
347
 * @param array  $extra  User membershiptype
 *
348
 */
349
function get_group_user_search_results($group, $query, $offset, $limit, $membershiptype) {
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
    $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]);
        }
    }

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


390
function group_user_search($group, $queries, $constraints, $offset, $limit, $membershiptype) {
391
392
393
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);
    return call_static_method(generate_class_name('search', $plugin), 'group_search_user', 
394
                              $group, $queries, $constraints, $offset, $limit, $membershiptype);
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
426
427
428
429
/**
 * 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(...),
 *               ),
 *           );
 */
430
function search_group($query_string, $limit, $offset = 0, $type = 'member') {
431
432
433
    $plugin = get_config('searchplugin');
    safe_require('search', $plugin);

434
    return call_static_method(generate_class_name('search', $plugin), 'search_group', $query_string, $limit, $offset, $type);
Nigel McNie's avatar
Nigel McNie committed
435
}
436
437
438
439
440
441
442

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

444
function get_portfolio_items_by_tag($tag, $owner, $limit, $offset, $sort='name', $returntags=true) {
445
446
447
448
449
450
451
452
453
454
455
    // 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');
    }

    $plugin = 'internal';
    safe_require('search', $plugin);

456
    return call_static_method(generate_class_name('search', $plugin), 'portfolio_search_by_tag', $tag, $owner, $limit, $offset, $sort, $returntags);
457
458
}

459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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;
}
Martyn Smith's avatar
Martyn Smith committed
479
?>