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