Failed Conditions
Pull Request — master (#2943)
by Andreas
03:32
created

search.php ➔ search_pagename()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 6
nop 6
dl 0
loc 20
rs 8.9777
c 0
b 0
f 0
1
<?php
2
/**
3
 * DokuWiki search functions
4
 *
5
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6
 * @author     Andreas Gohr <[email protected]>
7
 */
8
9
use dokuwiki\Utf8\Sort;
10
11
/**
12
 * Recurse directory
13
 *
14
 * This function recurses into a given base directory
15
 * and calls the supplied function for each file and directory
16
 *
17
 * @param   array    &$data The results of the search are stored here
18
 * @param   string    $base Where to start the search
19
 * @param   callback  $func Callback (function name or array with object,method)
20
 * @param   array     $opts option array will be given to the Callback
21
 * @param   string    $dir  Current directory beyond $base
22
 * @param   int       $lvl  Recursion Level
23
 * @param   mixed     $sort 'natural' to use natural order sorting (default);
24
 *                          'date' to sort by filemtime; leave empty to skip sorting.
25
 * @author  Andreas Gohr <[email protected]>
26
 */
27
function search(&$data, $base, $func, $opts, $dir='', $lvl=1, $sort='natural')
28
{
29
    $dirs   = array();
30
    $files  = array();
31
    $filepaths = array();
32
33
    // safeguard against runaways #1452
34
    if ($base == '' || $base == '/') {
35
        throw new RuntimeException('No valid $base passed to search() - possible misconfiguration or bug');
36
    }
37
38
    //read in directories and files
39
    $dh = @opendir($base.'/'.$dir);
40
    if (!$dh) return;
41
    while (($file = readdir($dh)) !== false) {
42
        if (preg_match('/^[\._]/', $file)) continue; //skip hidden files and upper dirs
43
        if (is_dir($base.'/'.$dir.'/'.$file)) {
44
            $dirs[] = $dir.'/'.$file;
45
            continue;
46
        }
47
        $files[] = $dir.'/'.$file;
48
        $filepaths[] = $base.'/'.$dir.'/'.$file;
49
    }
50
    closedir($dh);
51
    if (!empty($sort)) {
52
        if ($sort == 'date') {
53
            @array_multisort(array_map('filemtime', $filepaths), SORT_NUMERIC, SORT_DESC, $files);
0 ignored issues
show
Bug introduced by
array_map('filemtime', $filepaths) cannot be passed to array_multisort() as the parameter $arr expects a reference.
Loading history...
54
        } else /* natural */ {
55
            Sort::asortFN($files);
56
        }
57
        Sort::asortFN($dirs);
58
    }
59
60
    //give directories to userfunction then recurse
61
    foreach ($dirs as $dir) {
62
        if (call_user_func_array($func, array(&$data, $base, $dir, 'd', $lvl,$opts))) {
63
            search($data, $base, $func, $opts, $dir, $lvl+1, $sort);
64
        }
65
    }
66
    //now handle the files
67
    foreach ($files as $file) {
68
        call_user_func_array($func, array(&$data, $base, $file, 'f', $lvl, $opts));
69
    }
70
}
71
72
/**
73
 * The following functions are userfunctions to use with the search
74
 * function above. This function is called for every found file or
75
 * directory. When a directory is given to the function it has to
76
 * decide if this directory should be traversed (true) or not (false)
77
 * The function has to accept the following parameters:
78
 *
79
 * array &$data  - Reference to the result data structure
80
 * string $base  - Base usually $conf['datadir']
81
 * string $file  - current file or directory relative to $base
82
 * string $type  - Type either 'd' for directory or 'f' for file
83
 * int    $lvl   - Current recursion depht
84
 * array  $opts  - option array as given to search()
85
 *
86
 * return values for files are ignored
87
 *
88
 * All functions should check the ACL for document READ rights
89
 * namespaces (directories) are NOT checked (when sneaky_index is 0) as this
90
 * would break the recursion (You can have an nonreadable dir over a readable
91
 * one deeper nested) also make sure to check the file type (for example
92
 * in case of lockfiles).
93
 */
94
95
/**
96
 * Searches for pages beginning with the given query
97
 *
98
 * @author Andreas Gohr <[email protected]>
99
 *
100
 * @param array $data
101
 * @param string $base
102
 * @param string $file
103
 * @param string $type
104
 * @param integer $lvl
105
 * @param array $opts
106
 *
107
 * @return bool
108
 */
109
function search_qsearch(&$data, $base, $file, $type, $lvl, $opts)
110
{
111
    $opts = array(
112
            'idmatch'   => '(^|:)'.preg_quote($opts['query'],'/').'/',
113
            'listfiles' => true,
114
            'pagesonly' => true,
115
            );
116
    return search_universal($data, $base, $file, $type, $lvl, $opts);
117
}
118
119
/**
120
 * Build the browsable index of pages
121
 *
122
 * $opts['ns'] is the currently viewed namespace
123
 *
124
 * @author  Andreas Gohr <[email protected]>
125
 *
126
 * @param array $data
127
 * @param string $base
128
 * @param string $file
129
 * @param string $type
130
 * @param integer $lvl
131
 * @param array $opts
132
 *
133
 * @return bool
134
 */
135
function search_index(&$data, $base, $file, $type, $lvl, $opts)
136
{
137
    global $conf;
138
    $opts = array(
139
        'pagesonly' => true,
140
        'listdirs' => true,
141
        'listfiles' => empty($opts['nofiles']),
142
        'sneakyacl' => $conf['sneaky_index'],
143
        // Hacky, should rather use recmatch
144
        'depth' => preg_match('#^'.preg_quote($file, '#').'(/|$)#','/'.$opts['ns']) ? 0 : -1
145
    );
146
147
    return search_universal($data, $base, $file, $type, $lvl, $opts);
148
}
149
150
/**
151
 * List all namespaces
152
 *
153
 * @author  Andreas Gohr <[email protected]>
154
 *
155
 * @param array $data
156
 * @param string $base
157
 * @param string $file
158
 * @param string $type
159
 * @param integer $lvl
160
 * @param array $opts
161
 *
162
 * @return bool
163
 */
164
function search_namespaces(&$data, $base, $file, $type, $lvl, $opts)
0 ignored issues
show
Unused Code introduced by
The parameter $opts is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
165
{
166
    $opts = array(
167
            'listdirs' => true,
168
            );
169
    return search_universal($data, $base, $file, $type, $lvl, $opts);
170
}
171
172
/**
173
 * List all mediafiles in a namespace
174
 *   $opts['depth']     recursion level, 0 for all
175
 *   $opts['showmsg']   shows message if invalid media id is used
176
 *   $opts['skipacl']   skip acl checking
177
 *   $opts['pattern']   check given pattern
178
 *   $opts['hash']      add hashes to result list
179
 *
180
 * @author  Andreas Gohr <[email protected]>
181
 *
182
 * @param array $data
183
 * @param string $base
184
 * @param string $file
185
 * @param string $type
186
 * @param integer $lvl
187
 * @param array $opts
188
 *
189
 * @return bool
190
 */
191
function search_media(&$data, $base, $file, $type, $lvl, $opts)
0 ignored issues
show
Unused Code introduced by
The parameter $lvl is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
192
{
193
    //we do nothing with directories
194
    if ($type == 'd') {
195
        if (empty($opts['depth'])) return true; // recurse forever
196
        $depth = substr_count($file,'/');
197
        if ($depth >= $opts['depth']) return false; // depth reached
198
        return true;
199
    }
200
201
    $info         = array();
202
    $info['id']   = pathID($file, true);
203
    if ($info['id'] != cleanID($info['id'])) {
204
        if ($opts['showmsg'])
205
            msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1);
206
        return false; // skip non-valid files
207
    }
208
209
    //check ACL for namespace (we have no ACL for mediafiles)
210
    $info['perm'] = auth_quickaclcheck(getNS($info['id']).':*');
211
    if (empty($opts['skipacl']) && $info['perm'] < AUTH_READ) {
212
        return false;
213
    }
214
215
    //check pattern filter
216
    if (!empty($opts['pattern']) && !@preg_match($opts['pattern'], $info['id'])) {
217
        return false;
218
    }
219
220
    $info['file']     = \dokuwiki\Utf8\PhpString::basename($file);
221
    $info['size']     = filesize($base.'/'.$file);
222
    $info['mtime']    = filemtime($base.'/'.$file);
223
    $info['writable'] = is_writable($base.'/'.$file);
224
    if (preg_match("/\.(jpe?g|gif|png)$/", $file)) {
225
        $info['isimg'] = true;
226
        $info['meta']  = new JpegMeta($base.'/'.$file);
227
    } else {
228
        $info['isimg'] = false;
229
    }
230
    if (!empty($opts['hash'])) {
231
        $info['hash'] = md5(io_readFile(mediaFN($info['id']), false));
232
    }
233
234
    $data[] = $info;
235
236
    return false;
237
}
238
239
/**
240
 * This function just lists documents (for RSS namespace export)
241
 *
242
 * @author  Andreas Gohr <[email protected]>
243
 *
244
 * @param array $data
245
 * @param string $base
246
 * @param string $file
247
 * @param string $type
248
 * @param integer $lvl
249
 * @param array $opts
250
 *
251
 * @return bool
252
 */
