lib.php 45.7 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 search-internal
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
 *
 */

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

/**
31
 * The internal search plugin which searches against the
Martyn Smith's avatar
Martyn Smith committed
32
33
34
35
 * Mahara database.
 */
class PluginSearchInternal extends PluginSearch {

36
37
38
39
    public static function can_be_disabled() {
        return false;
    }

Martyn Smith's avatar
Martyn Smith committed
40
41
42
    /**
     * Implement user searching with SQL
     *
43
44
     * NOTE: user with ID zero should never be returned
     *
Martyn Smith's avatar
Martyn Smith committed
45
46
47
     * @param string  The query string
     * @param integer How many results to return
     * @param integer What result to start at (0 == first result)
48
49
50
51
     * @param data    Filters the users searched by
     *                can contain:
     *             'group' => integer, // only users in this group
     *             'owner' => boolean  // include the group ownwer (only if group is set)
52
     *             'exclude'=> int     // excludes a user
Martyn Smith's avatar
Martyn Smith committed
53
54
55
56
57
     * @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
58
     *               data    => array(   // the result records
Martyn Smith's avatar
Martyn Smith committed
59
     *                   array(
60
61
62
63
64
65
66
     *                       id            => integer,
     *                       username      => string,
     *                       institution   => string,
     *                       firstname     => string,
     *                       lastname      => string,
     *                       preferredname => string,
     *                       email         => string,
Martyn Smith's avatar
Martyn Smith committed
67
68
     *                   ),
     *                   array(
69
70
71
72
73
74
75
     *                       id            => integer,
     *                       username      => string,
     *                       institution   => string,
     *                       firstname     => string,
     *                       lastname      => string,
     *                       preferredname => string,
     *                       email         => string,
Martyn Smith's avatar
Martyn Smith committed
76
77
78
79
80
     *                   ),
     *                   array(...),
     *               ),
     *           );
     */
81
    public static function search_user($query_string, $limit, $offset = 0, $data=array()) {
82
        safe_require('artefact', 'internal');
Richard Mansfield's avatar
Richard Mansfield committed
83
84
85
86
87
88
89
90
91
92

        // Get the list of searchable profile fields from the internal artefact
        $required   = array_keys(ArtefactTypeProfile::get_always_searchable_fields());
        $optional   = array_diff(array_keys(ArtefactTypeProfile::get_searchable_fields()), $required);
        $required[] = 'username'; // Not a profile field, but used in the search query.

        // Get a list of match expressions to use in the WHERE clause
        $matches = new StdClass;
        foreach (array_merge($required, $optional) as $f) {
            $matches->{$f} = self::match_user_field_expression($f, 'u');
93
        }
Richard Mansfield's avatar
Richard Mansfield committed
94

95
        $data = self::prepare_search_user_options($data);
96
97
        $sql = '
            SELECT
Richard Mansfield's avatar
Richard Mansfield committed
98
99
                COUNT(u.id)
            FROM {usr} u';
100
        if (isset($data['group'])) {
101
102
103
            $groupadminsql = '';
            if (isset($data['includeadmins']) and !$data['includeadmins']) {
                $groupadminsql = " AND gm.role != 'admin'";
104
            }
105
106
107
108
            $groupjoin = '
                INNER JOIN {group_member} gm ON
                    (gm.member = u.id AND gm.group = ' . (int)$data['group'] . $groupadminsql . ")\n";
            $sql .= $groupjoin;
109
        }
110
111
        $sql .= "
                LEFT OUTER JOIN {usr_account_preference} h ON (u.id = h.usr AND h.field = 'hiderealname')";
112
        $querydata = self::split_query_string(strtolower(trim($query_string)));
113
        $hidenameallowed = get_config('userscanhiderealnames') ? 'TRUE' : 'FALSE';
114
        $searchusernamesallowed = get_config('searchusernames') ? 'TRUE' : 'FALSE';
Richard Mansfield's avatar
Richard Mansfield committed
115
116
117
118
119
120
121
122
123
124
125
126
127

        $termsql = "$matches->preferredname
                    OR (
                        (u.preferredname IS NULL OR u.preferredname = '' OR NOT $hidenameallowed OR h.value != '1')
                        AND ($matches->firstname OR $matches->lastname)
                    )
                    OR ($searchusernamesallowed AND $matches->username)";

        if ($optional) {
            foreach ($optional as $f) {
                $termsql .= "
                    OR {$matches->$f}";
            }
128
129
        }

130
131
        $where = '
            WHERE
Richard Mansfield's avatar
Richard Mansfield committed
132
133
134
135
136
                u.id != 0 AND u.active = 1 AND u.deleted = 0';

        $values = array();
        foreach ($querydata as $term) {
            $where .= '
137
                AND (
Richard Mansfield's avatar
Richard Mansfield committed
138
139
140
141
142
143
144
145
146
147
                    ' . $termsql . '
                )';
            $values = array_pad($values, count($values) + 4 + count($optional), $term);
        }

        if (isset($data['exclude'])) {
            $where .= '
                AND u.id != ?';
            $values[] = $data['exclude'];
        }
148

149
150
        $sql .= $where;
        $count = count_records_sql($sql, $values);
151

152
        $result = array(
Nigel McNie's avatar
Nigel McNie committed
153
154
155
            'count'   => $count,
            'limit'   => $limit,
            'offset'  => $offset,
156
            'data'    => false,
Nigel McNie's avatar
Nigel McNie committed
157
        );
158

159
160
        if ($count < 1) {
            return $result;
161
162
        }

Richard Mansfield's avatar
Richard Mansfield committed
163
164
165
166
        $sql = '
            SELECT
                u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.studentid, u.staff
            FROM {usr} u';
167

168
169
170
        if (isset($data['group'])) {
            $sql .= $groupjoin;
        }
171
172
        $sql .= "
                LEFT OUTER JOIN {usr_account_preference} h ON (u.id = h.usr AND h.field = 'hiderealname')";
173
174
175
176
177
178
179
180
181
182
183
184
185

        $sql .= $where . '
            ORDER BY ' . $data['orderby'];

        $result['data'] = get_records_sql_array($sql, $values, $offset, $limit);

        if ($result['data']) {
            foreach ($result['data'] as &$item) {
                $item = (array)$item;
            }
        }

        return $result;
186
    }
187

Richard Mansfield's avatar
Richard Mansfield committed
188
189
190
191
192
193
194
    private static function match_user_field_expression($field, $alias) {
        if (get_config_plugin('search', 'internal', 'exactusersearch')) {
            return 'LOWER(' . $alias . '.' . $field . ') = ?';
        }
        return $alias . '.' . $field . ' ' . db_ilike() . " '%' || ? || '%'";
    }

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

    /**
     * Split a query string into search terms.
     *
     * Contents of double-quoted strings are counted as a single term,
     * '"' can be entered as '\"', '\' as '\\'.
     */
    private static function split_query_string($query) {
        $terms = array();

        // Split string on unescaped double quotes
        $quotesplit = preg_split('/(?<!\\\)(\")/', $query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

        $inphrase = false;

        foreach ($quotesplit as $q) {
            if ($q == '"') {
                $inphrase = !$inphrase;
                continue;
            }

            // Remove escaping
            $q = preg_replace(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $q);
            if ($inphrase) {
                if ($trimmed = trim($q)) {
                    $terms[] = $trimmed;
                }
            }
            else {
                // Split unquoted sequences on spaces
                foreach (preg_split('/\s+/', $q, -1, PREG_SPLIT_NO_EMPTY) as $word) {
                    $terms[] = $word;
                }
            }
        }
        return $terms;
    }


234
235
236
237
238
239
240
241
242
243
244
245
246
    private static function prepare_search_user_options($options) {
        if (isset($options['group'])) {
            $options['group'] = intval($options['group']);
        }
        if (isset($options['includeadmins'])) {
            $options['includeadmins'] = (bool)$options['includeadmins'];
        }
        if (isset($options['orderby']) && $options['orderby'] == 'lastname') {
            $options['orderby'] = 'u.lastname, u.firstname, u.id';
        }
        else {
            $options['orderby'] = 'u.firstname, u.lastname, u.id';
        }
247
248
249
        if (isset($options['exclude'])) {
            $options['exclude'] = intval($options['exclude']);
        }
250
251
        return $options;
    }
Nigel McNie's avatar
Nigel McNie committed
252
    
253

254
255
    private static function match_expression($op, $string, &$values, $ilike) {
        switch ($op) {
256
257
        case 'starts':
            $values[] = $string;
258
            return ' ' . $ilike . ' ? || \'%\'';
259
260
261
262
263
        case 'equals':
            $values[] = $string;
            return ' = ? ';
        case 'contains':
            $values[] = $string;
264
            return ' ' . $ilike . ' \'%\' || ? || \'%\'';
265
266
267
268
269
270
        case 'in':
            return ' IN (' . join(',', array_map('db_quote',$string)) . ')';
        }
    }


271
    public static function admin_search_user($queries, $constraints, $offset, $limit, 
272
                                             $sortfield, $sortdir) {
273
274
275
276
277
278
279
280
281
282
        $sort = 'TRUE';
        if (preg_match('/^[a-zA-Z_0-9"]+$/', $sortfield)) {
            $sort = $sortfield;
            if (strtoupper($sortdir) != 'DESC') {
                $sort .= ' ASC';
            }
            else {
                $sort .= ' DESC';
            }
        }
283
        $where = 'WHERE u.id <> 0 AND u.deleted = 0';
284
285
        $values = array();

286
287
288
        // Get the correct keyword for case insensitive LIKE
        $ilike = db_ilike();

289
        // Only handle OR/AND expressions at the top level.  Eventually we may need subexpressions.
290

Richard Mansfield's avatar
Richard Mansfield committed
291
        if (!empty($queries)) {
292
293
            $where .= ' AND ( ';
            $str = array();
Richard Mansfield's avatar
Richard Mansfield committed
294
            foreach ($queries as $f) {
295
296
297
                if (!preg_match('/^[a-zA-Z_0-9"]+$/', $f['field'])) {
                    continue; // skip this field as it fails validation
                }
298
                $str[] = 'u.' . $f['field'] 
299
                    . PluginSearchInternal::match_expression($f['type'], $f['string'], $values, $ilike);
300
301
302
303
            }
            $where .= join(' OR ', $str) . ') ';
        } 

304
305
306
        // @todo: Institution stuff is messy and will probably need to
        // be rewritten when we get multiple institutions per user

307
        $requested = false;
308
        $institutionsearch = '';
Richard Mansfield's avatar
Richard Mansfield committed
309
310
        if (!empty($constraints)) {
            foreach ($constraints as $f) {
311
312
313
314
315
316
                if (strpos($f['field'], 'institution') === 0) {
                    $institutionsearch .= ' 
                        LEFT OUTER JOIN {usr_institution} i ON i.usr = u.id ';
                    if (strpos($f['field'], 'requested') > 0) {
                        $institutionsearch .= ' 
                            LEFT OUTER JOIN {usr_institution_request} ir ON ir.usr = u.id ';
317
                    }
318
319
                    if ($f['field'] == 'institution_requested') {
                        $where .= ' AND ( i.institution ' .
320
                            PluginSearchInternal::match_expression($f['type'], $f['string'], $values, $ilike) .
321
                            ' OR ir.institution ' .
322
                            PluginSearchInternal::match_expression($f['type'], $f['string'], $values, $ilike) . ')';
323
                        $requested = true;
324
325
326
327
328
                    } else {
                        if ($f['string'] == 'mahara') {
                            $where .= ' AND i.institution IS NULL';
                        } else {
                            $where .= ' AND i.institution'
329
                                . PluginSearchInternal::match_expression($f['type'], $f['string'], $values, $ilike);
330
                        }
331
                    }
332
                } else {
333
                    $where .= ' AND u.' . $f['field'] 
334
                        . PluginSearchInternal::match_expression($f['type'], $f['string'], $values, $ilike);
335
                }
336
            }
337
        }
338
        if (strpos($sort, 'institution') === 0) {
339
            $sort = 'i.' . $sort;
340
341
            if ($institutionsearch == '') {
                $institutionsearch = ' LEFT OUTER JOIN {usr_institution} i ON i.usr = u.id ';
342
            }
343
344
        }

345
        $count = get_field_sql('SELECT COUNT(*) FROM {usr} u ' . $institutionsearch . $where, $values);
346
347

        if ($count > 0) {
348
            $data = get_records_sql_assoc('
349
                SELECT 
350
                    u.id, u.firstname, u.lastname, u.username, u.email, u.staff, u.profileicon,
351
                    u.active, NOT u.suspendedcusr IS NULL as suspended
352
                FROM
353
                    {usr} u ' . $institutionsearch . $where . '
354
                ORDER BY ' . $sort,
355
                $values,
Richard Mansfield's avatar
Richard Mansfield committed
356
357
                $offset,
                $limit);
358
359

            if ($data) {
360
361
362
363
364
365
366
367
                $inst = get_records_select_array('usr_institution', 
                                                 'usr IN (' . join(',', array_keys($data)) . ')',
                                                 null, '', 'usr,institution');
                if ($inst) {
                    foreach ($inst as $i) {
                        $data[$i->usr]->institutions[] = $i->institution;
                    }
                }
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
                if ($requested) {
                    $inst = get_records_select_array('usr_institution_request', 
                                                     'usr IN (' . join(',', array_keys($data)) . ')',
                                                     null, '', 'usr,institution,confirmedusr,confirmedinstitution');
                    if ($inst) {
                        foreach ($inst as $i) {
                            if ($i->confirmedusr) {
                                $data[$i->usr]->requested[] = $i->institution;
                            }
                            if ($i->confirmedinstitution) {
                                $data[$i->usr]->invitedby[] = $i->institution;
                            }
                        }
                    }
                }
383
                foreach ($data as &$item) {
384
                    $item->username = display_username($item);
385
386
                    $item = (array)$item;
                }
387
                $data = array_values($data);
388
389
390
391
392
393
394
395
            }
        }
        else {
            $data = false;
        }

        return array(
            'count'   => $count,
Richard Mansfield's avatar
Richard Mansfield committed
396
397
            'limit'   => $limit,
            'offset'  => $offset,
398
399
400
401
            'data'    => $data,
        );
    }

402

403
    public static function group_search_user($group, $queries, $constraints, $offset, $limit, $membershiptype, $order=null) {
404
        // Only handle OR/AND expressions at the top level.  Eventually we may need subexpressions.
405
406
        $searchsql = '';
        $values = array();
407
        if (!empty($queries)) {
408
409
            $ilike = db_ilike();
            $searchsql .= ' AND ( ';
410
411
            $str = array();
            foreach ($queries as $f) {
412
413
414
                if (!preg_match('/^[a-zA-Z_0-9"]+$/', $f['field'])) {
                    continue; // skip this field as it fails validation
                }
415
416
417
                $str[] = 'u.' . $f['field'] 
                    . PluginSearchInternal::match_expression($f['type'], $f['string'], $values, $ilike);
            }
418
            $searchsql .= join(' OR ', $str) . ') ';
419
420
        }

421
422
423
424
425
426
427
428
429
        if ($membershiptype == 'nonmember') {
            $select = '
                    u.id, u.firstname, u.lastname, u.username, u.email, u.profileicon, u.staff';
            $from = '
                FROM {usr} u
                WHERE u.id > 0 AND u.deleted = 0 ' . $searchsql . '
                    AND NOT u.id IN (SELECT member FROM {group_member} gm WHERE gm.group = ?)';
            $values[] = $group;
            $orderby = 'u.firstname, u.lastname, u.id';
430
        }
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
        else if ($membershiptype == 'notinvited') {
            $select = '
                    u.id, u.firstname, u.lastname, u.username, u.email, u.profileicon, u.staff';
            $from = '
                FROM {usr} u
                WHERE u.id > 0 AND u.deleted = 0 ' . $searchsql . '
                    AND NOT u.id IN (SELECT member FROM {group_member} gm WHERE gm.group = ?)
                    AND NOT u.id IN (SELECT member FROM {group_member_invite} gmi WHERE gmi.group = ?)';
            $values[] = $group;
            $values[] = $group;
            $orderby = 'u.firstname, u.lastname, u.id';
        }
        else if ($membershiptype == 'request') {
            $select = '
                    u.id, u.firstname, u.lastname, u.username, u.email, u.profileicon,
                    u.staff, ' . db_format_tsfield('gmr.ctime', 'jointime');
            $from = '
                FROM {usr} u
                    INNER JOIN {group_member_request} gmr ON (gmr.member = u.id)
                WHERE u.id > 0 AND u.deleted = 0 ' . $searchsql . '
                    AND gmr.group = ?';
            $values[] = $group;
453
            $orderby = 'u.firstname, u.lastname, gmr.ctime, u.id';
454
455
456
457
458
459
460
461
462
463
464
        }
        else if ($membershiptype == 'invite') {
            $select = '
                    u.id, u.firstname, u.lastname, u.username, u.email, u.profileicon,
                    u.staff, ' . db_format_tsfield('gmi.ctime', 'jointime');
            $from = '
                FROM {usr} u
                    INNER JOIN {group_member_invite} gmi ON (gmi.member = u.id)
                WHERE u.id > 0 AND u.deleted = 0 ' . $searchsql . '
                    AND gmi.group = ?';
            $values[] = $group;
465
            $orderby = 'u.firstname, u.lastname, gmi.ctime, u.id';
466
467
468
469
470
471
472
473
474
475
476
        }
        else { // All group members
            $select = '
                    u.id, u.firstname, u.lastname, u.username, u.email, u.profileicon,
                    u.staff, ' . db_format_tsfield('gm.ctime', 'jointime') . ', gm.role';
            $from = '
                FROM {usr} u
                    INNER JOIN {group_member} gm ON (gm.member = u.id)
                WHERE u.id > 0 AND u.deleted = 0 ' . $searchsql . '
                    AND gm.group = ?';
            $values[] = $group;
477
            $orderby = "gm.role = 'admin' DESC, u.firstname, u.lastname, gm.ctime, u.id";
478
479
480
            if ($order == 'latest') {
                $orderby = 'gm.ctime DESC, u.firstname, u.lastname, u.id';
            }
481
482
        }

483
        if ($order == 'random') {
484
485
486
            $orderby = db_random();
        }

487
        $count = get_field_sql('SELECT COUNT(*)' . $from, $values);
488
489
490

        if ($count > 0) {
            $data = get_records_sql_assoc('
491
                SELECT ' . $select . $from . ' ORDER BY ' . $orderby,
492
493
494
495
496
497
498
499
500
501
502
503
                $values,
                $offset,
                $limit);

            if ($data) {
                foreach ($data as &$item) {
                    $item = (array)$item;
                }
                $data = array_values($data);
            }
        }
        else {
504
            $data = array();
505
506
507
508
509
510
511
512
513
514
        }

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

515
516
517
518
519
520
521
522
523
524

    public static function institutional_admin_search_user($query, $institution, $limit) {
        $sql = '
            FROM {usr} u ';

        $where = '
            WHERE u.id <> 0 AND u.deleted = 0 ';

        $values = array();
        if (!empty($query)) {
525
526
527
528
529
530
531
            $query = preg_replace('/\s\s+/', ' ', $query);
            $words = explode(' ', $query);
            foreach ($words as &$word) {
                $values[] = $word;
                $values[] = $word;
                $word = 'u.firstname ' . db_ilike() . ' \'%\' || ? || \'%\' OR u.lastname ' . db_ilike() . ' \'%\' || ? || \'%\'';
            }
532
            $where .= '
533
                AND (' . join(' OR ', $words) . ') ';
534
535
        }

536
        $studentid = '';
537
538
539
540
541
542
        if (!is_null($institution->member)) {
            $sql .= '
                LEFT OUTER JOIN {usr_institution} member ON (member.usr = u.id
                    AND member.institution = ' . db_quote($institution->name) . ')';
            $where .= '
                AND ' . ($institution->member ? ' NOT ' : '') . ' member.usr IS NULL';
543
            $studentid = ', member.studentid';
544
        }
545
        if (!is_null($institution->requested) || !is_null($institution->invitedby)) {
546
547
548
549
550
551
552
553
554
            $sql .= '
                LEFT OUTER JOIN {usr_institution_request} req ON (req.usr = u.id
                    AND req.institution = ' . db_quote($institution->name) . ')';
            if (!is_null($institution->requested)) {
                if ($institution->requested == 1) {
                    $where .= ' AND req.confirmedusr = 1';
                } else {
                    $where .= ' AND (req.confirmedusr = 0 OR req.confirmedusr IS NULL)';
                }
555
                $studentid = ', req.studentid';
556
            }
557
            if (!is_null($institution->invitedby)) {
558
559
560
561
562
563
564
565
566
567
568
569
570
571
                if ($institution->requested == 1) {
                    $where .= ' AND req.confirmedinstitution = 1';
                } else {
                    $where .= ' AND (req.confirmedinstitution = 0 OR req.confirmedinstitution IS NULL)';
                }
            }
        }

        $count = get_field_sql('SELECT COUNT(*) ' . $sql . $where, $values);

        if ($count > 0) {
            $data = get_records_sql_array('
                SELECT 
                    u.id, u.firstname, u.lastname, u.username, u.preferredname, 
572
                    u.admin, u.staff' . $studentid . $sql . $where . '
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
                ORDER BY u.firstname ASC',
                $values,
                0,
                $limit);
            foreach ($data as &$item) {
                $item = (array)$item;
            }
        }
        else {
            $data = false;
        }

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





597
598
599
600
601
602
    /**
     * Implement group searching with SQL
     *
     * @param string  The query string
     * @param integer How many results to return
     * @param integer What result to start at (0 == first result)
603
     * @param string  Which groups to search (all, member, notmember)
604
605
606
607
608
609
610
     * @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
     *               data    => array(   // the result records
     *                   array(
Nigel McNie's avatar
Nigel McNie committed
611
     *                       id            => integer,
612
613
614
615
616
617
     *                       name          => string,
     *                       description   => string,
     *                       jointype      => string,
     *                       owner         => string,
     *                       ctime         => string,
     *                       mtime         => string,
Nigel McNie's avatar
Nigel McNie committed
618
619
620
     *                   ),
     *                   array(
     *                       id            => integer,
621
622
623
624
625
626
     *                       name          => string,
     *                       description   => string,
     *                       jointype      => string,
     *                       owner         => string,
     *                       ctime         => string,
     *                       mtime         => string,
Nigel McNie's avatar
Nigel McNie committed
627
628
629
630
631
     *                   ),
     *                   array(...),
     *               ),
     *           );
     */
632
    public static function search_group($query_string, $limit, $offset=0, $type='member', $category='') {
633
        global $USER;
634
635
        $data = array();

636
637
        $sql = "
            FROM
638
                {group}
639
            WHERE (
640
641
                name " . db_ilike() . " '%' || ? || '%'
                OR description " . db_ilike() . " '%' || ? || '%'
642
643
644
            ) AND deleted = 0 ";
        $values = array($query_string, $query_string);

645
646
647
648
        if (!$grouproles = join(',', array_keys($USER->get('grouproles')))) {
            $grouproles = '-1';
        }

649
       if ($type == 'member') {
650
            $sql .=  'AND id IN (' . $grouproles . ')';
651
        }
652
        else if ($type == 'notmember') {
653
            $sql .= 'AND id NOT IN (' . $grouproles . ')';
654
        }
655
        if (!empty($category)) {
Dan Marsden's avatar
Dan Marsden committed
656
            if ($category == -1) { //find unassigned groups
657
                $sql .= " AND category IS NULL";
Dan Marsden's avatar
Dan Marsden committed
658
            } else {
659
660
                $sql .= ' AND category = ?';
                $values[] = $category;
Dan Marsden's avatar
Dan Marsden committed
661
            }
662
        }
663

664
665
666
        $count = get_field_sql('SELECT COUNT(*) '.$sql, $values);

        if ($count > 0) {
667
            $sql = 'SELECT id, name, description, grouptype, jointype, public, ctime, mtime, category ' . $sql . ' ORDER BY name';
668
            $data = get_records_sql_array($sql, $values, $offset, $limit);
669
        }
Martyn Smith's avatar
Martyn Smith committed
670
671
672
673
674

        return array(
            'count'   => $count,
            'limit'   => $limit,
            'offset'  => $offset,
675
            'data'    => $data,
Martyn Smith's avatar
Martyn Smith committed
676
677
        );
    }
Martyn Smith's avatar
Martyn Smith committed
678
679
680
681
682
683
684
685
686
687
688

    /**
     * Given a query string and limits, return an array of matching objects
     * owned by the current user.  Possible return types are ...
     *   - artefact
     *   - view
     *
     * Implementations of this search should search across tags for artefacts
     * and views at a minimum. Ideally the search would also index
     * title/description and other metadata for these objects.
     *
689
690
691
     * NOTE: This implementation of internal search only does artefacts, and
     * badly at that. See the bug tracker for more information.
     *
Martyn Smith's avatar
Martyn Smith committed
692
693
694
695
696
697
     * @param string  The query string
     * @param integer How many results to return
     * @param integer What result to start at (0 == first result)
     * @param string  Type to search for (either 'all' or one of the types above).
     * 
     */
698
699
    public static function self_search($querystring, $limit, $offset, $type = 'all') {
        global $USER;
700
701
702
703
        if (trim($querystring) == '') {
            return false;
        }

704
705
706
707
708
        // Tokenise the search
        $querydata = self::search_parse_query($querystring);

        $sql = "
            SELECT
709
                a.id, a.artefacttype, a.title, a.description
710
            FROM
711
                {artefact} a
712
            LEFT JOIN {artefact_tag} at ON (at.artefact = a.id)
713
            WHERE
714
715
716
717
718
719
                a.owner = ?
            AND (
                ($querydata[0])
                OR
                (LOWER(at.tag) = ?)
            )";
720
721
722
723
        $count_sql = "
            SELECT
                COUNT(*)
            FROM
724
                {artefact} a
725
            LEFT JOIN {artefact_tag} at ON (at.artefact = a.id)
726
            WHERE
727
728
729
730
731
732
                a.owner = ?
            AND (
                ($querydata[0])
                OR
                (LOWER(at.tag) = ?)
            )";
733
        array_unshift($querydata[1], $USER->get('id'));
734
735
        array_push($querydata[1], $querystring);

736
737
738
739
740
741
742
        $results = array(
            'data'   => get_records_sql_array($sql, $querydata[1], $offset, $limit),
            'offset' => $offset,
            'limit'  => $limit,
            'count'  => get_field_sql($count_sql, $querydata[1])
        );

743
744
745
746
747
748
749
        if ($results['data']) {
            foreach ($results['data'] as &$result) {
                $newresult = array();
                foreach ($result as $key => &$value) {
                    if ($key == 'id' || $key == 'artefacttype' || $key == 'title' || $key == 'description') {
                        $newresult[$key] = $value;
                    }
750
                }
751
752
753
754
755
756
757
758
759
                $newresult['type'] = 'artefact';
                $artefactplugin = get_field('artefact_installed_type', 'plugin', 'name', $newresult['artefacttype']);
                if ($artefactplugin == 'internal') {
                    $newresult['summary'] = $newresult['title'];
                    $newresult['title'] = get_string($newresult['artefacttype'], 'artefact.' . $artefactplugin);
                }
                else {
                    $newresult['summary'] = $newresult['description'];
                }
760
                $newresult['summary'] = clean_html($newresult['summary']);
761
                $result = $newresult;
762
            }
763
764

            self::self_search_make_links($results);
765
766
767
768
769
770
        }

        return $results;
    }


771
772
773
774
775
776
777
778
    /**
     * Returns portfolio items (artefacts, views) owned by $owner and tagged
     * with $tag.
     *
     * @param string   $tag Tag
     * @param object   $owner: owner type (user,group,institution), and id
     * @param integer  $limit
     * @param integer  $offset
779
     * @param string   $sort
780
     * @param array    $types view/artefacttype filters
781
     * @param boolean  $returntags Return all the tags that have been attached to each result
782
     */
783
    public static function portfolio_search_by_tag($tag, $owner, $limit, $offset, $sort, $types, $returntags) {
784
785
        $viewfilter = is_null($types) || $types['view'] == true ? 'AND TRUE' : 'AND FALSE';

786
787
788
789
790
791
792
793
794
795
        if (is_null($types)) {
            $artefacttypefilter = '';
        }
        else if (!empty($types['artefact'])) {
            $artefacttypefilter = ' AND a.artefacttype IN (' . join(',', array_map('db_quote', $types['artefact'])) . ')';
        }
        else {
            $artefacttypefilter = ' AND FALSE';
        }

796
797
798
799
800
801
802
803
804
        if (!is_null($tag)) {
            $artefacttypefilter .= ' AND at.tag = ?';
            $viewfilter .= ' AND vt.tag = ?';
            $values = array($owner->id, $tag, $owner->id, $tag);
        }
        else {
            $values = array($owner->id, $owner->id);
        }

805
806
        $from = "FROM (
           (SELECT a.id, a.title, a.description, 'artefact' AS type, a.artefacttype, " . db_format_tsfield('a.ctime', 'ctime') . "
807
            FROM {artefact} a JOIN {artefact_tag} at ON (a.id = at.artefact)
808
            WHERE a.owner = ?" . $artefacttypefilter . ")
809
810
           UNION
           (SELECT v.id, v.title, v.description, 'view' AS type, NULL AS artefacttype, " . db_format_tsfield('v.ctime', 'ctime') . "
811
812
            FROM {view} v JOIN {view_tag} vt ON (v.id = vt.view)
            WHERE v.owner = ? " . $viewfilter . ")
813
814
815
816
817
818
819
        ) p";

        $result = (object) array(
            'tag'    => $tag,
            'owner'  => $owner,
            'offset' => $offset,
            'limit'  => $limit,
820
            'sort'   => $sort,
821
822
823
824
825
826
            'count'  => 0,
            'data'   => array(),
        );

        if ($count = count_records_sql('SELECT COUNT(*) ' . $from, $values, $offset, $limit)) {
            $result->count = $count;
827
            $sort = $sort == 'date' ? 'ctime DESC' : 'title ASC';
828
            if ($data = get_records_sql_assoc("SELECT type || ':' || id AS tid, p.* " . $from . ' ORDER BY ' . $sort, $values, $offset, $limit)) {
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
                if ($returntags) {
                    $ids = array('view' => array(), 'artefact' => array());
                    foreach ($data as &$d) {
                        $ids[$d->type][$d->id] = 1;
                    }
                    if (!empty($ids['view'])) {
                        if ($viewtags = get_records_select_array('view_tag', 'view IN (' . join(',', array_keys($ids['view'])) . ')')) {
                            foreach ($viewtags as &$vt) {
                                $data['view:' . $vt->view]->tags[] = $vt->tag;
                            }
                        }
                    }
                    if (!empty($ids['artefact'])) {
                        if ($artefacttags = get_records_select_array('artefact_tag', 'artefact IN (' . join(',', array_keys($ids['artefact'])) . ')')) {
                            foreach ($artefacttags as &$at) {
                                $data['artefact:' . $at->artefact]->tags[] = $at->tag;
                            }
                        }
                    }
                }
849
850
851
852
853
854
855
                $result->data = $data;
            }
        }
        return $result;
    }


856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
    /**
     * Parses a query string into SQL fragments for searching. Supports 
     * phrases, AND/OR etc.
     *
     * Lifted from drupal 5.1, (C) 2007 Drupal
     *
     * This function comes from Drupal's search module, with some small changes.
     */
    private static function search_parse_query($text) {
        $keys = array('positive' => array(), 'negative' => array());

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

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

        // Classify tokens
        $or = FALSE;
        foreach ($matches as $match) {
          $phrase = FALSE;
          // Strip off phrase quotes
          if ($match[2]{0} == '"') {
            $match[2] = substr($match[2], 1, -1);
            $phrase = TRUE;
          }
          // Simplify keyword according to indexing rules and external preprocessors
          $words = self::search_simplify($match[2]);
          // Re-explode in case simplification added more words, except when matching a phrase
          $words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
          // Negative matches
          if ($match[1] == '-') {
            $keys['negative'] = array_merge($keys['negative'], $words);
          }
          // OR operator: instead of a single keyword, we store an array of all
          // OR'd keywords.
          elseif ($match[2] == 'OR' && count($keys['positive'])) {
            $last = array_pop($keys['positive']);
            // Starting a new OR?
            if (!is_array($last)) {
              $last = array($last);
            }
            $keys['positive'][] = $last;
            $or = TRUE;
            continue;
          }
          // Plain keyword
          else {
            if ($or) {
              // Add to last element (which is an array)
              $keys['positive'][count($keys['positive']) - 1] = array_merge($keys['positive'][count($keys['positive']) - 1], $words);
            }
            else {
              $keys['positive'] = array_merge($keys['positive'], $words);
            }
          }
          $or = FALSE;
        }

        // Convert keywords into SQL statements.
        $query = array();
        //$query2 = array();
        $arguments = array();
        $arguments2 = array();
        //$matches = 0; 
        // Positive matches
        foreach ($keys['positive'] as $key) {
          // Group of ORed terms
          if (is_array($key) && count($key)) {
            $queryor = array();
            $any = FALSE;
            foreach ($key as $or) {
              list($q, $count) = self::_search_parse_query($or, $arguments2);
              $any |= $count;
              if ($q) {
                $queryor[] = $q;
                $arguments[] = $or;
                $arguments[] = $or;
              }
            }

            if (count($queryor)) {
              $query[] = '('. implode(' OR ', $queryor) .')';
              // A group of OR keywords only needs to match once
              //$matches += ($any > 0);
            }
          }
          // Single ANDed term
          else {
            list($q, $count) = self::_search_parse_query($key, $arguments2);
            if ($q) {
              $query[] = $q;
              $arguments[] = $key;
              $arguments[] = $key;
              // Each AND keyword needs to match at least once
              //$matches += $count;
            }
          }
        }
        // Negative matches
        foreach ($keys['negative'] as $key) {
          list($q) = self::_search_parse_query($key, $arguments2, TRUE);
          if ($q) {
            $query[] = $q;
            $arguments[] = $key;
            $arguments[] = $key;
          }
        }
        $query = implode(' AND ', $query);

        // Build word-index conditions for the first pass
        //$query2 = substr(str_repeat("i.word = '%s' OR ", count($arguments2)), 0, -4);

        return array($query, $arguments, /*$query2, $arguments2, $matches*/);
Martyn Smith's avatar
Martyn Smith committed
971
    }
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

    /**
     * Helper function for search_parse_query();
     */
    private static function _search_parse_query(&$word, &$scores, $not = FALSE) {
      $count = 0;
      // Determine the scorewords of this word/phrase
      if (!$not) {
        $split = explode(' ', $word);
        foreach ($split as $s) {
          $num = is_numeric($s);
          if ($num || strlen($s) >= /*variable_get('minimum_word_size', 3)*/3) {
            $s = $num ? ((int)ltrim($s, '-0')) : $s;
            if (!isset($scores[$s])) {
              $scores[$s] = $s;
              $count++;
            }
          }
        }
      }
      // Return matching snippet and number of added words
      return array("a.title ". ($not ? 'NOT ' : '') ."LIKE '%' || ? || '%'" . ($not ? ' AND ' : ' OR ') . 'a.description ' . ($not ? 'NOT ' : '') . "LIKE '%' || ? || '%'", $count);
    }

    /**
     * Simplifies a string according to indexing rules.
     */
    private static function search_simplify($text) {
      // Decode entities to UTF-8
For faster browsing, not all history is shown. View entire blame