[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/inc/ -> search.php (source)

   1  <?php
   2  /**
   3   * DokuWiki search functions
   4   *
   5   * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
   6   * @author     Andreas Gohr <andi@splitbrain.org>
   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 <andi@splitbrain.org>
  26   */
  27  function search(&$data,$base,$func,$opts,$dir='',$lvl=1,$sort='natural'){
  28      $dirs   = array();
  29      $files  = array();
  30      $filepaths = array();
  31  
  32      // safeguard against runaways #1452
  33      if($base == '' || $base == '/') {
  34          throw new RuntimeException('No valid $base passed to search() - possible misconfiguration or bug');
  35      }
  36  
  37      //read in directories and files
  38      $dh = @opendir($base.'/'.$dir);
  39      if(!$dh) return;
  40      while(($file = readdir($dh)) !== false){
  41          if(preg_match('/^[\._]/',$file)) continue; //skip hidden files and upper dirs
  42          if(is_dir($base.'/'.$dir.'/'.$file)){
  43              $dirs[] = $dir.'/'.$file;
  44              continue;
  45          }
  46          $files[] = $dir.'/'.$file;
  47          $filepaths[] = $base.'/'.$dir.'/'.$file;
  48      }
  49      closedir($dh);
  50      if (!empty($sort)) {
  51          if ($sort == 'date') {
  52              @array_multisort(array_map('filemtime', $filepaths), SORT_NUMERIC, SORT_DESC, $files);
  53          } else /* natural */ {
  54              Sort::asortFN($files);
  55          }
  56          Sort::asortFN($dirs);
  57      }
  58  
  59      //give directories to userfunction then recurse
  60      foreach($dirs as $dir){
  61          if (call_user_func_array($func, array(&$data,$base,$dir,'d',$lvl,$opts))){
  62              search($data,$base,$func,$opts,$dir,$lvl+1,$sort);
  63          }
  64      }
  65      //now handle the files
  66      foreach($files as $file){
  67          call_user_func_array($func, array(&$data,$base,$file,'f',$lvl,$opts));
  68      }
  69  }
  70  
  71  /**
  72   * The following functions are userfunctions to use with the search
  73   * function above. This function is called for every found file or
  74   * directory. When a directory is given to the function it has to
  75   * decide if this directory should be traversed (true) or not (false)
  76   * The function has to accept the following parameters:
  77   *
  78   * array &$data  - Reference to the result data structure
  79   * string $base  - Base usually $conf['datadir']
  80   * string $file  - current file or directory relative to $base
  81   * string $type  - Type either 'd' for directory or 'f' for file
  82   * int    $lvl   - Current recursion depht
  83   * array  $opts  - option array as given to search()
  84   *
  85   * return values for files are ignored
  86   *
  87   * All functions should check the ACL for document READ rights
  88   * namespaces (directories) are NOT checked (when sneaky_index is 0) as this
  89   * would break the recursion (You can have an nonreadable dir over a readable
  90   * one deeper nested) also make sure to check the file type (for example
  91   * in case of lockfiles).
  92   */
  93  
  94  /**
  95   * Searches for pages beginning with the given query
  96   *
  97   * @author Andreas Gohr <andi@splitbrain.org>
  98   *
  99   * @param array $data
 100   * @param string $base
 101   * @param string $file
 102   * @param string $type
 103   * @param integer $lvl
 104   * @param array $opts
 105   *
 106   * @return bool
 107   */
 108  function search_qsearch(&$data,$base,$file,$type,$lvl,$opts){
 109      $opts = array(
 110              'idmatch'   => '(^|:)'.preg_quote($opts['query'],'/').'/',
 111              'listfiles' => true,
 112              'pagesonly' => true,
 113              );
 114      return search_universal($data,$base,$file,$type,$lvl,$opts);
 115  }
 116  
 117  /**
 118   * Build the browsable index of pages
 119   *
 120   * $opts['ns'] is the currently viewed namespace
 121   *
 122   * @author  Andreas Gohr <andi@splitbrain.org>
 123   *
 124   * @param array $data
 125   * @param string $base
 126   * @param string $file
 127   * @param string $type
 128   * @param integer $lvl
 129   * @param array $opts
 130   *
 131   * @return bool
 132   */
 133  function search_index(&$data,$base,$file,$type,$lvl,$opts){
 134      global $conf;
 135      $opts = array(
 136          'pagesonly' => true,
 137          'listdirs' => true,
 138          'listfiles' => empty($opts['nofiles']),
 139          'sneakyacl' => $conf['sneaky_index'],
 140          // Hacky, should rather use recmatch
 141          'depth' => preg_match('#^'.preg_quote($file, '#').'(/|$)#','/'.$opts['ns']) ? 0 : -1
 142      );
 143  
 144      return search_universal($data, $base, $file, $type, $lvl, $opts);
 145  }
 146  
 147  /**
 148   * List all namespaces
 149   *
 150   * @author  Andreas Gohr <andi@splitbrain.org>
 151   *
 152   * @param array $data
 153   * @param string $base
 154   * @param string $file
 155   * @param string $type
 156   * @param integer $lvl
 157   * @param array $opts
 158   *
 159   * @return bool
 160   */
 161  function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){
 162      $opts = array(
 163              'listdirs' => true,
 164              );
 165      return search_universal($data,$base,$file,$type,$lvl,$opts);
 166  }
 167  
 168  /**
 169   * List all mediafiles in a namespace
 170   *   $opts['depth']     recursion level, 0 for all
 171   *   $opts['showmsg']   shows message if invalid media id is used
 172   *   $opts['skipacl']   skip acl checking
 173   *   $opts['pattern']   check given pattern
 174   *   $opts['hash']      add hashes to result list
 175   *
 176   * @author  Andreas Gohr <andi@splitbrain.org>
 177   *
 178   * @param array $data
 179   * @param string $base
 180   * @param string $file
 181   * @param string $type
 182   * @param integer $lvl
 183   * @param array $opts
 184   *
 185   * @return bool
 186   */
 187  function search_media(&$data,$base,$file,$type,$lvl,$opts){
 188  
 189      //we do nothing with directories
 190      if($type == 'd') {
 191          if(empty($opts['depth'])) return true; // recurse forever
 192          $depth = substr_count($file,'/');
 193          if($depth >= $opts['depth']) return false; // depth reached
 194          return true;
 195      }
 196  
 197      $info         = array();
 198      $info['id']   = pathID($file,true);
 199      if($info['id'] != cleanID($info['id'])){
 200          if($opts['showmsg'])
 201              msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1);
 202          return false; // skip non-valid files
 203      }
 204  
 205      //check ACL for namespace (we have no ACL for mediafiles)
 206      $info['perm'] = auth_quickaclcheck(getNS($info['id']).':*');
 207      if(empty($opts['skipacl']) && $info['perm'] < AUTH_READ){
 208          return false;
 209      }
 210  
 211      //check pattern filter
 212      if(!empty($opts['pattern']) && !@preg_match($opts['pattern'], $info['id'])){
 213          return false;
 214      }
 215  
 216      $info['file']     = \dokuwiki\Utf8\PhpString::basename($file);
 217      $info['size']     = filesize($base.'/'.$file);
 218      $info['mtime']    = filemtime($base.'/'.$file);
 219      $info['writable'] = is_writable($base.'/'.$file);
 220      if(preg_match("/\.(jpe?g|gif|png)$/",$file)){
 221          $info['isimg'] = true;
 222          $info['meta']  = new JpegMeta($base.'/'.$file);
 223      }else{
 224          $info['isimg'] = false;
 225      }
 226      if(!empty($opts['hash'])){
 227          $info['hash'] = md5(io_readFile(mediaFN($info['id']),false));
 228      }
 229  
 230      $data[] = $info;
 231  
 232      return false;
 233  }
 234  
 235  /**
 236   * This function just lists documents (for RSS namespace export)
 237   *
 238   * @author  Andreas Gohr <andi@splitbrain.org>
 239   *
 240   * @param array $data
 241   * @param string $base
 242   * @param string $file
 243   * @param string $type
 244   * @param integer $lvl
 245   * @param array $opts
 246   *
 247   * @return bool
 248   */
 249  function search_list(&$data,$base,$file,$type,$lvl,$opts){
 250      //we do nothing with directories
 251      if($type == 'd') return false;
 252      //only search txt files
 253      if(substr($file,-4) == '.txt'){
 254          //check ACL
 255          $id = pathID($file);
 256          if(auth_quickaclcheck($id) < AUTH_READ){
 257              return false;
 258          }
 259          $data[]['id'] = $id;
 260      }
 261      return false;
 262  }
 263  
 264  /**
 265   * Quicksearch for searching matching pagenames
 266   *
 267   * $opts['query'] is the search query
 268   *
 269   * @author  Andreas Gohr <andi@splitbrain.org>
 270   *
 271   * @param array $data
 272   * @param string $base
 273   * @param string $file
 274   * @param string $type
 275   * @param integer $lvl
 276   * @param array $opts
 277   *
 278   * @return bool
 279   */
 280  function search_pagename(&$data,$base,$file,$type,$lvl,$opts){
 281      //we do nothing with directories
 282      if($type == 'd') return true;
 283      //only search txt files
 284      if(substr($file,-4) != '.txt') return true;
 285  
 286      //simple stringmatching
 287      if (!empty($opts['query'])){
 288          if(strpos($file,$opts['query']) !== false){
 289              //check ACL
 290              $id = pathID($file);
 291              if(auth_quickaclcheck($id) < AUTH_READ){
 292                  return false;
 293              }
 294              $data[]['id'] = $id;
 295          }
 296      }
 297      return true;
 298  }
 299  
 300  /**
 301   * Just lists all documents
 302   *
 303   * $opts['depth']   recursion level, 0 for all
 304   * $opts['hash']    do md5 sum of content?
 305   * $opts['skipacl'] list everything regardless of ACL
 306   *
 307   * @author  Andreas Gohr <andi@splitbrain.org>
 308   *
 309   * @param array $data
 310   * @param string $base
 311   * @param string $file
 312   * @param string $type
 313   * @param integer $lvl
 314   * @param array $opts
 315   *
 316   * @return bool
 317   */
 318  function search_allpages(&$data,$base,$file,$type,$lvl,$opts){
 319      if(isset($opts['depth']) && $opts['depth']){
 320          $parts = explode('/',ltrim($file,'/'));
 321          if(($type == 'd' && count($parts) >= $opts['depth'])
 322            || ($type != 'd' && count($parts) > $opts['depth'])){
 323              return false; // depth reached
 324          }
 325      }
 326  
 327      //we do nothing with directories
 328      if($type == 'd'){
 329          return true;
 330      }
 331  
 332      //only search txt files
 333      if(substr($file,-4) != '.txt') return true;
 334  
 335      $item = array();
 336      $item['id']   = pathID($file);
 337      if(empty($opts['skipacl']) && auth_quickaclcheck($item['id']) < AUTH_READ){
 338          return false;
 339      }
 340  
 341      $item['rev']   = filemtime($base.'/'.$file);
 342      $item['mtime'] = $item['rev'];
 343      $item['size']  = filesize($base.'/'.$file);
 344      if(!empty($opts['hash'])){
 345          $item['hash'] = md5(trim(rawWiki($item['id'])));
 346      }
 347  
 348      $data[] = $item;
 349      return true;
 350  }
 351  
 352  /* ------------- helper functions below -------------- */
 353  
 354  /**
 355   * fulltext sort
 356   *
 357   * Callback sort function for use with usort to sort the data
 358   * structure created by search_fulltext. Sorts descending by count
 359   *
 360   * @author  Andreas Gohr <andi@splitbrain.org>
 361   *
 362   * @param array $a
 363   * @param array $b
 364   *
 365   * @return int
 366   */
 367  function sort_search_fulltext($a,$b){
 368      if($a['count'] > $b['count']){
 369          return -1;
 370      }elseif($a['count'] < $b['count']){
 371          return 1;
 372      }else{
 373          return Sort::strcmp($a['id'],$b['id']);
 374      }
 375  }
 376  
 377  /**
 378   * translates a document path to an ID
 379   *
 380   * @author  Andreas Gohr <andi@splitbrain.org>
 381   * @todo    move to pageutils
 382   *
 383   * @param string $path
 384   * @param bool $keeptxt
 385   *
 386   * @return mixed|string
 387   */
 388  function pathID($path,$keeptxt=false){
 389      $id = utf8_decodeFN($path);
 390      $id = str_replace('/',':',$id);
 391      if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id);
 392      $id = trim($id, ':');
 393      return $id;
 394  }
 395  
 396  
 397  /**
 398   * This is a very universal callback for the search() function, replacing
 399   * many of the former individual functions at the cost of a more complex
 400   * setup.
 401   *
 402   * How the function behaves, depends on the options passed in the $opts
 403   * array, where the following settings can be used.
 404   *
 405   * depth      int     recursion depth. 0 for unlimited                       (default: 0)
 406   * keeptxt    bool    keep .txt extension for IDs                            (default: false)
 407   * listfiles  bool    include files in listing                               (default: false)
 408   * listdirs   bool    include namespaces in listing                          (default: false)
 409   * pagesonly  bool    restrict files to pages                                (default: false)
 410   * skipacl    bool    do not check for READ permission                       (default: false)
 411   * sneakyacl  bool    don't recurse into nonreadable dirs                    (default: false)
 412   * hash       bool    create MD5 hash for files                              (default: false)
 413   * meta       bool    return file metadata                                   (default: false)
 414   * filematch  string  match files against this regexp                        (default: '', so accept everything)
 415   * idmatch    string  match full ID against this regexp                      (default: '', so accept everything)
 416   * dirmatch   string  match directory against this regexp when adding        (default: '', so accept everything)
 417   * nsmatch    string  match namespace against this regexp when adding        (default: '', so accept everything)
 418   * recmatch   string  match directory against this regexp when recursing     (default: '', so accept everything)
 419   * showmsg    bool    warn about non-ID files                                (default: false)
 420   * showhidden bool    show hidden files(e.g. by hidepages config) too        (default: false)
 421   * firsthead  bool    return first heading for pages                         (default: false)
 422   *
 423   * @param array &$data  - Reference to the result data structure
 424   * @param string $base  - Base usually $conf['datadir']
 425   * @param string $file  - current file or directory relative to $base
 426   * @param string $type  - Type either 'd' for directory or 'f' for file
 427   * @param int    $lvl   - Current recursion depht
 428   * @param array  $opts  - option array as given to search()
 429   * @return bool if this directory should be traversed (true) or not (false)
 430   *              return value is ignored for files
 431   *
 432   * @author Andreas Gohr <gohr@cosmocode.de>
 433   */
 434  function search_universal(&$data,$base,$file,$type,$lvl,$opts){
 435      $item   = array();
 436      $return = true;
 437  
 438      // get ID and check if it is a valid one
 439      $item['id'] = pathID($file,($type == 'd' || !empty($opts['keeptxt'])));
 440      if($item['id'] != cleanID($item['id'])){
 441          if(!empty($opts['showmsg'])){
 442              msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped',-1);
 443          }
 444          return false; // skip non-valid files
 445      }
 446      $item['ns']  = getNS($item['id']);
 447  
 448      if($type == 'd') {
 449          // decide if to recursion into this directory is wanted
 450          if(empty($opts['depth'])){
 451              $return = true; // recurse forever
 452          }else{
 453              $depth = substr_count($file,'/');
 454              if($depth >= $opts['depth']){
 455                  $return = false; // depth reached
 456              }else{
 457                  $return = true;
 458              }
 459          }
 460  
 461          if ($return) {
 462              $match = empty($opts['recmatch']) || preg_match('/'.$opts['recmatch'].'/',$file);
 463              if (!$match) {
 464                  return false; // doesn't match
 465              }
 466          }
 467      }
 468  
 469      // check ACL
 470      if(empty($opts['skipacl'])){
 471          if($type == 'd'){
 472              $item['perm'] = auth_quickaclcheck($item['id'].':*');
 473          }else{
 474              $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
 475          }
 476      }else{
 477          $item['perm'] = AUTH_DELETE;
 478      }
 479  
 480      // are we done here maybe?
 481      if($type == 'd'){
 482          if(empty($opts['listdirs'])) return $return;
 483          //neither list nor recurse forbidden items:
 484          if(empty($opts['skipacl']) && !empty($opts['sneakyacl']) && $item['perm'] < AUTH_READ) return false;
 485          if(!empty($opts['dirmatch']) && !preg_match('/'.$opts['dirmatch'].'/',$file)) return $return;
 486          if(!empty($opts['nsmatch']) && !preg_match('/'.$opts['nsmatch'].'/',$item['ns'])) return $return;
 487      }else{
 488          if(empty($opts['listfiles'])) return $return;
 489          if(empty($opts['skipacl']) && $item['perm'] < AUTH_READ) return $return;
 490          if(!empty($opts['pagesonly']) && (substr($file,-4) != '.txt')) return $return;
 491          if(empty($opts['showhidden']) && isHiddenPage($item['id'])) return $return;
 492          if(!empty($opts['filematch']) && !preg_match('/'.$opts['filematch'].'/',$file)) return $return;
 493          if(!empty($opts['idmatch']) && !preg_match('/'.$opts['idmatch'].'/',$item['id'])) return $return;
 494      }
 495  
 496      // still here? prepare the item
 497      $item['type']  = $type;
 498      $item['level'] = $lvl;
 499      $item['open']  = $return;
 500  
 501      if(!empty($opts['meta'])){
 502          $item['file']       = \dokuwiki\Utf8\PhpString::basename($file);
 503          $item['size']       = filesize($base.'/'.$file);
 504          $item['mtime']      = filemtime($base.'/'.$file);
 505          $item['rev']        = $item['mtime'];
 506          $item['writable']   = is_writable($base.'/'.$file);
 507          $item['executable'] = is_executable($base.'/'.$file);
 508      }
 509  
 510      if($type == 'f'){
 511          if(!empty($opts['hash'])) $item['hash'] = md5(io_readFile($base.'/'.$file,false));
 512          if(!empty($opts['firsthead'])) $item['title'] = p_get_first_heading($item['id'],METADATA_DONT_RENDER);
 513      }
 514  
 515      // finally add the item
 516      $data[] = $item;
 517      return $return;
 518  }
 519  
 520  //Setup VIM: ex: et ts=4 :