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