MediaWiki  1.28.0
BlockLevelPass.php
Go to the documentation of this file.
1 <?php
2 
26  private $DTopen = false;
27  private $inPre = false;
28  private $lastSection = '';
29  private $linestart;
30  private $text;
31 
32  # State constants for the definition list colon extraction
33  const COLON_STATE_TEXT = 0;
34  const COLON_STATE_TAG = 1;
41 
49  public static function doBlockLevels( $text, $lineStart ) {
50  $pass = new self( $text, $lineStart );
51  return $pass->execute();
52  }
53 
57  private function __construct( $text, $lineStart ) {
58  $this->text = $text;
59  $this->lineStart = $lineStart;
60  }
61 
67  private function closeParagraph() {
68  $result = '';
69  if ( $this->lastSection !== '' ) {
70  $result = '</' . $this->lastSection . ">\n";
71  }
72  $this->inPre = false;
73  $this->lastSection = '';
74  return $result;
75  }
76 
86  private function getCommon( $st1, $st2 ) {
87  $shorter = min( strlen( $st1 ), strlen( $st2 ) );
88 
89  for ( $i = 0; $i < $shorter; ++$i ) {
90  if ( $st1[$i] !== $st2[$i] ) {
91  break;
92  }
93  }
94  return $i;
95  }
96 
104  private function openList( $char ) {
105  $result = $this->closeParagraph();
106 
107  if ( '*' === $char ) {
108  $result .= "<ul><li>";
109  } elseif ( '#' === $char ) {
110  $result .= "<ol><li>";
111  } elseif ( ':' === $char ) {
112  $result .= "<dl><dd>";
113  } elseif ( ';' === $char ) {
114  $result .= "<dl><dt>";
115  $this->DTopen = true;
116  } else {
117  $result = '<!-- ERR 1 -->';
118  }
119 
120  return $result;
121  }
122 
129  private function nextItem( $char ) {
130  if ( '*' === $char || '#' === $char ) {
131  return "</li>\n<li>";
132  } elseif ( ':' === $char || ';' === $char ) {
133  $close = "</dd>\n";
134  if ( $this->DTopen ) {
135  $close = "</dt>\n";
136  }
137  if ( ';' === $char ) {
138  $this->DTopen = true;
139  return $close . '<dt>';
140  } else {
141  $this->DTopen = false;
142  return $close . '<dd>';
143  }
144  }
145  return '<!-- ERR 2 -->';
146  }
147 
154  private function closeList( $char ) {
155  if ( '*' === $char ) {
156  $text = "</li></ul>";
157  } elseif ( '#' === $char ) {
158  $text = "</li></ol>";
159  } elseif ( ':' === $char ) {
160  if ( $this->DTopen ) {
161  $this->DTopen = false;
162  $text = "</dt></dl>";
163  } else {
164  $text = "</dd></dl>";
165  }
166  } else {
167  return '<!-- ERR 3 -->';
168  }
169  return $text;
170  }
171 
176  private function execute() {
177  $text = $this->text;
178  # Parsing through the text line by line. The main thing
179  # happening here is handling of block-level elements p, pre,
180  # and making lists from lines starting with * # : etc.
181  $textLines = StringUtils::explode( "\n", $text );
182 
183  $lastPrefix = $output = '';
184  $this->DTopen = $inBlockElem = false;
185  $prefixLength = 0;
186  $pendingPTag = false;
187  $inBlockquote = false;
188 
189  foreach ( $textLines as $inputLine ) {
190  # Fix up $lineStart
191  if ( !$this->lineStart ) {
192  $output .= $inputLine;
193  $this->lineStart = true;
194  continue;
195  }
196  # * = ul
197  # # = ol
198  # ; = dt
199  # : = dd
200 
201  $lastPrefixLength = strlen( $lastPrefix );
202  $preCloseMatch = preg_match( '/<\\/pre/i', $inputLine );
203  $preOpenMatch = preg_match( '/<pre/i', $inputLine );
204  # If not in a <pre> element, scan for and figure out what prefixes are there.
205  if ( !$this->inPre ) {
206  # Multiple prefixes may abut each other for nested lists.
207  $prefixLength = strspn( $inputLine, '*#:;' );
208  $prefix = substr( $inputLine, 0, $prefixLength );
209 
210  # eh?
211  # ; and : are both from definition-lists, so they're equivalent
212  # for the purposes of determining whether or not we need to open/close
213  # elements.
214  $prefix2 = str_replace( ';', ':', $prefix );
215  $t = substr( $inputLine, $prefixLength );
216  $this->inPre = (bool)$preOpenMatch;
217  } else {
218  # Don't interpret any other prefixes in preformatted text
219  $prefixLength = 0;
220  $prefix = $prefix2 = '';
221  $t = $inputLine;
222  }
223 
224  # List generation
225  if ( $prefixLength && $lastPrefix === $prefix2 ) {
226  # Same as the last item, so no need to deal with nesting or opening stuff
227  $output .= $this->nextItem( substr( $prefix, -1 ) );
228  $pendingPTag = false;
229 
230  if ( substr( $prefix, -1 ) === ';' ) {
231  # The one nasty exception: definition lists work like this:
232  # ; title : definition text
233  # So we check for : in the remainder text to split up the
234  # title and definition, without b0rking links.
235  $term = $t2 = '';
236  if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
237  $t = $t2;
238  $output .= $term . $this->nextItem( ':' );
239  }
240  }
241  } elseif ( $prefixLength || $lastPrefixLength ) {
242  # We need to open or close prefixes, or both.
243 
244  # Either open or close a level...
245  $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
246  $pendingPTag = false;
247 
248  # Close all the prefixes which aren't shared.
249  while ( $commonPrefixLength < $lastPrefixLength ) {
250  $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
251  --$lastPrefixLength;
252  }
253 
254  # Continue the current prefix if appropriate.
255  if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
256  $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
257  }
258 
259  # Open prefixes where appropriate.
260  if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
261  $output .= "\n";
262  }
263  while ( $prefixLength > $commonPrefixLength ) {
264  $char = substr( $prefix, $commonPrefixLength, 1 );
265  $output .= $this->openList( $char );
266 
267  if ( ';' === $char ) {
268  # @todo FIXME: This is dupe of code above
269  if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
270  $t = $t2;
271  $output .= $term . $this->nextItem( ':' );
272  }
273  }
274  ++$commonPrefixLength;
275  }
276  if ( !$prefixLength && $lastPrefix ) {
277  $output .= "\n";
278  }
279  $lastPrefix = $prefix2;
280  }
281 
282  # If we have no prefixes, go to paragraph mode.
283  if ( 0 == $prefixLength ) {
284  # No prefix (not in list)--go to paragraph mode
285  # @todo consider using a stack for nestable elements like span, table and div
286  $openMatch = preg_match(
287  '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
288  . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
289  $t
290  );
291  $closeMatch = preg_match(
292  '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
293  . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
295  . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
296  $t
297  );
298 
299  if ( $openMatch || $closeMatch ) {
300  $pendingPTag = false;
301  # @todo bug 5718: paragraph closed
302  $output .= $this->closeParagraph();
303  if ( $preOpenMatch && !$preCloseMatch ) {
304  $this->inPre = true;
305  }
306  $bqOffset = 0;
307  while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t,
308  $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset )
309  ) {
310  $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
311  $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
312  }
313  $inBlockElem = !$closeMatch;
314  } elseif ( !$inBlockElem && !$this->inPre ) {
315  if ( ' ' == substr( $t, 0, 1 )
316  && ( $this->lastSection === 'pre' || trim( $t ) != '' )
317  && !$inBlockquote
318  ) {
319  # pre
320  if ( $this->lastSection !== 'pre' ) {
321  $pendingPTag = false;
322  $output .= $this->closeParagraph() . '<pre>';
323  $this->lastSection = 'pre';
324  }
325  $t = substr( $t, 1 );
326  } else {
327  # paragraph
328  if ( trim( $t ) === '' ) {
329  if ( $pendingPTag ) {
330  $output .= $pendingPTag . '<br />';
331  $pendingPTag = false;
332  $this->lastSection = 'p';
333  } else {
334  if ( $this->lastSection !== 'p' ) {
335  $output .= $this->closeParagraph();
336  $this->lastSection = '';
337  $pendingPTag = '<p>';
338  } else {
339  $pendingPTag = '</p><p>';
340  }
341  }
342  } else {
343  if ( $pendingPTag ) {
344  $output .= $pendingPTag;
345  $pendingPTag = false;
346  $this->lastSection = 'p';
347  } elseif ( $this->lastSection !== 'p' ) {
348  $output .= $this->closeParagraph() . '<p>';
349  $this->lastSection = 'p';
350  }
351  }
352  }
353  }
354  }
355  # somewhere above we forget to get out of pre block (bug 785)
356  if ( $preCloseMatch && $this->inPre ) {
357  $this->inPre = false;
358  }
359  if ( $pendingPTag === false ) {
360  $output .= $t;
361  if ( $prefixLength === 0 ) {
362  $output .= "\n";
363  }
364  }
365  }
366  while ( $prefixLength ) {
367  $output .= $this->closeList( $prefix2[$prefixLength - 1] );
368  --$prefixLength;
369  if ( !$prefixLength ) {
370  $output .= "\n";
371  }
372  }
373  if ( $this->lastSection !== '' ) {
374  $output .= '</' . $this->lastSection . '>';
375  $this->lastSection = '';
376  }
377 
378  return $output;
379  }
380 
391  private function findColonNoLinks( $str, &$before, &$after ) {
392  $colonPos = strpos( $str, ':' );
393  if ( $colonPos === false ) {
394  # Nothing to find!
395  return false;
396  }
397 
398  $ltPos = strpos( $str, '<' );
399  if ( $ltPos === false || $ltPos > $colonPos ) {
400  # Easy; no tag nesting to worry about
401  $before = substr( $str, 0, $colonPos );
402  $after = substr( $str, $colonPos + 1 );
403  return $colonPos;
404  }
405 
406  # Ugly state machine to walk through avoiding tags.
407  $state = self::COLON_STATE_TEXT;
408  $level = 0;
409  $len = strlen( $str );
410  for ( $i = 0; $i < $len; $i++ ) {
411  $c = $str[$i];
412 
413  switch ( $state ) {
414  case self::COLON_STATE_TEXT:
415  switch ( $c ) {
416  case "<":
417  # Could be either a <start> tag or an </end> tag
418  $state = self::COLON_STATE_TAGSTART;
419  break;
420  case ":":
421  if ( $level === 0 ) {
422  # We found it!
423  $before = substr( $str, 0, $i );
424  $after = substr( $str, $i + 1 );
425  return $i;
426  }
427  # Embedded in a tag; don't break it.
428  break;
429  default:
430  # Skip ahead looking for something interesting
431  $colonPos = strpos( $str, ':', $i );
432  if ( $colonPos === false ) {
433  # Nothing else interesting
434  return false;
435  }
436  $ltPos = strpos( $str, '<', $i );
437  if ( $level === 0 ) {
438  if ( $ltPos === false || $colonPos < $ltPos ) {
439  # We found it!
440  $before = substr( $str, 0, $colonPos );
441  $after = substr( $str, $colonPos + 1 );
442  return $i;
443  }
444  }
445  if ( $ltPos === false ) {
446  # Nothing else interesting to find; abort!
447  # We're nested, but there's no close tags left. Abort!
448  break 2;
449  }
450  # Skip ahead to next tag start
451  $i = $ltPos;
452  $state = self::COLON_STATE_TAGSTART;
453  }
454  break;
455  case self::COLON_STATE_TAG:
456  # In a <tag>
457  switch ( $c ) {
458  case ">":
459  $level++;
460  $state = self::COLON_STATE_TEXT;
461  break;
462  case "/":
463  # Slash may be followed by >?
464  $state = self::COLON_STATE_TAGSLASH;
465  break;
466  default:
467  # ignore
468  }
469  break;
470  case self::COLON_STATE_TAGSTART:
471  switch ( $c ) {
472  case "/":
473  $state = self::COLON_STATE_CLOSETAG;
474  break;
475  case "!":
476  $state = self::COLON_STATE_COMMENT;
477  break;
478  case ">":
479  # Illegal early close? This shouldn't happen D:
480  $state = self::COLON_STATE_TEXT;
481  break;
482  default:
483  $state = self::COLON_STATE_TAG;
484  }
485  break;
486  case self::COLON_STATE_CLOSETAG:
487  # In a </tag>
488  if ( $c === ">" ) {
489  $level--;
490  if ( $level < 0 ) {
491  wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" );
492  return false;
493  }
494  $state = self::COLON_STATE_TEXT;
495  }
496  break;
497  case self::COLON_STATE_TAGSLASH:
498  if ( $c === ">" ) {
499  # Yes, a self-closed tag <blah/>
500  $state = self::COLON_STATE_TEXT;
501  } else {
502  # Probably we're jumping the gun, and this is an attribute
503  $state = self::COLON_STATE_TAG;
504  }
505  break;
506  case self::COLON_STATE_COMMENT:
507  if ( $c === "-" ) {
508  $state = self::COLON_STATE_COMMENTDASH;
509  }
510  break;
511  case self::COLON_STATE_COMMENTDASH:
512  if ( $c === "-" ) {
513  $state = self::COLON_STATE_COMMENTDASHDASH;
514  } else {
515  $state = self::COLON_STATE_COMMENT;
516  }
517  break;
518  case self::COLON_STATE_COMMENTDASHDASH:
519  if ( $c === ">" ) {
520  $state = self::COLON_STATE_TEXT;
521  } else {
522  $state = self::COLON_STATE_COMMENT;
523  }
524  break;
525  default:
526  throw new MWException( "State machine error in " . __METHOD__ );
527  }
528  }
529  if ( $level > 0 ) {
530  wfDebug( __METHOD__ . ": Invalid input; not enough close tags (level $level, state $state)\n" );
531  return false;
532  }
533  return false;
534  }
535 }
const MARKER_PREFIX
Definition: Parser.php:134
external whereas SearchGetNearMatch runs after $term
Definition: hooks.txt:2713
const COLON_STATE_TAGSTART
__construct($text, $lineStart)
Private constructor.
const COLON_STATE_COMMENTDASH
const COLON_STATE_COMMENT
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1934
openList($char)
Open the list item element identified by the prefix character.
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
nextItem($char)
Close the current list item and open the next one.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1046
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
execute()
Execute the pass.
getCommon($st1, $st2)
getCommon() returns the length of the longest common substring of both arguments, starting at the beg...
const COLON_STATE_COMMENTDASHDASH
findColonNoLinks($str, &$before, &$after)
Split up a string on ':', ignoring any occurrences inside tags to prevent illegal overlapping...
static doBlockLevels($text, $lineStart)
Make lists from lines starting with ':', '*', '#', etc.
static explode($separator, $subject)
Workalike for explode() with limited memory usage.
closeParagraph()
If a pre or p is open, return the corresponding close tag and update the state.
const COLON_STATE_TAGSLASH
const COLON_STATE_CLOSETAG
closeList($char)
Close the current list item identified by the prefix character.