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