1<?php 2/* 3 * To change this template, choose Tools | Templates 4 * and open the template in the editor. 5 */ 6 7class SphinxSearch 8{ 9 private $_sphinx = null; 10 private $_result = array(); 11 private $_index = null; 12 private $_query = ''; 13 public function __construct($host, $port, $index) 14 { 15 $this->_sphinx = new SphinxClient(); 16 $this->_sphinx->SetServer($host, $port); 17 $this->_sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); 18 $this->_sphinx->SetFieldWeights(array('categories' => 5, 'title' => 20, 'body' => 3)); 19 $this->_sphinx->SetFilter('level', array(1)); 20 21 $this->_index = $index; 22 } 23 24 public function search($keywords, $categories, $start, $resultsPerPage = 10) 25 { 26 $this->_sphinx->SetLimits($start, $resultsPerPage); 27 $query = ''; 28 if (!empty($keywords) && empty($categories)){ 29 $query = "@(body,title,categories) {$keywords}"; 30 } else { 31 $query = "@(body,title) {$keywords} @categories ".$categories; 32 } 33 $this->_query = $query; 34 $res = $this->_sphinx->Query($query, $this->_index); 35 $this->_result = $res; 36 if (empty($res['matches'])) { 37 return false; 38 } 39 40 $pageMapper = new PageMapper(); 41 42 $pageCrcList = array_keys($res['matches']); 43 $pagesIds = $pageMapper->getByCrc($pageCrcList); 44 45 $pagesList = array(); 46 $body = array(); 47 $title = array(); 48 $category = array(); 49 foreach ($pageCrcList as $crc){ 50 if (!empty($pagesIds[$crc]['hid'])){ 51 $bodyHtml = p_render('xhtml',p_get_instructions(getSection($pagesIds[$crc]['page'], $pagesIds[$crc]['title'])),$info); 52 } else { 53 $bodyHtml = p_wiki_xhtml($pagesIds[$crc]['page']); 54 } 55 $body[$crc] = strip_tags($bodyHtml); 56 $title[$crc] = strip_tags($pagesIds[$crc]['title']); 57 $category[$crc] = $pagesIds[$crc]['page']; 58 } 59 60 $starQuery = $this->starQuery($keywords); 61 $bodyExcerpt = $this->getExcerpt($body, $starQuery); 62 $titleExcerpt = $this->getExcerpt($title, $starQuery); 63 $i = 0; 64 $results = array(); 65 foreach($body as $crc => $notused){ 66 $results[$crc] = array( 67 'page' => $pagesIds[$crc]['page'], 68 'bodyExcerpt' => $bodyExcerpt[$i], 69 'titleExcerpt' => $titleExcerpt[$i], 70 'hid' => $pagesIds[$crc]['hid'], 71 'title' => $pagesIds[$crc]['title'] 72 ); 73 $i++; 74 } 75 return $results; 76 } 77 78 public function getTotalFound() 79 { 80 return !empty($this->_result['total_found'])?$this->_result['total_found'] : 0; 81 } 82 83 public function getExcerpt($data, $query) 84 { 85 return $this->_sphinx->BuildExcerpts($data, $this->_index, $query); 86 } 87 88 public function starQuery($query) 89 { 90 $words = explode(" ", $query); 91 $starQuery = ''; 92 foreach($words as $word){ 93 $starQuery .= "*".$word."* "; 94 } 95 return $starQuery; 96 } 97 98 public function getQuery() 99 { 100 return $this->_query; 101 } 102} 103