Merge "Pass content to SearchUpdate rather than raw text"
[lhc/web/wiklou.git] / includes / search / SearchEngine.php
1 <?php
2 /**
3 * Basic search engine
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Search
22 */
23
24 /**
25 * @defgroup Search Search
26 */
27
28 /**
29 * Contain a class for special pages
30 * @ingroup Search
31 */
32 class SearchEngine {
33 var $limit = 10;
34 var $offset = 0;
35 var $prefix = '';
36 var $searchTerms = array();
37 var $namespaces = array( NS_MAIN );
38 var $showRedirects = false;
39
40 /// Feature values
41 protected $features = array();
42
43 /**
44 * @var DatabaseBase
45 */
46 protected $db;
47
48 function __construct( $db = null ) {
49 if ( $db ) {
50 $this->db = $db;
51 } else {
52 $this->db = wfGetDB( DB_SLAVE );
53 }
54 }
55
56 /**
57 * Perform a full text search query and return a result set.
58 * If title searches are not supported or disabled, return null.
59 * STUB
60 *
61 * @param string $term raw search term
62 * @return SearchResultSet|Status|null
63 */
64 function searchText( $term ) {
65 return null;
66 }
67
68 /**
69 * Perform a title-only search query and return a result set.
70 * If title searches are not supported or disabled, return null.
71 * STUB
72 *
73 * @param string $term raw search term
74 * @return SearchResultSet|null
75 */
76 function searchTitle( $term ) {
77 return null;
78 }
79
80 /**
81 * If this search backend can list/unlist redirects
82 * @deprecated since 1.18 Call supports( 'list-redirects' );
83 * @return bool
84 */
85 function acceptListRedirects() {
86 wfDeprecated( __METHOD__, '1.18' );
87 return $this->supports( 'list-redirects' );
88 }
89
90 /**
91 * @since 1.18
92 * @param $feature String
93 * @return Boolean
94 */
95 public function supports( $feature ) {
96 switch ( $feature ) {
97 case 'list-redirects':
98 return true;
99 case 'title-suffix-filter':
100 default:
101 return false;
102 }
103 }
104
105 /**
106 * Way to pass custom data for engines
107 * @since 1.18
108 * @param $feature String
109 * @param $data Mixed
110 * @return bool
111 */
112 public function setFeatureData( $feature, $data ) {
113 $this->features[$feature] = $data;
114 }
115
116 /**
117 * When overridden in derived class, performs database-specific conversions
118 * on text to be used for searching or updating search index.
119 * Default implementation does nothing (simply returns $string).
120 *
121 * @param string $string String to process
122 * @return string
123 */
124 public function normalizeText( $string ) {
125 global $wgContLang;
126
127 // Some languages such as Chinese require word segmentation
128 return $wgContLang->segmentByWord( $string );
129 }
130
131 /**
132 * Transform search term in cases when parts of the query came as different GET params (when supported)
133 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
134 */
135 function transformSearchTerm( $term ) {
136 return $term;
137 }
138
139 /**
140 * If an exact title match can be found, or a very slightly close match,
141 * return the title. If no match, returns NULL.
142 *
143 * @param $searchterm String
144 * @return Title
145 */
146 public static function getNearMatch( $searchterm ) {
147 $title = self::getNearMatchInternal( $searchterm );
148
149 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
150 return $title;
151 }
152
153 /**
154 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
155 * SearchResultSet.
156 *
157 * @param $searchterm string
158 * @return SearchResultSet
159 */
160 public static function getNearMatchResultSet( $searchterm ) {
161 return new SearchNearMatchResultSet( self::getNearMatch( $searchterm ) );
162 }
163
164 /**
165 * Really find the title match.
166 * @return null|Title
167 */
168 private static function getNearMatchInternal( $searchterm ) {
169 global $wgContLang, $wgEnableSearchContributorsByIP;
170
171 $allSearchTerms = array( $searchterm );
172
173 if ( $wgContLang->hasVariants() ) {
174 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
175 }
176
177 $titleResult = null;
178 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
179 return $titleResult;
180 }
181
182 foreach ( $allSearchTerms as $term ) {
183
184 # Exact match? No need to look further.
185 $title = Title::newFromText( $term );
186 if ( is_null( $title ) ) {
187 return null;
188 }
189
190 # Try files if searching in the Media: namespace
191 if ( $title->getNamespace() == NS_MEDIA ) {
192 $title = Title::makeTitle( NS_FILE, $title->getText() );
193 }
194
195 if ( $title->isSpecialPage() || $title->isExternal() || $title->exists() ) {
196 return $title;
197 }
198
199 # See if it still otherwise has content is some sane sense
200 $page = WikiPage::factory( $title );
201 if ( $page->hasViewableContent() ) {
202 return $title;
203 }
204
205 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
206 return $title;
207 }
208
209 # Now try all lower case (i.e. first letter capitalized)
210 $title = Title::newFromText( $wgContLang->lc( $term ) );
211 if ( $title && $title->exists() ) {
212 return $title;
213 }
214
215 # Now try capitalized string
216 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
217 if ( $title && $title->exists() ) {
218 return $title;
219 }
220
221 # Now try all upper case
222 $title = Title::newFromText( $wgContLang->uc( $term ) );
223 if ( $title && $title->exists() ) {
224 return $title;
225 }
226
227 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
228 $title = Title::newFromText( $wgContLang->ucwordbreaks( $term ) );
229 if ( $title && $title->exists() ) {
230 return $title;
231 }
232
233 // Give hooks a chance at better match variants
234 $title = null;
235 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
236 return $title;
237 }
238 }
239
240 $title = Title::newFromText( $searchterm );
241
242 # Entering an IP address goes to the contributions page
243 if ( $wgEnableSearchContributorsByIP ) {
244 if ( ( $title->getNamespace() == NS_USER && User::isIP( $title->getText() ) )
245 || User::isIP( trim( $searchterm ) ) ) {
246 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
247 }
248 }
249
250 # Entering a user goes to the user page whether it's there or not
251 if ( $title->getNamespace() == NS_USER ) {
252 return $title;
253 }
254
255 # Go to images that exist even if there's no local page.
256 # There may have been a funny upload, or it may be on a shared
257 # file repository such as Wikimedia Commons.
258 if ( $title->getNamespace() == NS_FILE ) {
259 $image = wfFindFile( $title );
260 if ( $image ) {
261 return $title;
262 }
263 }
264
265 # MediaWiki namespace? Page may be "implied" if not customized.
266 # Just return it, with caps forced as the message system likes it.
267 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
268 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
269 }
270
271 # Quoted term? Try without the quotes...
272 $matches = array();
273 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
274 return SearchEngine::getNearMatch( $matches[1] );
275 }
276
277 return null;
278 }
279
280 public static function legalSearchChars() {
281 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
282 }
283
284 /**
285 * Set the maximum number of results to return
286 * and how many to skip before returning the first.
287 *
288 * @param $limit Integer
289 * @param $offset Integer
290 */
291 function setLimitOffset( $limit, $offset = 0 ) {
292 $this->limit = intval( $limit );
293 $this->offset = intval( $offset );
294 }
295
296 /**
297 * Set which namespaces the search should include.
298 * Give an array of namespace index numbers.
299 *
300 * @param $namespaces Array
301 */
302 function setNamespaces( $namespaces ) {
303 $this->namespaces = $namespaces;
304 }
305
306 /**
307 * Parse some common prefixes: all (search everything)
308 * or namespace names
309 *
310 * @param $query String
311 * @return string
312 */
313 function replacePrefixes( $query ) {
314 global $wgContLang;
315
316 $parsed = $query;
317 if ( strpos( $query, ':' ) === false ) { // nothing to do
318 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
319 return $parsed;
320 }
321
322 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
323 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
324 $this->namespaces = null;
325 $parsed = substr( $query, strlen( $allkeyword ) );
326 } elseif ( strpos( $query, ':' ) !== false ) {
327 $prefix = substr( $query, 0, strpos( $query, ':' ) );
328 $index = $wgContLang->getNsIndex( $prefix );
329 if ( $index !== false ) {
330 $this->namespaces = array( $index );
331 $parsed = substr( $query, strlen( $prefix ) + 1 );
332 }
333 }
334 if ( trim( $parsed ) == '' ) {
335 $parsed = $query; // prefix was the whole query
336 }
337
338 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
339
340 return $parsed;
341 }
342
343 /**
344 * Make a list of searchable namespaces and their canonical names.
345 * @return Array
346 */
347 public static function searchableNamespaces() {
348 global $wgContLang;
349 $arr = array();
350 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
351 if ( $ns >= NS_MAIN ) {
352 $arr[$ns] = $name;
353 }
354 }
355
356 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
357 return $arr;
358 }
359
360 /**
361 * Extract default namespaces to search from the given user's
362 * settings, returning a list of index numbers.
363 *
364 * @param $user User
365 * @return Array
366 */
367 public static function userNamespaces( $user ) {
368 global $wgSearchEverythingOnlyLoggedIn;
369
370 $searchableNamespaces = SearchEngine::searchableNamespaces();
371
372 // get search everything preference, that can be set to be read for logged-in users
373 // it overrides other options
374 if ( !$wgSearchEverythingOnlyLoggedIn || $user->isLoggedIn() ) {
375 if ( $user->getOption( 'searcheverything' ) ) {
376 return array_keys( $searchableNamespaces );
377 }
378 }
379
380 $arr = array();
381 foreach ( $searchableNamespaces as $ns => $name ) {
382 if ( $user->getOption( 'searchNs' . $ns ) ) {
383 $arr[] = $ns;
384 }
385 }
386
387 return $arr;
388 }
389
390 /**
391 * Find snippet highlight settings for all users
392 *
393 * @return Array contextlines, contextchars
394 */
395 public static function userHighlightPrefs() {
396 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
397 $contextchars = 75; // same as above.... :P
398 return array( $contextlines, $contextchars );
399 }
400
401 /**
402 * An array of namespaces indexes to be searched by default
403 *
404 * @return Array
405 */
406 public static function defaultNamespaces() {
407 global $wgNamespacesToBeSearchedDefault;
408
409 return array_keys( $wgNamespacesToBeSearchedDefault, true );
410 }
411
412 /**
413 * Get a list of namespace names useful for showing in tooltips
414 * and preferences
415 *
416 * @param $namespaces Array
417 * @return array
418 */
419 public static function namespacesAsText( $namespaces ) {
420 global $wgContLang;
421
422 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
423 foreach ( $formatted as $key => $ns ) {
424 if ( empty( $ns ) ) {
425 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
426 }
427 }
428 return $formatted;
429 }
430
431 /**
432 * Return the help namespaces to be shown on Special:Search
433 *
434 * @return Array
435 */
436 public static function helpNamespaces() {
437 global $wgNamespacesToBeSearchedHelp;
438
439 return array_keys( $wgNamespacesToBeSearchedHelp, true );
440 }
441
442 /**
443 * Return a 'cleaned up' search string
444 *
445 * @param $text String
446 * @return String
447 */
448 function filter( $text ) {
449 $lc = $this->legalSearchChars();
450 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
451 }
452 /**
453 * Load up the appropriate search engine class for the currently
454 * active database backend, and return a configured instance.
455 *
456 * @return SearchEngine
457 */
458 public static function create() {
459 global $wgSearchType;
460 $dbr = null;
461 if ( $wgSearchType ) {
462 $class = $wgSearchType;
463 } else {
464 $dbr = wfGetDB( DB_SLAVE );
465 $class = $dbr->getSearchEngine();
466 }
467 $search = new $class( $dbr );
468 $search->setLimitOffset( 0, 0 );
469 return $search;
470 }
471
472 /**
473 * Create or update the search index record for the given page.
474 * Title and text should be pre-processed.
475 * STUB
476 *
477 * @param $id Integer
478 * @param $title String
479 * @param $text String
480 */
481 function update( $id, $title, $text ) {
482 // no-op
483 }
484
485 /**
486 * Update a search index record's title only.
487 * Title should be pre-processed.
488 * STUB
489 *
490 * @param $id Integer
491 * @param $title String
492 */
493 function updateTitle( $id, $title ) {
494 // no-op
495 }
496
497 /**
498 * Delete an indexed page
499 * Title should be pre-processed.
500 * STUB
501 *
502 * @param Integer $id Page id that was deleted
503 * @param String $title Title of page that was deleted
504 */
505 function delete( $id, $title ) {
506 // no-op
507 }
508
509 /**
510 * Get OpenSearch suggestion template
511 *
512 * @return String
513 */
514 public static function getOpenSearchTemplate() {
515 global $wgOpenSearchTemplate, $wgCanonicalServer;
516 if ( $wgOpenSearchTemplate ) {
517 return $wgOpenSearchTemplate;
518 } else {
519 $ns = implode( '|', SearchEngine::defaultNamespaces() );
520 if ( !$ns ) {
521 $ns = "0";
522 }
523 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
524 }
525 }
526 }
527
528 /**
529 * @ingroup Search
530 */
531 class SearchResultSet {
532 /**
533 * Fetch an array of regular expression fragments for matching
534 * the search terms as parsed by this engine in a text extract.
535 * STUB
536 *
537 * @return Array
538 */
539 function termMatches() {
540 return array();
541 }
542
543 function numRows() {
544 return 0;
545 }
546
547 /**
548 * Return true if results are included in this result set.
549 * STUB
550 *
551 * @return Boolean
552 */
553 function hasResults() {
554 return false;
555 }
556
557 /**
558 * Some search modes return a total hit count for the query
559 * in the entire article database. This may include pages
560 * in namespaces that would not be matched on the given
561 * settings.
562 *
563 * Return null if no total hits number is supported.
564 *
565 * @return Integer
566 */
567 function getTotalHits() {
568 return null;
569 }
570
571 /**
572 * Some search modes return a suggested alternate term if there are
573 * no exact hits. Returns true if there is one on this set.
574 *
575 * @return Boolean
576 */
577 function hasSuggestion() {
578 return false;
579 }
580
581 /**
582 * @return String: suggested query, null if none
583 */
584 function getSuggestionQuery() {
585 return null;
586 }
587
588 /**
589 * @return String: HTML highlighted suggested query, '' if none
590 */
591 function getSuggestionSnippet() {
592 return '';
593 }
594
595 /**
596 * Return information about how and from where the results were fetched,
597 * should be useful for diagnostics and debugging
598 *
599 * @return String
600 */
601 function getInfo() {
602 return null;
603 }
604
605 /**
606 * Return a result set of hits on other (multiple) wikis associated with this one
607 *
608 * @return SearchResultSet
609 */
610 function getInterwikiResults() {
611 return null;
612 }
613
614 /**
615 * Check if there are results on other wikis
616 *
617 * @return Boolean
618 */
619 function hasInterwikiResults() {
620 return $this->getInterwikiResults() != null;
621 }
622
623 /**
624 * Fetches next search result, or false.
625 * STUB
626 *
627 * @return SearchResult
628 */
629 function next() {
630 return false;
631 }
632
633 /**
634 * Frees the result set, if applicable.
635 */
636 function free() {
637 // ...
638 }
639 }
640
641 /**
642 * This class is used for different SQL-based search engines shipped with MediaWiki
643 */
644 class SqlSearchResultSet extends SearchResultSet {
645
646 protected $mResultSet;
647
648 function __construct( $resultSet, $terms ) {
649 $this->mResultSet = $resultSet;
650 $this->mTerms = $terms;
651 }
652
653 function termMatches() {
654 return $this->mTerms;
655 }
656
657 function numRows() {
658 if ( $this->mResultSet === false ) {
659 return false;
660 }
661
662 return $this->mResultSet->numRows();
663 }
664
665 function next() {
666 if ( $this->mResultSet === false ) {
667 return false;
668 }
669
670 $row = $this->mResultSet->fetchObject();
671 if ( $row === false ) {
672 return false;
673 }
674
675 return SearchResult::newFromRow( $row );
676 }
677
678 function free() {
679 if ( $this->mResultSet === false ) {
680 return false;
681 }
682
683 $this->mResultSet->free();
684 }
685 }
686
687 /**
688 * @ingroup Search
689 */
690 class SearchResultTooMany {
691 # # Some search engines may bail out if too many matches are found
692 }
693
694 /**
695 * @todo FIXME: This class is horribly factored. It would probably be better to
696 * have a useful base class to which you pass some standard information, then
697 * let the fancy self-highlighters extend that.
698 * @ingroup Search
699 */
700 class SearchResult {
701
702 /**
703 * @var Revision
704 */
705 var $mRevision = null;
706 var $mImage = null;
707
708 /**
709 * @var Title
710 */
711 var $mTitle;
712
713 /**
714 * @var String
715 */
716 var $mText;
717
718 /**
719 * Return a new SearchResult and initializes it with a title.
720 *
721 * @param $title Title
722 * @return SearchResult
723 */
724 public static function newFromTitle( $title ) {
725 $result = new self();
726 $result->initFromTitle( $title );
727 return $result;
728 }
729 /**
730 * Return a new SearchResult and initializes it with a row.
731 *
732 * @param $row object
733 * @return SearchResult
734 */
735 public static function newFromRow( $row ) {
736 $result = new self();
737 $result->initFromRow( $row );
738 return $result;
739 }
740
741 public function __construct( $row = null ) {
742 if ( !is_null( $row ) ) {
743 // Backwards compatibility with pre-1.17 callers
744 $this->initFromRow( $row );
745 }
746 }
747
748 /**
749 * Initialize from a database row. Makes a Title and passes that to
750 * initFromTitle.
751 *
752 * @param $row object
753 */
754 protected function initFromRow( $row ) {
755 $this->initFromTitle( Title::makeTitle( $row->page_namespace, $row->page_title ) );
756 }
757
758 /**
759 * Initialize from a Title and if possible initializes a corresponding
760 * Revision and File.
761 *
762 * @param $title Title
763 */
764 protected function initFromTitle( $title ) {
765 $this->mTitle = $title;
766 if ( !is_null( $this->mTitle ) ) {
767 $id = false;
768 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
769 $this->mRevision = Revision::newFromTitle(
770 $this->mTitle, $id, Revision::READ_NORMAL );
771 if ( $this->mTitle->getNamespace() === NS_FILE ) {
772 $this->mImage = wfFindFile( $this->mTitle );
773 }
774 }
775 }
776
777 /**
778 * Check if this is result points to an invalid title
779 *
780 * @return Boolean
781 */
782 function isBrokenTitle() {
783 if ( is_null( $this->mTitle ) ) {
784 return true;
785 }
786 return false;
787 }
788
789 /**
790 * Check if target page is missing, happens when index is out of date
791 *
792 * @return Boolean
793 */
794 function isMissingRevision() {
795 return !$this->mRevision && !$this->mImage;
796 }
797
798 /**
799 * @return Title
800 */
801 function getTitle() {
802 return $this->mTitle;
803 }
804
805 /**
806 * @return float|null if not supported
807 */
808 function getScore() {
809 return null;
810 }
811
812 /**
813 * Lazy initialization of article text from DB
814 */
815 protected function initText() {
816 if ( !isset( $this->mText ) ) {
817 if ( $this->mRevision != null ) {
818 //TODO: if we could plug in some code that knows about special content models *and* about
819 // special features of the search engine, the search could benefit. See similar
820 // comment in SearchUpdate's constructor
821 $content = $this->mRevision->getContent();
822 $this->mText = $content ? $content->getTextForSearchIndex() : '';
823 } else { // TODO: can we fetch raw wikitext for commons images?
824 $this->mText = '';
825 }
826 }
827 }
828
829 /**
830 * @param array $terms terms to highlight
831 * @return String: highlighted text snippet, null (and not '') if not supported
832 */
833 function getTextSnippet( $terms ) {
834 global $wgUser, $wgAdvancedSearchHighlighting;
835 $this->initText();
836
837 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
838 list( $contextlines, $contextchars ) = SearchEngine::userHighlightPrefs( $wgUser );
839 $h = new SearchHighlighter();
840 if ( $wgAdvancedSearchHighlighting ) {
841 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
842 } else {
843 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
844 }
845 }
846
847 /**
848 * @param array $terms terms to highlight
849 * @return String: highlighted title, '' if not supported
850 */
851 function getTitleSnippet( $terms ) {
852 return '';
853 }
854
855 /**
856 * @param array $terms terms to highlight
857 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
858 */
859 function getRedirectSnippet( $terms ) {
860 return '';
861 }
862
863 /**
864 * @return Title object for the redirect to this page, null if none or not supported
865 */
866 function getRedirectTitle() {
867 return null;
868 }
869
870 /**
871 * @return string highlighted relevant section name, null if none or not supported
872 */
873 function getSectionSnippet() {
874 return '';
875 }
876
877 /**
878 * @return Title object (pagename+fragment) for the section, null if none or not supported
879 */
880 function getSectionTitle() {
881 return null;
882 }
883
884 /**
885 * @return String: timestamp
886 */
887 function getTimestamp() {
888 if ( $this->mRevision ) {
889 return $this->mRevision->getTimestamp();
890 } elseif ( $this->mImage ) {
891 return $this->mImage->getTimestamp();
892 }
893 return '';
894 }
895
896 /**
897 * @return Integer: number of words
898 */
899 function getWordCount() {
900 $this->initText();
901 return str_word_count( $this->mText );
902 }
903
904 /**
905 * @return Integer: size in bytes
906 */
907 function getByteSize() {
908 $this->initText();
909 return strlen( $this->mText );
910 }
911
912 /**
913 * @return Boolean if hit has related articles
914 */
915 function hasRelated() {
916 return false;
917 }
918
919 /**
920 * @return String: interwiki prefix of the title (return iw even if title is broken)
921 */
922 function getInterwikiPrefix() {
923 return '';
924 }
925 }
926 /**
927 * A SearchResultSet wrapper for SearchEngine::getNearMatch
928 */
929 class SearchNearMatchResultSet extends SearchResultSet {
930 private $fetched = false;
931 /**
932 * @param $match mixed Title if matched, else null
933 */
934 public function __construct( $match ) {
935 $this->result = $match;
936 }
937 public function hasResult() {
938 return (bool)$this->result;
939 }
940 public function numRows() {
941 return $this->hasResults() ? 1 : 0;
942 }
943 public function next() {
944 if ( $this->fetched || !$this->result ) {
945 return false;
946 }
947 $this->fetched = true;
948 return SearchResult::newFromTitle( $this->result );
949 }
950 }
951
952 /**
953 * Highlight bits of wikitext
954 *
955 * @ingroup Search
956 */
957 class SearchHighlighter {
958 var $mCleanWikitext = true;
959
960 function __construct( $cleanupWikitext = true ) {
961 $this->mCleanWikitext = $cleanupWikitext;
962 }
963
964 /**
965 * Default implementation of wikitext highlighting
966 *
967 * @param $text String
968 * @param array $terms terms to highlight (unescaped)
969 * @param $contextlines Integer
970 * @param $contextchars Integer
971 * @return String
972 */
973 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
974 global $wgContLang;
975 global $wgSearchHighlightBoundaries;
976 $fname = __METHOD__;
977
978 if ( $text == '' ) {
979 return '';
980 }
981
982 // spli text into text + templates/links/tables
983 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
984 // first capture group is for detecting nested templates/links/tables/references
985 $endPatterns = array(
986 1 => '/(\{\{)|(\}\})/', // template
987 2 => '/(\[\[)|(\]\])/', // image
988 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
989
990 // @todo FIXME: This should prolly be a hook or something
991 if ( function_exists( 'wfCite' ) ) {
992 $spat .= '|(<ref>)'; // references via cite extension
993 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
994 }
995 $spat .= '/';
996 $textExt = array(); // text extracts
997 $otherExt = array(); // other extracts
998 wfProfileIn( "$fname-split" );
999 $start = 0;
1000 $textLen = strlen( $text );
1001 $count = 0; // sequence number to maintain ordering
1002 while ( $start < $textLen ) {
1003 // find start of template/image/table
1004 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
1005 $epat = '';
1006 foreach ( $matches as $key => $val ) {
1007 if ( $key > 0 && $val[1] != - 1 ) {
1008 if ( $key == 2 ) {
1009 // see if this is an image link
1010 $ns = substr( $val[0], 2, - 1 );
1011 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE ) {
1012 break;
1013 }
1014
1015 }
1016 $epat = $endPatterns[$key];
1017 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1018 $start = $val[1];
1019 break;
1020 }
1021 }
1022 if ( $epat ) {
1023 // find end (and detect any nested elements)
1024 $level = 0;
1025 $offset = $start + 1;
1026 $found = false;
1027 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
1028 if ( array_key_exists( 2, $endMatches ) ) {
1029 // found end
1030 if ( $level == 0 ) {
1031 $len = strlen( $endMatches[2][0] );
1032 $off = $endMatches[2][1];
1033 $this->splitAndAdd( $otherExt, $count,
1034 substr( $text, $start, $off + $len - $start ) );
1035 $start = $off + $len;
1036 $found = true;
1037 break;
1038 } else {
1039 // end of nested element
1040 $level -= 1;
1041 }
1042 } else {
1043 // nested
1044 $level += 1;
1045 }
1046 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
1047 }
1048 if ( ! $found ) {
1049 // couldn't find appropriate closing tag, skip
1050 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1051 $start += strlen( $matches[0][0] );
1052 }
1053 continue;
1054 }
1055 }
1056 // else: add as text extract
1057 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1058 break;
1059 }
1060
1061 $all = $textExt + $otherExt; // these have disjunct key sets
1062
1063 wfProfileOut( "$fname-split" );
1064
1065 // prepare regexps
1066 foreach ( $terms as $index => $term ) {
1067 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1068 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1069 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1070 } else {
1071 $terms[$index] = $term;
1072 }
1073 }
1074 $anyterm = implode( '|', $terms );
1075 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1076
1077 // @todo FIXME: A hack to scale contextchars, a correct solution
1078 // would be to have contextchars actually be char and not byte
1079 // length, and do proper utf-8 substrings and lengths everywhere,
1080 // but PHP is making that very hard and unclean to implement :(
1081 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1082 $contextchars = intval( $contextchars * $scale );
1083
1084 $patPre = "(^|$wgSearchHighlightBoundaries)";
1085 $patPost = "($wgSearchHighlightBoundaries|$)";
1086
1087 $pat1 = "/(" . $phrase . ")/ui";
1088 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1089
1090 wfProfileIn( "$fname-extract" );
1091
1092 $left = $contextlines;
1093
1094 $snippets = array();
1095 $offsets = array();
1096
1097 // show beginning only if it contains all words
1098 $first = 0;
1099 $firstText = '';
1100 foreach ( $textExt as $index => $line ) {
1101 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1102 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1103 $first = $index;
1104 break;
1105 }
1106 }
1107 if ( $firstText ) {
1108 $succ = true;
1109 // check if first text contains all terms
1110 foreach ( $terms as $term ) {
1111 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1112 $succ = false;
1113 break;
1114 }
1115 }
1116 if ( $succ ) {
1117 $snippets[$first] = $firstText;
1118 $offsets[$first] = 0;
1119 }
1120 }
1121 if ( ! $snippets ) {
1122 // match whole query on text
1123 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1124 // match whole query on templates/tables/images
1125 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1126 // match any words on text
1127 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1128 // match any words on templates/tables/images
1129 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1130
1131 ksort( $snippets );
1132 }
1133
1134 // add extra chars to each snippet to make snippets constant size
1135 $extended = array();
1136 if ( count( $snippets ) == 0 ) {
1137 // couldn't find the target words, just show beginning of article
1138 if ( array_key_exists( $first, $all ) ) {
1139 $targetchars = $contextchars * $contextlines;
1140 $snippets[$first] = '';
1141 $offsets[$first] = 0;
1142 }
1143 } else {
1144 // if begin of the article contains the whole phrase, show only that !!
1145 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1146 && $offsets[$first] < $contextchars * 2 ) {
1147 $snippets = array( $first => $snippets[$first] );
1148 }
1149
1150 // calc by how much to extend existing snippets
1151 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1152 }
1153
1154 foreach ( $snippets as $index => $line ) {
1155 $extended[$index] = $line;
1156 $len = strlen( $line );
1157 if ( $len < $targetchars - 20 ) {
1158 // complete this line
1159 if ( $len < strlen( $all[$index] ) ) {
1160 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] + $targetchars, $offsets[$index] );
1161 $len = strlen( $extended[$index] );
1162 }
1163
1164 // add more lines
1165 $add = $index + 1;
1166 while ( $len < $targetchars - 20
1167 && array_key_exists( $add, $all )
1168 && !array_key_exists( $add, $snippets ) ) {
1169 $offsets[$add] = 0;
1170 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1171 $extended[$add] = $tt;
1172 $len += strlen( $tt );
1173 $add++;
1174 }
1175 }
1176 }
1177
1178 // $snippets = array_map( 'htmlspecialchars', $extended );
1179 $snippets = $extended;
1180 $last = - 1;
1181 $extract = '';
1182 foreach ( $snippets as $index => $line ) {
1183 if ( $last == - 1 ) {
1184 $extract .= $line; // first line
1185 } elseif ( $last + 1 == $index && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1186 $extract .= " " . $line; // continous lines
1187 } else {
1188 $extract .= '<b> ... </b>' . $line;
1189 }
1190
1191 $last = $index;
1192 }
1193 if ( $extract ) {
1194 $extract .= '<b> ... </b>';
1195 }
1196
1197 $processed = array();
1198 foreach ( $terms as $term ) {
1199 if ( ! isset( $processed[$term] ) ) {
1200 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1201 $extract = preg_replace( $pat3,
1202 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1203 $processed[$term] = true;
1204 }
1205 }
1206
1207 wfProfileOut( "$fname-extract" );
1208
1209 return $extract;
1210 }
1211
1212 /**
1213 * Split text into lines and add it to extracts array
1214 *
1215 * @param array $extracts index -> $line
1216 * @param $count Integer
1217 * @param $text String
1218 */
1219 function splitAndAdd( &$extracts, &$count, $text ) {
1220 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
1221 foreach ( $split as $line ) {
1222 $tt = trim( $line );
1223 if ( $tt ) {
1224 $extracts[$count++] = $tt;
1225 }
1226 }
1227 }
1228
1229 /**
1230 * Do manual case conversion for non-ascii chars
1231 *
1232 * @param $matches Array
1233 * @return string
1234 */
1235 function caseCallback( $matches ) {
1236 global $wgContLang;
1237 if ( strlen( $matches[0] ) > 1 ) {
1238 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1239 } else {
1240 return $matches[0];
1241 }
1242 }
1243
1244 /**
1245 * Extract part of the text from start to end, but by
1246 * not chopping up words
1247 * @param $text String
1248 * @param $start Integer
1249 * @param $end Integer
1250 * @param $posStart Integer: (out) actual start position
1251 * @param $posEnd Integer: (out) actual end position
1252 * @return String
1253 */
1254 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1255 if ( $start != 0 ) {
1256 $start = $this->position( $text, $start, 1 );
1257 }
1258 if ( $end >= strlen( $text ) ) {
1259 $end = strlen( $text );
1260 } else {
1261 $end = $this->position( $text, $end );
1262 }
1263
1264 if ( !is_null( $posStart ) ) {
1265 $posStart = $start;
1266 }
1267 if ( !is_null( $posEnd ) ) {
1268 $posEnd = $end;
1269 }
1270
1271 if ( $end > $start ) {
1272 return substr( $text, $start, $end - $start );
1273 } else {
1274 return '';
1275 }
1276 }
1277
1278 /**
1279 * Find a nonletter near a point (index) in the text
1280 *
1281 * @param $text String
1282 * @param $point Integer
1283 * @param $offset Integer: offset to found index
1284 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1285 */
1286 function position( $text, $point, $offset = 0 ) {
1287 $tolerance = 10;
1288 $s = max( 0, $point - $tolerance );
1289 $l = min( strlen( $text ), $point + $tolerance ) - $s;
1290 $m = array();
1291 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE ) ) {
1292 return $m[0][1] + $s + $offset;
1293 } else {
1294 // check if point is on a valid first UTF8 char
1295 $char = ord( $text[$point] );
1296 while ( $char >= 0x80 && $char < 0xc0 ) {
1297 // skip trailing bytes
1298 $point++;
1299 if ( $point >= strlen( $text ) ) {
1300 return strlen( $text );
1301 }
1302 $char = ord( $text[$point] );
1303 }
1304 return $point;
1305
1306 }
1307 }
1308
1309 /**
1310 * Search extracts for a pattern, and return snippets
1311 *
1312 * @param string $pattern regexp for matching lines
1313 * @param array $extracts extracts to search
1314 * @param $linesleft Integer: number of extracts to make
1315 * @param $contextchars Integer: length of snippet
1316 * @param array $out map for highlighted snippets
1317 * @param array $offsets map of starting points of snippets
1318 * @protected
1319 */
1320 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1321 if ( $linesleft == 0 ) {
1322 return; // nothing to do
1323 }
1324 foreach ( $extracts as $index => $line ) {
1325 if ( array_key_exists( $index, $out ) ) {
1326 continue; // this line already highlighted
1327 }
1328
1329 $m = array();
1330 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) ) {
1331 continue;
1332 }
1333
1334 $offset = $m[0][1];
1335 $len = strlen( $m[0][0] );
1336 if ( $offset + $len < $contextchars ) {
1337 $begin = 0;
1338 } elseif ( $len > $contextchars ) {
1339 $begin = $offset;
1340 } else {
1341 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
1342 }
1343
1344 $end = $begin + $contextchars;
1345
1346 $posBegin = $begin;
1347 // basic snippet from this line
1348 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1349 $offsets[$index] = $posBegin;
1350 $linesleft--;
1351 if ( $linesleft == 0 ) {
1352 return;
1353 }
1354 }
1355 }
1356
1357 /**
1358 * Basic wikitext removal
1359 * @protected
1360 * @return mixed
1361 */
1362 function removeWiki( $text ) {
1363 $fname = __METHOD__;
1364 wfProfileIn( $fname );
1365
1366 // $text = preg_replace( "/'{2,5}/", "", $text );
1367 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1368 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1369 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1370 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1371 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1372 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1373 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1374 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1375 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1376 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1377 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1378 $text = preg_replace( "/'''''/", "", $text );
1379 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1380 $text = preg_replace( "/''/", "", $text );
1381
1382 wfProfileOut( $fname );
1383 return $text;
1384 }
1385
1386 /**
1387 * callback to replace [[target|caption]] kind of links, if
1388 * the target is category or image, leave it
1389 *
1390 * @param $matches Array
1391 */
1392 function linkReplace( $matches ) {
1393 $colon = strpos( $matches[1], ':' );
1394 if ( $colon === false ) {
1395 return $matches[2]; // replace with caption
1396 }
1397 global $wgContLang;
1398 $ns = substr( $matches[1], 0, $colon );
1399 $index = $wgContLang->getNsIndex( $ns );
1400 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) ) {
1401 return $matches[0]; // return the whole thing
1402 } else {
1403 return $matches[2];
1404 }
1405 }
1406
1407 /**
1408 * Simple & fast snippet extraction, but gives completely unrelevant
1409 * snippets
1410 *
1411 * @param $text String
1412 * @param $terms Array
1413 * @param $contextlines Integer
1414 * @param $contextchars Integer
1415 * @return String
1416 */
1417 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1418 global $wgContLang;
1419 $fname = __METHOD__;
1420
1421 $lines = explode( "\n", $text );
1422
1423 $terms = implode( '|', $terms );
1424 $max = intval( $contextchars ) + 1;
1425 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1426
1427 $lineno = 0;
1428
1429 $extract = "";
1430 wfProfileIn( "$fname-extract" );
1431 foreach ( $lines as $line ) {
1432 if ( 0 == $contextlines ) {
1433 break;
1434 }
1435 ++$lineno;
1436 $m = array();
1437 if ( ! preg_match( $pat1, $line, $m ) ) {
1438 continue;
1439 }
1440 --$contextlines;
1441 // truncate function changes ... to relevant i18n message.
1442 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1443
1444 if ( count( $m ) < 3 ) {
1445 $post = '';
1446 } else {
1447 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1448 }
1449
1450 $found = $m[2];
1451
1452 $line = htmlspecialchars( $pre . $found . $post );
1453 $pat2 = '/(' . $terms . ")/i";
1454 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1455
1456 $extract .= "${line}\n";
1457 }
1458 wfProfileOut( "$fname-extract" );
1459
1460 return $extract;
1461 }
1462
1463 }
1464
1465 /**
1466 * Dummy class to be used when non-supported Database engine is present.
1467 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1468 * such as a LIKE search through titles.
1469 * @ingroup Search
1470 */
1471 class SearchEngineDummy extends SearchEngine {
1472 // no-op
1473 }