MediaWiki  1.27.1
XmlTypeCheck.php
Go to the documentation of this file.
1 <?php
28 class XmlTypeCheck {
33  public $wellFormed = null;
34 
39  public $filterMatch = false;
40 
46  public $filterMatchType = false;
47 
52  public $rootElement = '';
53 
59  protected $elementData = [];
60 
64  protected $elementDataContext = [];
65 
69  protected $stackDepth = 0;
70 
74  private $parserOptions = [
75  'processing_instruction_handler' => '',
76  ];
77 
90  function __construct( $input, $filterCallback = null, $isFile = true, $options = [] ) {
91  $this->filterCallback = $filterCallback;
92  $this->parserOptions = array_merge( $this->parserOptions, $options );
93  $this->validateFromInput( $input, $isFile );
94  }
95 
107  public static function newFromFilename( $fname, $filterCallback = null ) {
108  return new self( $fname, $filterCallback, true );
109  }
110 
122  public static function newFromString( $string, $filterCallback = null ) {
123  return new self( $string, $filterCallback, false );
124  }
125 
131  public function getRootElement() {
132  return $this->rootElement;
133  }
134 
138  private function validateFromInput( $xml, $isFile ) {
139  $reader = new XMLReader();
140  if ( $isFile ) {
141  $s = $reader->open( $xml, null, LIBXML_NOERROR | LIBXML_NOWARNING );
142  } else {
143  $s = $reader->XML( $xml, null, LIBXML_NOERROR | LIBXML_NOWARNING );
144  }
145  if ( $s !== true ) {
146  // Couldn't open the XML
147  $this->wellFormed = false;
148  } else {
149  $oldDisable = libxml_disable_entity_loader( true );
150  $reader->setParserProperty( XMLReader::SUBST_ENTITIES, true );
151  try {
152  $this->validate( $reader );
153  } catch ( Exception $e ) {
154  // Calling this malformed, because we didn't parse the whole
155  // thing. Maybe just an external entity refernce.
156  $this->wellFormed = false;
157  $reader->close();
158  libxml_disable_entity_loader( $oldDisable );
159  throw $e;
160  }
161  $reader->close();
162  libxml_disable_entity_loader( $oldDisable );
163  }
164  }
165 
166  private function readNext( XMLReader $reader ) {
167  set_error_handler( [ $this, 'XmlErrorHandler' ] );
168  $ret = $reader->read();
169  restore_error_handler();
170  return $ret;
171  }
172 
173  public function XmlErrorHandler( $errno, $errstr ) {
174  $this->wellFormed = false;
175  }
176 
177  private function validate( $reader ) {
178 
179  // First, move through anything that isn't an element, and
180  // handle any processing instructions with the callback
181  do {
182  if ( !$this->readNext( $reader ) ) {
183  // Hit the end of the document before any elements
184  $this->wellFormed = false;
185  return;
186  }
187  if ( $reader->nodeType === XMLReader::PI ) {
188  $this->processingInstructionHandler( $reader->name, $reader->value );
189  }
190  } while ( $reader->nodeType != XMLReader::ELEMENT );
191 
192  // Process the rest of the document
193  do {
194  switch ( $reader->nodeType ) {
195  case XMLReader::ELEMENT:
196  $name = $this->expandNS(
197  $reader->name,
198  $reader->namespaceURI
199  );
200  if ( $this->rootElement === '' ) {
201  $this->rootElement = $name;
202  }
203  $empty = $reader->isEmptyElement;
204  $attrs = $this->getAttributesArray( $reader );
205  $this->elementOpen( $name, $attrs );
206  if ( $empty ) {
207  $this->elementClose();
208  }
209  break;
210 
211  case XMLReader::END_ELEMENT:
212  $this->elementClose();
213  break;
214 
215  case XMLReader::WHITESPACE:
216  case XMLReader::SIGNIFICANT_WHITESPACE:
217  case XMLReader::CDATA:
218  case XMLReader::TEXT:
219  $this->elementData( $reader->value );
220  break;
221 
222  case XMLReader::ENTITY_REF:
223  // Unexpanded entity (maybe external?),
224  // don't send to the filter (xml_parse didn't)
225  break;
226 
227  case XMLReader::COMMENT:
228  // Don't send to the filter (xml_parse didn't)
229  break;
230 
231  case XMLReader::PI:
232  // Processing instructions can happen after the header too
234  $reader->name,
235  $reader->value
236  );
237  break;
238  default:
239  // One of DOC, DOC_TYPE, ENTITY, END_ENTITY,
240  // NOTATION, or XML_DECLARATION
241  // xml_parse didn't send these to the filter, so we won't.
242  }
243 
244  } while ( $this->readNext( $reader ) );
245 
246  if ( $this->stackDepth !== 0 ) {
247  $this->wellFormed = false;
248  } elseif ( $this->wellFormed === null ) {
249  $this->wellFormed = true;
250  }
251 
252  }
253 
259  private function getAttributesArray( XMLReader $r ) {
260  $attrs = [];
261  while ( $r->moveToNextAttribute() ) {
262  if ( $r->namespaceURI === 'http://www.w3.org/2000/xmlns/' ) {
263  // XMLReader treats xmlns attributes as normal
264  // attributes, while xml_parse doesn't
265  continue;
266  }
267  $name = $this->expandNS( $r->name, $r->namespaceURI );
268  $attrs[$name] = $r->value;
269  }
270  return $attrs;
271  }
272 
278  private function expandNS( $name, $namespaceURI ) {
279  if ( $namespaceURI ) {
280  $parts = explode( ':', $name );
281  $localname = array_pop( $parts );
282  return "$namespaceURI:$localname";
283  }
284  return $name;
285  }
286 
291  private function elementOpen( $name, $attribs ) {
292  $this->elementDataContext[] = [ $name, $attribs ];
293  $this->elementData[] = '';
294  $this->stackDepth++;
295  }
296 
299  private function elementClose() {
300  list( $name, $attribs ) = array_pop( $this->elementDataContext );
301  $data = array_pop( $this->elementData );
302  $this->stackDepth--;
303  $callbackReturn = false;
304 
305  if ( is_callable( $this->filterCallback ) ) {
306  $callbackReturn = call_user_func(
307  $this->filterCallback,
308  $name,
309  $attribs,
310  $data
311  );
312  }
313  if ( $callbackReturn ) {
314  // Filter hit!
315  $this->filterMatch = true;
316  $this->filterMatchType = $callbackReturn;
317  }
318  }
319 
323  private function elementData( $data ) {
324  // Collect any data here, and we'll run the callback in elementClose
325  $this->elementData[ $this->stackDepth - 1 ] .= trim( $data );
326  }
327 
332  private function processingInstructionHandler( $target, $data ) {
333  $callbackReturn = false;
334  if ( $this->parserOptions['processing_instruction_handler'] ) {
335  $callbackReturn = call_user_func(
336  $this->parserOptions['processing_instruction_handler'],
337  $target,
338  $data
339  );
340  }
341  if ( $callbackReturn ) {
342  // Filter hit!
343  $this->filterMatch = true;
344  $this->filterMatchType = $callbackReturn;
345  }
346  }
347 }
readNext(XMLReader $reader)
$parserOptions
Additional parsing options.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
static newFromString($string, $filterCallback=null)
Alternative constructor: from string.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1798
validateFromInput($xml, $isFile)
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
expandNS($name, $namespaceURI)
elementData($data)
getRootElement()
Get the root element.
processingInstructionHandler($target, $data)
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1798
XmlErrorHandler($errno, $errstr)
$stackDepth
Current depth of the data stack.
elementOpen($name, $attribs)
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 $options
Definition: hooks.txt:1004
mixed $filterMatchType
Will contain the type of filter hit if the optional element filter returned a match at some point...
static newFromFilename($fname, $filterCallback=null)
Alternative constructor: from filename.
$rootElement
Name of the document's root element, including any namespace as an expanded URL.
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
__construct($input, $filterCallback=null, $isFile=true, $options=[])
$elementData
A stack of strings containing the data of each xml element as it's processed.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:35
$filterMatch
Will be set to true if the optional element filter returned a match at some point.
getAttributesArray(XMLReader $r)
Get all of the attributes for an XMLReader's current node.
$elementDataContext
A stack of element names and attributes, as we process them.
$wellFormed
Will be set to true or false to indicate whether the file is well-formed XML.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition: hooks.txt:1798
validate($reader)
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310