Make MessageCache use the immutable text cache during cache rebuilds
[mediawiki.git] / includes / content / WikiTextStructure.php
blob9f79aa8d088da86a80c7298c5fa8a15802fd930d
1 <?php
3 use HtmlFormatter\HtmlFormatter;
5 /**
6 * Class allowing to explore structure of parsed wikitext.
7 */
8 class WikiTextStructure {
9 /**
10 * @var string
12 private $openingText;
13 /**
14 * @var string
16 private $allText;
17 /**
18 * @var string[]
20 private $auxText = [];
21 /**
22 * @var ParserOutput
24 private $parserOutput;
26 /**
27 * @var string[] selectors to elements that are excluded entirely from search
29 private $excludedElementSelectors = [
30 // "it looks like you don't have javascript enabled..." – do not need to index
31 'audio', 'video',
32 // The [1] for references
33 'sup.reference',
34 // The ↑ next to references in the references section
35 '.mw-cite-backlink',
36 // Headings are already indexed in their own field.
37 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
38 // Collapsed fields are hidden by default so we don't want them showing up.
39 '.autocollapse',
42 /**
43 * @var string[] selectors to elements that are considered auxiliary to article text for search
45 private $auxiliaryElementSelectors = [
46 // Thumbnail captions aren't really part of the text proper
47 '.thumbcaption',
48 // Neither are tables
49 'table',
50 // Common style for "See also:".
51 '.rellink',
52 // Common style for calling out helpful links at the top of the article.
53 '.dablink',
54 // New class users can use to mark stuff as auxiliary to searches.
55 '.searchaux',
58 /**
59 * WikiTextStructure constructor.
60 * @param ParserOutput $parserOutput
62 public function __construct( ParserOutput $parserOutput ) {
63 $this->parserOutput = $parserOutput;
66 /**
67 * Get headings on the page.
68 * @return string[]
69 * First strip out things that look like references. We can't use HTML filtering because
70 * the references come back as <sup> tags without a class. To keep from breaking stuff like
71 * ==Applicability of the strict mass–energy equivalence formula, ''E'' = ''mc''<sup>2</sup>==
72 * we don't remove the whole <sup> tag. We also don't want to strip the <sup> tag and remove
73 * everything that looks like [2] because, I dunno, maybe there is a band named Word [2] Foo
74 * or something. Whatever. So we only strip things that look like <sup> tags wrapping a
75 * reference. And since the data looks like:
76 * Reference in heading <sup>&#91;1&#93;</sup><sup>&#91;2&#93;</sup>
77 * we can not really use HtmlFormatter as we have no suitable selector.
79 public function headings() {
80 $headings = [];
81 $ignoredHeadings = $this->getIgnoredHeadings();
82 foreach ( $this->parserOutput->getSections() as $heading ) {
83 $heading = $heading[ 'line' ];
85 // Some wikis wrap the brackets in a span:
86 // https://en.wikipedia.org/wiki/MediaWiki:Cite_reference_link
87 $heading = preg_replace( '/<\/?span>/', '', $heading );
88 // Normalize [] so the following regexp would work.
89 $heading = preg_replace( [ '/&#91;/', '/&#93;/' ], [ '[', ']' ], $heading );
90 $heading = preg_replace( '/<sup>\s*\[\s*\d+\s*\]\s*<\/sup>/is', '', $heading );
92 // Strip tags from the heading or else we'll display them (escaped) in search results
93 $heading = trim( Sanitizer::stripAllTags( $heading ) );
95 // Note that we don't take the level of the heading into account - all headings are equal.
96 // Except the ones we ignore.
97 if ( !in_array( $heading, $ignoredHeadings ) ) {
98 $headings[] = $heading;
101 return $headings;
105 * Parse a message content into an array. This function is generally used to
106 * parse settings stored as i18n messages (see search-ignored-headings).
108 * @param string $message
109 * @return string[]
111 public static function parseSettingsInMessage( $message ) {
112 $lines = explode( "\n", $message );
113 $lines = preg_replace( '/#.*$/', '', $lines ); // Remove comments
114 $lines = array_map( 'trim', $lines ); // Remove extra spaces
115 $lines = array_filter( $lines ); // Remove empty lines
116 return $lines;
120 * Get list of heading to ignore.
121 * @return string[]
123 private function getIgnoredHeadings() {
124 static $ignoredHeadings = null;
125 if ( $ignoredHeadings === null ) {
126 $ignoredHeadings = [];
127 $source = wfMessage( 'search-ignored-headings' )->inContentLanguage();
128 if ( $source->isBlank() ) {
129 // Try old version too, just in case
130 $source = wfMessage( 'cirrussearch-ignored-headings' )->inContentLanguage();
132 if ( !$source->isDisabled() ) {
133 $lines = self::parseSettingsInMessage( $source->plain() );
134 $ignoredHeadings = $lines; // Now we just have headings!
137 return $ignoredHeadings;
141 * Extract parts of the text - opening, main and auxiliary.
143 private function extractWikitextParts() {
144 if ( !is_null( $this->allText ) ) {
145 return;
147 $this->parserOutput->setEditSectionTokens( false );
148 $this->parserOutput->setTOCEnabled( false );
149 $text = $this->parserOutput->getText();
150 if ( strlen( $text ) == 0 ) {
151 $this->allText = "";
152 // empty text - nothing to seek here
153 return;
155 $opening = null;
157 $this->openingText = $this->extractHeadingBeforeFirstHeading( $text );
159 // Add extra spacing around break tags so text crammed together like<br>this
160 // doesn't make one word.
161 $text = str_replace( '<br', "\n<br", $text );
163 $formatter = new HtmlFormatter( $text );
165 // Strip elements from the page that we never want in the search text.
166 $formatter->remove( $this->excludedElementSelectors );
167 $formatter->filterContent();
169 // Strip elements from the page that are auxiliary text. These will still be
170 // searched but matches will be ranked lower and non-auxiliary matches will be
171 // preferred in highlighting.
172 $formatter->remove( $this->auxiliaryElementSelectors );
173 $auxiliaryElements = $formatter->filterContent();
174 $this->allText = trim( Sanitizer::stripAllTags( $formatter->getText() ) );
175 foreach ( $auxiliaryElements as $auxiliaryElement ) {
176 $this->auxText[] =
177 trim( Sanitizer::stripAllTags( $formatter->getText( $auxiliaryElement ) ) );
182 * Get text before first heading.
183 * @param string $text
184 * @return string|null
186 private function extractHeadingBeforeFirstHeading( $text ) {
187 $matches = [];
188 if ( !preg_match( '/<h[123456]>/', $text, $matches, PREG_OFFSET_CAPTURE ) ) {
189 // There isn't a first heading so we interpret this as the article
190 // being entirely without heading.
191 return null;
193 $text = substr( $text, 0, $matches[ 0 ][ 1 ] );
194 if ( !$text ) {
195 // There isn't any text before the first heading so we declare there isn't
196 // a first heading.
197 return null;
200 $formatter = new HtmlFormatter( $text );
201 $formatter->remove( $this->excludedElementSelectors );
202 $formatter->remove( $this->auxiliaryElementSelectors );
203 $formatter->filterContent();
204 $text = trim( Sanitizer::stripAllTags( $formatter->getText() ) );
206 if ( !$text ) {
207 // There isn't any text after filtering before the first heading so we declare
208 // that there isn't a first heading.
209 return null;
212 return $text;
216 * Get opening text
217 * @return string
219 public function getOpeningText() {
220 $this->extractWikitextParts();
221 return $this->openingText;
225 * Get main text
226 * @return string
228 public function getMainText() {
229 $this->extractWikitextParts();
230 return $this->allText;
234 * Get auxiliary text
235 * @return string[]
237 public function getAuxiliaryText() {
238 $this->extractWikitextParts();
239 return $this->auxText;
243 * Get the defaultsort property
244 * @return string|null
246 public function getDefaultSort() {
247 return $this->parserOutput->getProperty( 'defaultsort' );