Merge "Addition of SearchAfterNoDirectMatch hook"
[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 $term String: raw search term
62 * @return SearchResultSet
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 $term String: raw search term
74 * @return SearchResultSet
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
243 # Entering an IP address goes to the contributions page
244 if ( $wgEnableSearchContributorsByIP ) {
245 if ( ( $title->getNamespace() == NS_USER && User::isIP( $title->getText() ) )
246 || User::isIP( trim( $searchterm ) ) ) {
247 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
248 }
249 }
250
251
252 # Entering a user goes to the user page whether it's there or not
253 if ( $title->getNamespace() == NS_USER ) {
254 return $title;
255 }
256
257 # Go to images that exist even if there's no local page.
258 # There may have been a funny upload, or it may be on a shared
259 # file repository such as Wikimedia Commons.
260 if ( $title->getNamespace() == NS_FILE ) {
261 $image = wfFindFile( $title );
262 if ( $image ) {
263 return $title;
264 }
265 }
266
267 # MediaWiki namespace? Page may be "implied" if not customized.
268 # Just return it, with caps forced as the message system likes it.
269 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
270 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
271 }
272
273 # Quoted term? Try without the quotes...
274 $matches = array();
275 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
276 return SearchEngine::getNearMatch( $matches[1] );
277 }
278
279 return null;
280 }
281
282 public static function legalSearchChars() {
283 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
284 }
285
286 /**
287 * Set the maximum number of results to return
288 * and how many to skip before returning the first.
289 *
290 * @param $limit Integer
291 * @param $offset Integer
292 */
293 function setLimitOffset( $limit, $offset = 0 ) {
294 $this->limit = intval( $limit );
295 $this->offset = intval( $offset );
296 }
297
298 /**
299 * Set which namespaces the search should include.
300 * Give an array of namespace index numbers.
301 *
302 * @param $namespaces Array
303 */
304 function setNamespaces( $namespaces ) {
305 $this->namespaces = $namespaces;
306 }
307
308 /**
309 * Parse some common prefixes: all (search everything)
310 * or namespace names
311 *
312 * @param $query String
313 * @return string
314 */
315 function replacePrefixes( $query ) {
316 global $wgContLang;
317
318 $parsed = $query;
319 if ( strpos( $query, ':' ) === false ) { // nothing to do
320 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
321 return $parsed;
322 }
323
324 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
325 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
326 $this->namespaces = null;
327 $parsed = substr( $query, strlen( $allkeyword ) );
328 } elseif ( strpos( $query, ':' ) !== false ) {
329 $prefix = substr( $query, 0, strpos( $query, ':' ) );
330 $index = $wgContLang->getNsIndex( $prefix );
331 if ( $index !== false ) {
332 $this->namespaces = array( $index );
333 $parsed = substr( $query, strlen( $prefix ) + 1 );
334 }
335 }
336 if ( trim( $parsed ) == '' )
337 $parsed = $query; // prefix was the whole query
338
339 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
340
341 return $parsed;
342 }
343
344 /**
345 * Make a list of searchable namespaces and their canonical names.
346 * @return Array
347 */
348 public static function searchableNamespaces() {
349 global $wgContLang;
350 $arr = array();
351 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
352 if ( $ns >= NS_MAIN ) {
353 $arr[$ns] = $name;
354 }
355 }
356
357 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
358 return $arr;
359 }
360
361 /**
362 * Extract default namespaces to search from the given user's
363 * settings, returning a list of index numbers.
364 *
365 * @param $user User
366 * @return Array
367 */
368 public static function userNamespaces( $user ) {
369 global $wgSearchEverythingOnlyLoggedIn;
370
371 $searchableNamespaces = SearchEngine::searchableNamespaces();
372
373 // get search everything preference, that can be set to be read for logged-in users
374 // it overrides other options
375 if ( !$wgSearchEverythingOnlyLoggedIn || $user->isLoggedIn() ) {
376 if ( $user->getOption( 'searcheverything' ) ) {
377 return array_keys( $searchableNamespaces );
378 }
379 }
380
381 $arr = array();
382 foreach ( $searchableNamespaces as $ns => $name ) {
383 if ( $user->getOption( 'searchNs' . $ns ) ) {
384 $arr[] = $ns;
385 }
386 }
387
388 return $arr;
389 }
390
391 /**
392 * Find snippet highlight settings for all users
393 *
394 * @return Array contextlines, contextchars
395 */
396 public static function userHighlightPrefs() {
397 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
398 $contextchars = 75; // same as above.... :P
399 return array( $contextlines, $contextchars );
400 }
401
402 /**
403 * An array of namespaces indexes to be searched by default
404 *
405 * @return Array
406 */
407 public static function defaultNamespaces() {
408 global $wgNamespacesToBeSearchedDefault;
409
410 return array_keys( $wgNamespacesToBeSearchedDefault, true );
411 }
412
413 /**
414 * Get a list of namespace names useful for showing in tooltips
415 * and preferences
416 *
417 * @param $namespaces Array
418 * @return array
419 */
420 public static function namespacesAsText( $namespaces ) {
421 global $wgContLang;
422
423 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
424 foreach ( $formatted as $key => $ns ) {
425 if ( empty( $ns ) )
426 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
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 * Get OpenSearch suggestion template
499 *
500 * @return String
501 */
502 public static function getOpenSearchTemplate() {
503 global $wgOpenSearchTemplate, $wgCanonicalServer;
504 if ( $wgOpenSearchTemplate ) {
505 return $wgOpenSearchTemplate;
506 } else {
507 $ns = implode( '|', SearchEngine::defaultNamespaces() );
508 if ( !$ns ) {
509 $ns = "0";
510 }
511 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
512 }
513 }
514 }
515
516 /**
517 * @ingroup Search
518 */
519 class SearchResultSet {
520 /**
521 * Fetch an array of regular expression fragments for matching
522 * the search terms as parsed by this engine in a text extract.
523 * STUB
524 *
525 * @return Array
526 */
527 function termMatches() {
528 return array();
529 }
530
531 function numRows() {
532 return 0;
533 }
534
535 /**
536 * Return true if results are included in this result set.
537 * STUB
538 *
539 * @return Boolean
540 */
541 function hasResults() {
542 return false;
543 }
544
545 /**
546 * Some search modes return a total hit count for the query
547 * in the entire article database. This may include pages
548 * in namespaces that would not be matched on the given
549 * settings.
550 *
551 * Return null if no total hits number is supported.
552 *
553 * @return Integer
554 */
555 function getTotalHits() {
556 return null;
557 }
558
559 /**
560 * Some search modes return a suggested alternate term if there are
561 * no exact hits. Returns true if there is one on this set.
562 *
563 * @return Boolean
564 */
565 function hasSuggestion() {
566 return false;
567 }
568
569 /**
570 * @return String: suggested query, null if none
571 */
572 function getSuggestionQuery() {
573 return null;
574 }
575
576 /**
577 * @return String: HTML highlighted suggested query, '' if none
578 */
579 function getSuggestionSnippet() {
580 return '';
581 }
582
583 /**
584 * Return information about how and from where the results were fetched,
585 * should be useful for diagnostics and debugging
586 *
587 * @return String
588 */
589 function getInfo() {
590 return null;
591 }
592
593 /**
594 * Return a result set of hits on other (multiple) wikis associated with this one
595 *
596 * @return SearchResultSet
597 */
598 function getInterwikiResults() {
599 return null;
600 }
601
602 /**
603 * Check if there are results on other wikis
604 *
605 * @return Boolean
606 */
607 function hasInterwikiResults() {
608 return $this->getInterwikiResults() != null;
609 }
610
611 /**
612 * Fetches next search result, or false.
613 * STUB
614 *
615 * @return SearchResult
616 */
617 function next() {
618 return false;
619 }
620
621 /**
622 * Frees the result set, if applicable.
623 */
624 function free() {
625 // ...
626 }
627 }
628
629 /**
630 * This class is used for different SQL-based search engines shipped with MediaWiki
631 */
632 class SqlSearchResultSet extends SearchResultSet {
633
634 protected $mResultSet;
635
636 function __construct( $resultSet, $terms ) {
637 $this->mResultSet = $resultSet;
638 $this->mTerms = $terms;
639 }
640
641 function termMatches() {
642 return $this->mTerms;
643 }
644
645 function numRows() {
646 if ( $this->mResultSet === false )
647 return false;
648
649 return $this->mResultSet->numRows();
650 }
651
652 function next() {
653 if ( $this->mResultSet === false )
654 return false;
655
656 $row = $this->mResultSet->fetchObject();
657 if ( $row === false )
658 return false;
659
660 return SearchResult::newFromRow( $row );
661 }
662
663 function free() {
664 if ( $this->mResultSet === false )
665 return false;
666
667 $this->mResultSet->free();
668 }
669 }
670
671 /**
672 * @ingroup Search
673 */
674 class SearchResultTooMany {
675 # # Some search engines may bail out if too many matches are found
676 }
677
678
679 /**
680 * @todo FIXME: This class is horribly factored. It would probably be better to
681 * have a useful base class to which you pass some standard information, then
682 * let the fancy self-highlighters extend that.
683 * @ingroup Search
684 */
685 class SearchResult {
686
687 /**
688 * @var Revision
689 */
690 var $mRevision = null;
691 var $mImage = null;
692
693 /**
694 * @var Title
695 */
696 var $mTitle;
697
698 /**
699 * @var String
700 */
701 var $mText;
702
703 /**
704 * Return a new SearchResult and initializes it with a title.
705 *
706 * @param $title Title
707 * @return SearchResult
708 */
709 public static function newFromTitle( $title ) {
710 $result = new self();
711 $result->initFromTitle( $title );
712 return $result;
713 }
714 /**
715 * Return a new SearchResult and initializes it with a row.
716 *
717 * @param $row object
718 * @return SearchResult
719 */
720 public static function newFromRow( $row ) {
721 $result = new self();
722 $result->initFromRow( $row );
723 return $result;
724 }
725
726 public function __construct( $row = null ) {
727 if ( !is_null( $row ) ) {
728 // Backwards compatibility with pre-1.17 callers
729 $this->initFromRow( $row );
730 }
731 }
732
733 /**
734 * Initialize from a database row. Makes a Title and passes that to
735 * initFromTitle.
736 *
737 * @param $row object
738 */
739 protected function initFromRow( $row ) {
740 $this->initFromTitle( Title::makeTitle( $row->page_namespace, $row->page_title ) );
741 }
742
743 /**
744 * Initialize from a Title and if possible initializes a corresponding
745 * Revision and File.
746 *
747 * @param $title Title
748 */
749 protected function initFromTitle( $title ) {
750 $this->mTitle = $title;
751 if ( !is_null( $this->mTitle ) ) {
752 $id = false;
753 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
754 $this->mRevision = Revision::newFromTitle(
755 $this->mTitle, $id, Revision::READ_NORMAL );
756 if ( $this->mTitle->getNamespace() === NS_FILE )
757 $this->mImage = wfFindFile( $this->mTitle );
758 }
759 }
760
761 /**
762 * Check if this is result points to an invalid title
763 *
764 * @return Boolean
765 */
766 function isBrokenTitle() {
767 if ( is_null( $this->mTitle ) )
768 return true;
769 return false;
770 }
771
772 /**
773 * Check if target page is missing, happens when index is out of date
774 *
775 * @return Boolean
776 */
777 function isMissingRevision() {
778 return !$this->mRevision && !$this->mImage;
779 }
780
781 /**
782 * @return Title
783 */
784 function getTitle() {
785 return $this->mTitle;
786 }
787
788 /**
789 * @return float|null if not supported
790 */
791 function getScore() {
792 return null;
793 }
794
795 /**
796 * Lazy initialization of article text from DB
797 */
798 protected function initText() {
799 if ( !isset( $this->mText ) ) {
800 if ( $this->mRevision != null ) {
801 //TODO: if we could plug in some code that knows about special content models *and* about
802 // special features of the search engine, the search could benefit.
803 $content = $this->mRevision->getContent();
804 $this->mText = $content ? $content->getTextForSearchIndex() : '';
805 } else { // TODO: can we fetch raw wikitext for commons images?
806 $this->mText = '';
807 }
808 }
809 }
810
811 /**
812 * @param $terms Array: terms to highlight
813 * @return String: highlighted text snippet, null (and not '') if not supported
814 */
815 function getTextSnippet( $terms ) {
816 global $wgUser, $wgAdvancedSearchHighlighting;
817 $this->initText();
818
819 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
820 list( $contextlines, $contextchars ) = SearchEngine::userHighlightPrefs( $wgUser );
821 $h = new SearchHighlighter();
822 if ( $wgAdvancedSearchHighlighting )
823 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
824 else
825 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
826 }
827
828 /**
829 * @param $terms Array: terms to highlight
830 * @return String: highlighted title, '' if not supported
831 */
832 function getTitleSnippet( $terms ) {
833 return '';
834 }
835
836 /**
837 * @param $terms Array: terms to highlight
838 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
839 */
840 function getRedirectSnippet( $terms ) {
841 return '';
842 }
843
844 /**
845 * @return Title object for the redirect to this page, null if none or not supported
846 */
847 function getRedirectTitle() {
848 return null;
849 }
850
851 /**
852 * @return string highlighted relevant section name, null if none or not supported
853 */
854 function getSectionSnippet() {
855 return '';
856 }
857
858 /**
859 * @return Title object (pagename+fragment) for the section, null if none or not supported
860 */
861 function getSectionTitle() {
862 return null;
863 }
864
865 /**
866 * @return String: timestamp
867 */
868 function getTimestamp() {
869 if ( $this->mRevision )
870 return $this->mRevision->getTimestamp();
871 elseif ( $this->mImage )
872 return $this->mImage->getTimestamp();
873 return '';
874 }
875
876 /**
877 * @return Integer: number of words
878 */
879 function getWordCount() {
880 $this->initText();
881 return str_word_count( $this->mText );
882 }
883
884 /**
885 * @return Integer: size in bytes
886 */
887 function getByteSize() {
888 $this->initText();
889 return strlen( $this->mText );
890 }
891
892 /**
893 * @return Boolean if hit has related articles
894 */
895 function hasRelated() {
896 return false;
897 }
898
899 /**
900 * @return String: interwiki prefix of the title (return iw even if title is broken)
901 */
902 function getInterwikiPrefix() {
903 return '';
904 }
905 }
906 /**
907 * A SearchResultSet wrapper for SearchEngine::getNearMatch
908 */
909 class SearchNearMatchResultSet extends SearchResultSet {
910 private $fetched = false;
911 /**
912 * @param $match mixed Title if matched, else null
913 */
914 public function __construct( $match ) {
915 $this->result = $match;
916 }
917 public function hasResult() {
918 return (bool)$this->result;
919 }
920 public function numRows() {
921 return $this->hasResults() ? 1 : 0;
922 }
923 public function next() {
924 if ( $this->fetched || !$this->result ) {
925 return false;
926 }
927 $this->fetched = true;
928 return SearchResult::newFromTitle( $this->result );
929 }
930 }
931
932 /**
933 * Highlight bits of wikitext
934 *
935 * @ingroup Search
936 */
937 class SearchHighlighter {
938 var $mCleanWikitext = true;
939
940 function __construct( $cleanupWikitext = true ) {
941 $this->mCleanWikitext = $cleanupWikitext;
942 }
943
944 /**
945 * Default implementation of wikitext highlighting
946 *
947 * @param $text String
948 * @param $terms Array: terms to highlight (unescaped)
949 * @param $contextlines Integer
950 * @param $contextchars Integer
951 * @return String
952 */
953 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
954 global $wgContLang;
955 global $wgSearchHighlightBoundaries;
956 $fname = __METHOD__;
957
958 if ( $text == '' )
959 return '';
960
961 // spli text into text + templates/links/tables
962 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
963 // first capture group is for detecting nested templates/links/tables/references
964 $endPatterns = array(
965 1 => '/(\{\{)|(\}\})/', // template
966 2 => '/(\[\[)|(\]\])/', // image
967 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
968
969 // @todo FIXME: This should prolly be a hook or something
970 if ( function_exists( 'wfCite' ) ) {
971 $spat .= '|(<ref>)'; // references via cite extension
972 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
973 }
974 $spat .= '/';
975 $textExt = array(); // text extracts
976 $otherExt = array(); // other extracts
977 wfProfileIn( "$fname-split" );
978 $start = 0;
979 $textLen = strlen( $text );
980 $count = 0; // sequence number to maintain ordering
981 while ( $start < $textLen ) {
982 // find start of template/image/table
983 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
984 $epat = '';
985 foreach ( $matches as $key => $val ) {
986 if ( $key > 0 && $val[1] != - 1 ) {
987 if ( $key == 2 ) {
988 // see if this is an image link
989 $ns = substr( $val[0], 2, - 1 );
990 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE )
991 break;
992
993 }
994 $epat = $endPatterns[$key];
995 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
996 $start = $val[1];
997 break;
998 }
999 }
1000 if ( $epat ) {
1001 // find end (and detect any nested elements)
1002 $level = 0;
1003 $offset = $start + 1;
1004 $found = false;
1005 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
1006 if ( array_key_exists( 2, $endMatches ) ) {
1007 // found end
1008 if ( $level == 0 ) {
1009 $len = strlen( $endMatches[2][0] );
1010 $off = $endMatches[2][1];
1011 $this->splitAndAdd( $otherExt, $count,
1012 substr( $text, $start, $off + $len - $start ) );
1013 $start = $off + $len;
1014 $found = true;
1015 break;
1016 } else {
1017 // end of nested element
1018 $level -= 1;
1019 }
1020 } else {
1021 // nested
1022 $level += 1;
1023 }
1024 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
1025 }
1026 if ( ! $found ) {
1027 // couldn't find appropriate closing tag, skip
1028 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1029 $start += strlen( $matches[0][0] );
1030 }
1031 continue;
1032 }
1033 }
1034 // else: add as text extract
1035 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1036 break;
1037 }
1038
1039 $all = $textExt + $otherExt; // these have disjunct key sets
1040
1041 wfProfileOut( "$fname-split" );
1042
1043 // prepare regexps
1044 foreach ( $terms as $index => $term ) {
1045 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1046 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1047 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1048 } else {
1049 $terms[$index] = $term;
1050 }
1051 }
1052 $anyterm = implode( '|', $terms );
1053 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1054
1055 // @todo FIXME: A hack to scale contextchars, a correct solution
1056 // would be to have contextchars actually be char and not byte
1057 // length, and do proper utf-8 substrings and lengths everywhere,
1058 // but PHP is making that very hard and unclean to implement :(
1059 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1060 $contextchars = intval( $contextchars * $scale );
1061
1062 $patPre = "(^|$wgSearchHighlightBoundaries)";
1063 $patPost = "($wgSearchHighlightBoundaries|$)";
1064
1065 $pat1 = "/(" . $phrase . ")/ui";
1066 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1067
1068 wfProfileIn( "$fname-extract" );
1069
1070 $left = $contextlines;
1071
1072 $snippets = array();
1073 $offsets = array();
1074
1075 // show beginning only if it contains all words
1076 $first = 0;
1077 $firstText = '';
1078 foreach ( $textExt as $index => $line ) {
1079 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1080 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1081 $first = $index;
1082 break;
1083 }
1084 }
1085 if ( $firstText ) {
1086 $succ = true;
1087 // check if first text contains all terms
1088 foreach ( $terms as $term ) {
1089 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1090 $succ = false;
1091 break;
1092 }
1093 }
1094 if ( $succ ) {
1095 $snippets[$first] = $firstText;
1096 $offsets[$first] = 0;
1097 }
1098 }
1099 if ( ! $snippets ) {
1100 // match whole query on text
1101 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1102 // match whole query on templates/tables/images
1103 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1104 // match any words on text
1105 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1106 // match any words on templates/tables/images
1107 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1108
1109 ksort( $snippets );
1110 }
1111
1112 // add extra chars to each snippet to make snippets constant size
1113 $extended = array();
1114 if ( count( $snippets ) == 0 ) {
1115 // couldn't find the target words, just show beginning of article
1116 if ( array_key_exists( $first, $all ) ) {
1117 $targetchars = $contextchars * $contextlines;
1118 $snippets[$first] = '';
1119 $offsets[$first] = 0;
1120 }
1121 } else {
1122 // if begin of the article contains the whole phrase, show only that !!
1123 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1124 && $offsets[$first] < $contextchars * 2 ) {
1125 $snippets = array ( $first => $snippets[$first] );
1126 }
1127
1128 // calc by how much to extend existing snippets
1129 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1130 }
1131
1132 foreach ( $snippets as $index => $line ) {
1133 $extended[$index] = $line;
1134 $len = strlen( $line );
1135 if ( $len < $targetchars - 20 ) {
1136 // complete this line
1137 if ( $len < strlen( $all[$index] ) ) {
1138 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] + $targetchars, $offsets[$index] );
1139 $len = strlen( $extended[$index] );
1140 }
1141
1142 // add more lines
1143 $add = $index + 1;
1144 while ( $len < $targetchars - 20
1145 && array_key_exists( $add, $all )
1146 && !array_key_exists( $add, $snippets ) ) {
1147 $offsets[$add] = 0;
1148 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1149 $extended[$add] = $tt;
1150 $len += strlen( $tt );
1151 $add++;
1152 }
1153 }
1154 }
1155
1156 // $snippets = array_map('htmlspecialchars', $extended);
1157 $snippets = $extended;
1158 $last = - 1;
1159 $extract = '';
1160 foreach ( $snippets as $index => $line ) {
1161 if ( $last == - 1 )
1162 $extract .= $line; // first line
1163 elseif ( $last + 1 == $index && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1164 $extract .= " " . $line; // continous lines
1165 else
1166 $extract .= '<b> ... </b>' . $line;
1167
1168 $last = $index;
1169 }
1170 if ( $extract )
1171 $extract .= '<b> ... </b>';
1172
1173 $processed = array();
1174 foreach ( $terms as $term ) {
1175 if ( ! isset( $processed[$term] ) ) {
1176 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1177 $extract = preg_replace( $pat3,
1178 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1179 $processed[$term] = true;
1180 }
1181 }
1182
1183 wfProfileOut( "$fname-extract" );
1184
1185 return $extract;
1186 }
1187
1188 /**
1189 * Split text into lines and add it to extracts array
1190 *
1191 * @param $extracts Array: index -> $line
1192 * @param $count Integer
1193 * @param $text String
1194 */
1195 function splitAndAdd( &$extracts, &$count, $text ) {
1196 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
1197 foreach ( $split as $line ) {
1198 $tt = trim( $line );
1199 if ( $tt )
1200 $extracts[$count++] = $tt;
1201 }
1202 }
1203
1204 /**
1205 * Do manual case conversion for non-ascii chars
1206 *
1207 * @param $matches Array
1208 * @return string
1209 */
1210 function caseCallback( $matches ) {
1211 global $wgContLang;
1212 if ( strlen( $matches[0] ) > 1 ) {
1213 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1214 } else {
1215 return $matches[0];
1216 }
1217 }
1218
1219 /**
1220 * Extract part of the text from start to end, but by
1221 * not chopping up words
1222 * @param $text String
1223 * @param $start Integer
1224 * @param $end Integer
1225 * @param $posStart Integer: (out) actual start position
1226 * @param $posEnd Integer: (out) actual end position
1227 * @return String
1228 */
1229 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1230 if ( $start != 0 ) {
1231 $start = $this->position( $text, $start, 1 );
1232 }
1233 if ( $end >= strlen( $text ) ) {
1234 $end = strlen( $text );
1235 } else {
1236 $end = $this->position( $text, $end );
1237 }
1238
1239 if ( !is_null( $posStart ) ) {
1240 $posStart = $start;
1241 }
1242 if ( !is_null( $posEnd ) ) {
1243 $posEnd = $end;
1244 }
1245
1246 if ( $end > $start ) {
1247 return substr( $text, $start, $end - $start );
1248 } else {
1249 return '';
1250 }
1251 }
1252
1253 /**
1254 * Find a nonletter near a point (index) in the text
1255 *
1256 * @param $text String
1257 * @param $point Integer
1258 * @param $offset Integer: offset to found index
1259 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1260 */
1261 function position( $text, $point, $offset = 0 ) {
1262 $tolerance = 10;
1263 $s = max( 0, $point - $tolerance );
1264 $l = min( strlen( $text ), $point + $tolerance ) - $s;
1265 $m = array();
1266 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE ) ) {
1267 return $m[0][1] + $s + $offset;
1268 } else {
1269 // check if point is on a valid first UTF8 char
1270 $char = ord( $text[$point] );
1271 while ( $char >= 0x80 && $char < 0xc0 ) {
1272 // skip trailing bytes
1273 $point++;
1274 if ( $point >= strlen( $text ) )
1275 return strlen( $text );
1276 $char = ord( $text[$point] );
1277 }
1278 return $point;
1279
1280 }
1281 }
1282
1283 /**
1284 * Search extracts for a pattern, and return snippets
1285 *
1286 * @param $pattern String: regexp for matching lines
1287 * @param $extracts Array: extracts to search
1288 * @param $linesleft Integer: number of extracts to make
1289 * @param $contextchars Integer: length of snippet
1290 * @param $out Array: map for highlighted snippets
1291 * @param $offsets Array: map of starting points of snippets
1292 * @protected
1293 */
1294 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1295 if ( $linesleft == 0 )
1296 return; // nothing to do
1297 foreach ( $extracts as $index => $line ) {
1298 if ( array_key_exists( $index, $out ) )
1299 continue; // this line already highlighted
1300
1301 $m = array();
1302 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) )
1303 continue;
1304
1305 $offset = $m[0][1];
1306 $len = strlen( $m[0][0] );
1307 if ( $offset + $len < $contextchars )
1308 $begin = 0;
1309 elseif ( $len > $contextchars )
1310 $begin = $offset;
1311 else
1312 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
1313
1314 $end = $begin + $contextchars;
1315
1316 $posBegin = $begin;
1317 // basic snippet from this line
1318 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1319 $offsets[$index] = $posBegin;
1320 $linesleft--;
1321 if ( $linesleft == 0 )
1322 return;
1323 }
1324 }
1325
1326 /**
1327 * Basic wikitext removal
1328 * @protected
1329 * @return mixed
1330 */
1331 function removeWiki( $text ) {
1332 $fname = __METHOD__;
1333 wfProfileIn( $fname );
1334
1335 // $text = preg_replace("/'{2,5}/", "", $text);
1336 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1337 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1338 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1339 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1340 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1341 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1342 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1343 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1344 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1345 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1346 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1347 $text = preg_replace( "/'''''/", "", $text );
1348 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1349 $text = preg_replace( "/''/", "", $text );
1350
1351 wfProfileOut( $fname );
1352 return $text;
1353 }
1354
1355 /**
1356 * callback to replace [[target|caption]] kind of links, if
1357 * the target is category or image, leave it
1358 *
1359 * @param $matches Array
1360 */
1361 function linkReplace( $matches ) {
1362 $colon = strpos( $matches[1], ':' );
1363 if ( $colon === false )
1364 return $matches[2]; // replace with caption
1365 global $wgContLang;
1366 $ns = substr( $matches[1], 0, $colon );
1367 $index = $wgContLang->getNsIndex( $ns );
1368 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) )
1369 return $matches[0]; // return the whole thing
1370 else
1371 return $matches[2];
1372
1373 }
1374
1375 /**
1376 * Simple & fast snippet extraction, but gives completely unrelevant
1377 * snippets
1378 *
1379 * @param $text String
1380 * @param $terms Array
1381 * @param $contextlines Integer
1382 * @param $contextchars Integer
1383 * @return String
1384 */
1385 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1386 global $wgContLang;
1387 $fname = __METHOD__;
1388
1389 $lines = explode( "\n", $text );
1390
1391 $terms = implode( '|', $terms );
1392 $max = intval( $contextchars ) + 1;
1393 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1394
1395 $lineno = 0;
1396
1397 $extract = "";
1398 wfProfileIn( "$fname-extract" );
1399 foreach ( $lines as $line ) {
1400 if ( 0 == $contextlines ) {
1401 break;
1402 }
1403 ++$lineno;
1404 $m = array();
1405 if ( ! preg_match( $pat1, $line, $m ) ) {
1406 continue;
1407 }
1408 --$contextlines;
1409 // truncate function changes ... to relevant i18n message.
1410 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1411
1412 if ( count( $m ) < 3 ) {
1413 $post = '';
1414 } else {
1415 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1416 }
1417
1418 $found = $m[2];
1419
1420 $line = htmlspecialchars( $pre . $found . $post );
1421 $pat2 = '/(' . $terms . ")/i";
1422 $line = preg_replace( $pat2,
1423 "<span class='searchmatch'>\\1</span>", $line );
1424
1425 $extract .= "${line}\n";
1426 }
1427 wfProfileOut( "$fname-extract" );
1428
1429 return $extract;
1430 }
1431
1432 }
1433
1434 /**
1435 * Dummy class to be used when non-supported Database engine is present.
1436 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1437 * such as a LIKE search through titles.
1438 * @ingroup Search
1439 */
1440 class SearchEngineDummy extends SearchEngine {
1441 // no-op
1442 }