1 <?php # vim:ts=2:sw=2:et:
2 /* For licensing and copyright terms, see the file named LICENSE */
4 class MTrackSearchEngineSolr implements IMTrackSearchEngine {
7 public function __construct() {
8 $this->url = MTrackConfig::get('solr', 'url');
11 public function setBatchMode() {
19 'header' => 'Content-Type: text/xml',
22 $ctx = stream_context_create($params);
23 for ($i = 0; $i < 10; $i++) {
24 $fp = fopen("$this->url/update", 'rb', false, $ctx);
31 throw new Exception("unable to update index; is Solr running?\n$xml\n");
34 public function commit($optimize = false) {
35 $this->post('<optimize/>');
38 public function add($object, $fields, $replace = false) {
39 $xml = "<add overwrite='true'><doc><field name='id'>$object</field>";
40 foreach ($fields as $key => $value) {
41 if (!strlen($value)) continue;
42 if (!strncmp($key, 'stored:', 7)) {
43 $key = substr($key, 7);
49 $t = strtotime($value);
50 $value = date('Y-m-d\\TH:i:s', $t) . 'Z';
53 // avoid: HTTP/1.1 400 Illegal_character_CTRLCHAR_code_12
54 $value = str_replace("\x0c", " ", $value);
56 $xml .= "<field name='$key'>" .
57 htmlspecialchars($value, ENT_QUOTES, 'utf-8') .
60 $xml .= "</doc></add>";
65 /** returns an array of MTrackSearchResult objects corresponding
66 * to matches to the supplied query string */
67 public function search($query) {
68 $q = http_build_query(array(
73 'hl.usePhraseHighlighter' => 'on',
74 'hl.simple.pre' => "<span class='hl'>",
75 'hl.simple.post' => "</span>",
80 $json = file_get_contents("$this->url/select?$q");
81 $doc = json_decode($json);
82 //echo htmlentities($json);
86 /* look for excerpt text */
88 foreach ($doc->highlighting as $name => $arr) {
90 foreach ($arr as $fname => $v) {
97 foreach ($doc->response->docs as $doc) {
98 $r = new MTrackSearchResult;
99 $r->objectid = $doc->id;
100 $r->score = $doc->score;
102 if (isset($hl[$r->objectid])) {
103 $r->excerpt = "<div class='excerpt'>" .
104 join("\n", $hl[$r->objectid]) .