253
function search_list(&$data, $base, $file, $type, $lvl, $opts)
0 ignored issues
show
Unused Code introduced by
The parameter $base is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $lvl is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $opts is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
254
{
255
    //we do nothing with directories
256
    if ($type == 'd') return false;
257
    //only search txt files
258
    if (substr($file, -4) == '.txt') {
259
        //check ACL
260
        $id = pathID($file);
261
        if (auth_quickaclcheck($id) < AUTH_READ) {
262
            return false;
263
        }
264
        $data[]['id'] = $id;
265
    }
266
    return false;
267
}
268
269
/**
270
 * Quicksearch for searching matching pagenames
271
 *
272
 * $opts['query'] is the search query
273
 *
274
 * @author  Andreas Gohr <[email protected]>
275
 *
276
 * @param array $data
277
 * @param string $base
278
 * @param string $file
279
 * @param string $type
280
 * @param integer $lvl
281
 * @param array $opts
282
 *
283
 * @return bool
284
 */
285
function search_pagename(&$data, $base, $file, $type, $lvl, $opts)
0 ignored issues
show
Unused Code introduced by
The parameter $base is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $lvl is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
286
{
287
    //we do nothing with directories
288
    if ($type == 'd') return true;
289
    //only search txt files
290
    if (substr($file, -4) != '.txt') return true;
291
292
    //simple stringmatching
293
    if (!empty($opts['query'])) {
294
        if (strpos($file, $opts['query']) !== false) {
295
            //check ACL
296
            $id = pathID($file);
297
            if (auth_quickaclcheck($id) < AUTH_READ) {
298
                return false;
299
            }
300
            $data[]['id'] = $id;
301
        }
302
    }
303
    return true;
304
}
305
306
/**
307
 * Just lists all documents
308
 *
309
 * $opts['depth']   recursion level, 0 for all
310
 * $opts['hash']    do md5 sum of content?
311
 * $opts['skipacl'] list everything regardless of ACL
312
 *
313
 * @author  Andreas Gohr <[email protected]>
314
 *
315
 * @param array $data
316
 * @param string $base
317
 * @param string $file
318
 * @param string $type
319
 * @param integer $lvl
320
 * @param array $opts
321
 *
322
 * @return bool
323
 */
