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