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