324
function search_allpages(&$data, $base, $file, $type, $lvl, $opts)
0 ignored issues
show
Unused Code introduced by
The parameter $lvl is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
325
{
326
    if (isset($opts['depth']) && $opts['depth']) {
327
        $parts = explode('/',ltrim($file, '/'));
328
        if (($type == 'd' && count($parts) >= $opts['depth'])
329
            || ($type != 'd' && count($parts) > $opts['depth'])
330
        ){
331
            return false; // depth reached
332
        }
333
    }
334
335
    //we do nothing with directories
336
    if ($type == 'd') {
337
        return true;
338
    }
339
340
    //only search txt files
341
    if (substr($file, -4) != '.txt') return true;
342
343
    $item = array();
344
    $item['id']   = pathID($file);
345
    if (empty($opts['skipacl']) && auth_quickaclcheck($item['id']) < AUTH_READ) {
346
        return false;
347
    }
348
349
    $item['rev']   = filemtime($base.'/'.$file);
350
    $item['mtime'] = $item['rev'];
351
    $item['size']  = filesize($base.'/'.$file);
352
    if (!empty($opts['hash'])) {
353
        $item['hash'] = md5(trim(rawWiki($item['id'])));
354
    }
355
356
    $data[] = $item;
357
    return true;
358
}
359
360
/* ------------- helper functions below -------------- */
361
362
/**
363
 * fulltext sort
364
 *
365
 * Callback sort function for use with usort to sort the data
366
 * structure created by search_fulltext. Sorts descending by count
367
 *
368
 * @author  Andreas Gohr <[email protected]>
369
 *
370
 * @param array $a
371
 * @param array $b
372
 *
373
 * @return int
374
 */
