import
[web.mtrack] / inc / search.php
1 <?php # vim:ts=2:sw=2:et:
2 /* For licensing and copyright terms, see the file named LICENSE */
3
4 include MTRACK_INC_DIR . '/search/lucene.php';
5 include MTRACK_INC_DIR . '/search/solr.php';
6
7 class MTrackSearchResult {
8   /** object identifier of result */
9   public $objectid;
10   /** result ranking; higher is more relevant */
11   public $score;
12   /** excerpt of matching text */
13   public $excerpt;
14
15   /* some implementations may need the caller to provide the context
16    * text; the default just returns what is there */
17   function getExcerpt($text) {
18     return $this->excerpt;
19   }
20 }
21
22 interface IMTrackSearchEngine {
23   public function setBatchMode();
24   public function commit($optimize = false);
25   public function add($object, $fields, $replace = false);
26   /** returns an array of MTrackSearchResult objects corresponding
27    * to matches to the supplied query string */
28   public function search($query);
29 }
30
31 class MTrackSearchDB {
32   static $index = null;
33   static $engine = null;
34
35   static function getEngine() {
36     if (self::$engine === null) {
37       $name = MTrackConfig::get('core', 'search_engine');
38       if (!$name) $name = 'MTrackSearchEngineLucene';
39       self::$engine = new $name;
40     }
41     return self::$engine;
42   }
43
44   /* functions that can perform indexing */
45   static $funcs = array();
46
47   static function register_indexer($id, $func)
48   {
49     self::$funcs[$id] = $func;
50   }
51
52   static function index_object($id)
53   {
54     $key = $id;
55     while (strlen($key)) {
56       if (isset(self::$funcs[$key])) {
57         break;
58       }
59       $new_key = preg_replace('/:[^:]+$/', '', $key);
60       if ($key == $new_key) {
61         break;
62       }
63       $key = $new_key;
64     }
65
66     if (isset(self::$funcs[$key])) {
67       $func = self::$funcs[$key];
68       return call_user_func($func, $id);
69     }
70     return false;
71   }
72
73   static function get() {
74     return self::getEngine()->getIdx();
75   }
76
77   static function setBatchMode() {
78     self::getEngine()->setBatchMode();
79   }
80
81   static function commit($optimize = false) {
82     self::getEngine()->commit($optimize);
83   }
84
85   static function add($object, $fields, $replace = false) {
86     self::getEngine()->add($object, $fields, $replace);
87   }
88
89   static function search($query) {
90     return self::getEngine()->search($query);
91   }
92 }