<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');

class action_plugin_autosearch extends DokuWiki_Action_Plugin {
  function getInfo(){
        return array(
            'author' => 'Ahmet Sacan',
            'email'  => 'ahmet@ceng.metu.edu.tr',
            'date'   => '2007-02-07',
            'name'   => 'Autosearch plugin',
            'desc'   => 'displays search results when a page does not exist',
            'url'    => 'http://www.ceng.metu.edu.tr/~ahmet',
        );
  }

  function register(&$contr){
    $contr->register_hook('ACTION_ACT_PREPROCESS',
                          'BEFORE',
                          $this,
                          'handle_act',
                           array());
  }
  function handle_act(&$e, $param){
    global $ID;
    if($e->data != 'show' || strpos($ID,'talk:')===0) return;

    if($_SERVER['REMOTE_USER'])
            $perm = auth_quickaclcheck($ID);
    else
            $perm = auth_aclcheck($ID,'',null);

    if(!is_file(wikiFN($ID))){
      $index_pages = explode(',',$this->getConf('index_pages'));
      foreach($index_pages as $index){
        if($index == '@subpage_with_same_name')
          $index = noNS($ID);
        if(is_file(wikiFN("$ID:$index"))){
            header("Location: ".wl("$ID:$index", $perm < AUTH_CREATE ? "" : "auto_search_indexed=1"));
            die();
        }
      }
      if($this->getConf('pagelist') && is_dir(dirname(wikiFN("$ID:dummy"))) && $indexmenu =& plugin_load('syntax', 'indexmenu')){
        $handled = $indexmenu->handle("{{indexmenu>$ID#2|js#default}}",null,null,$this);
        $dummy_renderer = (object) array('doc'=>'');
        $indexmenu->render('xhtml',$dummy_renderer, $handled);
        msg("Here are the subpages of [ $ID ]:<br>".$dummy_renderer->doc);

      }
      if($this->getConf('search'))
        $e->data = 'search';
    }
    elseif($_GET['auto_search_indexed']){
      $id = getNS($ID);
      msg("<a href='".wl(getNS($ID), "do=edit")."'>Click here</a> if you wanted to create the [ $id ] page.");
    }
  }
}