375
function sort_search_fulltext($a, $b)
376
{
377
    if ($a['count'] > $b['count']) {
378
        return -1;
379
    } elseif ($a['count'] < $b['count']) {
380
        return 1;
381
    }else{
382
        return Sort::strcmp($a['id'],$b['id']);
383
    }
384
}
385
386
/**
387
 * translates a document path to an ID
388
 *
389
 * @author  Andreas Gohr <[email protected]>
390
 * @todo    move to pageutils
391
 *
392
 * @param string $path
393
 * @param bool $keeptxt
394
 *
395
 * @return mixed|string
396
 */
397
function pathID($path, $keeptxt=false)
398
{
399
    $id = utf8_decodeFN($path);
400
    $id = str_replace('/', ':', $id);
401
    if (!$keeptxt) $id = preg_replace('#\.txt$#', '', $id);
402
    $id = trim($id, ':');
403
    return $id;
404
}
405
406
407
/**
408
 * This is a very universal callback for the search() function, replacing
409
 * many of the former individual functions at the cost of a more complex
410
 * setup.
411
 *
412
 * How the function behaves, depends on the options passed in the $opts
413
 * array, where the following settings can be used.
414
 *
415
 * depth      int     recursion depth. 0 for unlimited                       (default: 0)
416
 * keeptxt    bool    keep .txt extension for IDs                            (default: false)
417
 * listfiles  bool    include files in listing                               (default: false)
418
 * listdirs   bool    include namespaces in listing                          (default: false)
419
 * pagesonly  bool    restrict files to pages                                (default: false)
420
 * skipacl    bool    do not check for READ permission                       (default: false)
421
 * sneakyacl  bool    don't recurse into nonreadable dirs                    (default: false)
422
 * hash       bool    create MD5 hash for files                              (default: false)
423
 * meta       bool    return file metadata                                   (default: false)
424
 * filematch  string  match files against this regexp                        (default: '', so accept everything)
425
 * idmatch    string  match full ID against this regexp                      (default: '', so accept everything)
426
 * dirmatch   string  match directory against this regexp when adding        (default: '', so accept everything)
427
 * nsmatch    string  match namespace against this regexp when adding        (default: '', so accept everything)
428
 * recmatch   string  match directory against this regexp when recursing     (default: '', so accept everything)
429
 * showmsg    bool    warn about non-ID files                                (default: false)
430
 * showhidden bool    show hidden files(e.g. by hidepages config) too        (default: false)
431
 * firsthead  bool    return first heading for pages                         (default: false)
432
 *
433
 * @param array &$data  - Reference to the result data structure
434
 * @param string $base  - Base usually $conf['datadir']
435
 * @param string $file  - current file or directory relative to $base
436
 * @param string $type  - Type either 'd' for directory or 'f' for file
437
 * @param int    $lvl   - Current recursion depht
438
 * @param array  $opts  - option array as given to search()
439
 * @return bool if this directory should be traversed (true) or not (false)
440
 *              return value is ignored for files
441
 *
442
 * @author Andreas Gohr <[email protected]>
443
 */
444
function search_universal(&$data, $base, $file, $type, $lvl, $opts)
445
{
446
    $item   = array();
447
    $return = true;
448
449
    // get ID and check if it is a valid one
450
    $item['id'] = pathID($file, ($type == 'd' || !empty($opts['keeptxt'])));
451
    if ($item['id'] != cleanID($item['id'])){
452
        if (!empty($opts['showmsg'])) {
453
            msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped',-1);
454
        }
455
        return false; // skip non-valid files
456
    }
457
    $item['ns']  = getNS($item['id']);
458
459
    if ($type == 'd') {
460
        // decide if to recursion into this directory is wanted
461
        if (empty($opts['depth'])) {
462
            $return = true; // recurse forever
463
        } else {
464
            $depth = substr_count($file,'/');
465
            if ($depth >= $opts['depth']) {
466
                $return = false; // depth reached
467
            } else {
468
                $return = true;
469
            }
470
        }
471
472
        if ($return) {
473
            $match = empty($opts['recmatch']) || preg_match('/'.$opts['recmatch'].'/', $file);
474
            if (!$match) {
475
                return false; // doesn't match
476
            }
477
        }
478
    }
479
480
    // check ACL
481
    if (empty($opts['skipacl'])) {
482
        if ($type == 'd') {
483
            $item['perm'] = auth_quickaclcheck($item['id'].':*');
484
        } else {
485
            $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
486
        }
487
    } else {
488
        $item['perm'] = AUTH_DELETE;
489
    }
490
491
    // are we done here maybe?
492
    if ($type == 'd') {
493
        if (empty($opts['listdirs'])) return $return;
494
        //neither list nor recurse forbidden items:
495
        if (empty($opts['skipacl']) && !empty($opts['sneakyacl']) && $item['perm'] < AUTH_READ) return false;
496
        if (!empty($opts['dirmatch']) && !preg_match('/'.$opts['dirmatch'].'/', $file)) return $return;
497
        if (!empty($opts['nsmatch']) && !preg_match('/'.$opts['nsmatch'].'/', $item['ns'])) return $return;
498
    } else {
499
        if (empty($opts['listfiles'])) return $return;
500
        if (empty($opts['skipacl']) && $item['perm'] < AUTH_READ) return $return;
501
        if (!empty($opts['pagesonly']) && (substr($file, -4) != '.txt')) return $return;
502
        if (empty($opts['showhidden']) && isHiddenPage($item['id'])) return $return;
503
        if (!empty($opts['filematch']) && !preg_match('/'.$opts['filematch'].'/', $file)) return $return;
504
        if (!empty($opts['idmatch']) && !preg_match('/'.$opts['idmatch'].'/', $item['id'])) return $return;
505
    }
506
507
    // still here? prepare the item
508
    $item['type']  = $type;
509
    $item['level'] = $lvl;
510
    $item['open']  = $return;
511
512
    if (!empty($opts['meta'])) {
513
        $item['file']       = \dokuwiki\Utf8\PhpString::basename($file);
514
        $item['size']       = filesize($base.'/'.$file);
515
        $item['mtime']      = filemtime($base.'/'.$file);
516
        $item['rev']        = $item['mtime'];
517
        $item['writable']   = is_writable($base.'/'.$file);
518
        $item['executable'] = is_executable($base.'/'.$file);
519
    }
520
521
    if ($type == 'f') {
522
        if (!empty($opts['hash'])) $item['hash'] = md5(io_readFile($base.'/'.$file, false));
523
        if (!empty($opts['firsthead'])) {
524
            $item['title'] = p_get_first_heading($item['id'], METADATA_DONT_RENDER);
525
        }
526
    }
527
528
    // finally add the item
529
    $data[] = $item;
530
    return $return;
531
}
532
533
//Setup VIM: ex: et ts=4 :
534