MediaWiki  master
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 
72  protected $filterCallback;
73 
77  private $parserOptions = [
78  'processing_instruction_handler' => null,
79  'external_dtd_handler' => '',
80  'dtd_handler' => '',
81  'require_safe_dtd' => true
82  ];
83 
110  public function __construct( $input, $filterCallback = null, $isFile = true, $options = [] ) {
111  $this->filterCallback = $filterCallback;
112  $this->parserOptions = array_merge( $this->parserOptions, $options );
113  $this->validateFromInput( $input, $isFile );
114  }
115 
127  public static function newFromFilename( $fname, $filterCallback = null ) {
128  return new self( $fname, $filterCallback, true );
129  }
130 
142  public static function newFromString( $string, $filterCallback = null ) {
143  return new self( $string, $filterCallback, false );
144  }
145 
151  public function getRootElement() {
152  return $this->rootElement;
153  }
154 
159  private function validateFromInput( $xml, $isFile ) {
160  $reader = new XMLReader();
161  if ( $isFile ) {
162  $s = $reader->open( $xml, null, LIBXML_NOERROR | LIBXML_NOWARNING );
163  } else {
164  $s = $reader->XML( $xml, null, LIBXML_NOERROR | LIBXML_NOWARNING );
165  }
166  if ( $s !== true ) {
167  // Couldn't open the XML
168  $this->wellFormed = false;
169  } else {
170  $oldDisable = libxml_disable_entity_loader( true );
171  $reader->setParserProperty( XMLReader::SUBST_ENTITIES, true );
172  try {
173  $this->validate( $reader );
174  } catch ( Exception $e ) {
175  // Calling this malformed, because we didn't parse the whole
176  // thing. Maybe just an external entity refernce.
177  $this->wellFormed = false;
178  $reader->close();
179  libxml_disable_entity_loader( $oldDisable );
180  throw $e;
181  }
182  $reader->close();
183  libxml_disable_entity_loader( $oldDisable );
184  }
185  }
186 
187  private function readNext( XMLReader $reader ) {
188  set_error_handler( function ( $line, $file ) {
189  $this->wellFormed = false;
190  } );
191  $ret = $reader->read();
192  restore_error_handler();
193  return $ret;
194  }
195 
196  private function validate( $reader ) {
197  // First, move through anything that isn't an element, and
198  // handle any processing instructions with the callback
199  do {
200  if ( !$this->readNext( $reader ) ) {
201  // Hit the end of the document before any elements
202  $this->wellFormed = false;
203  return;
204  }
205  if ( $reader->nodeType === XMLReader::PI ) {
206  $this->processingInstructionHandler( $reader->name, $reader->value );
207  }
208  if ( $reader->nodeType === XMLReader::DOC_TYPE ) {
209  $this->dtdHandler( $reader );
210  }
211  } while ( $reader->nodeType != XMLReader::ELEMENT );
212 
213  // Process the rest of the document
214  do {
215  switch ( $reader->nodeType ) {
216  case XMLReader::ELEMENT:
217  $name = $this->expandNS(
218  $reader->name,
219  $reader->namespaceURI
220  );
221  if ( $this->rootElement === '' ) {
222  $this->rootElement = $name;
223  }
224  $empty = $reader->isEmptyElement;
225  $attrs = $this->getAttributesArray( $reader );
226  $this->elementOpen( $name, $attrs );
227  if ( $empty ) {
228  $this->elementClose();
229  }
230  break;
231 
232  case XMLReader::END_ELEMENT:
233  $this->elementClose();
234  break;
235 
236  case XMLReader::WHITESPACE:
237  case XMLReader::SIGNIFICANT_WHITESPACE:
238  case XMLReader::CDATA:
239  case XMLReader::TEXT:
240  $this->elementData( $reader->value );
241  break;
242 
243  case XMLReader::ENTITY_REF:
244  // Unexpanded entity (maybe external?),
245  // don't send to the filter (xml_parse didn't)
246  break;
247 
248  case XMLReader::COMMENT:
249  // Don't send to the filter (xml_parse didn't)
250  break;
251 
252  case XMLReader::PI:
253  // Processing instructions can happen after the header too
255  $reader->name,
256  $reader->value
257  );
258  break;
259  case XMLReader::DOC_TYPE:
260  // We should never see a doctype after first
261  // element.
262  $this->wellFormed = false;
263  break;
264  default:
265  // One of DOC, ENTITY, END_ENTITY,
266  // NOTATION, or XML_DECLARATION
267  // xml_parse didn't send these to the filter, so we won't.
268  }
269  } while ( $this->readNext( $reader ) );
270 
271  if ( $this->stackDepth !== 0 ) {
272  $this->wellFormed = false;
273  } elseif ( $this->wellFormed === null ) {
274  $this->wellFormed = true;
275  }
276  }
277 
283  private function getAttributesArray( XMLReader $r ) {
284  $attrs = [];
285  while ( $r->moveToNextAttribute() ) {
286  if ( $r->namespaceURI === 'http://www.w3.org/2000/xmlns/' ) {
287  // XMLReader treats xmlns attributes as normal
288  // attributes, while xml_parse doesn't
289  continue;
290  }
291  $name = $this->expandNS( $r->name, $r->namespaceURI );
292  $attrs[$name] = $r->value;
293  }
294  return $attrs;
295  }
296 
302  private function expandNS( $name, $namespaceURI ) {
303  if ( $namespaceURI ) {
304  $parts = explode( ':', $name );
305  $localname = array_pop( $parts );
306  return "$namespaceURI:$localname";
307  }
308  return $name;
309  }
310 
315  private function elementOpen( $name, $attribs ) {
316  $this->elementDataContext[] = [ $name, $attribs ];
317  $this->elementData[] = '';
318  $this->stackDepth++;
319  }
320 
321  private function elementClose() {
322  list( $name, $attribs ) = array_pop( $this->elementDataContext );
323  $data = array_pop( $this->elementData );
324  $this->stackDepth--;
325  $callbackReturn = false;
326 
327  if ( is_callable( $this->filterCallback ) ) {
328  $callbackReturn = call_user_func(
329  $this->filterCallback,
330  $name,
331  $attribs,
332  $data
333  );
334  }
335  if ( $callbackReturn ) {
336  // Filter hit!
337  $this->filterMatch = true;
338  $this->filterMatchType = $callbackReturn;
339  }
340  }
341 
345  private function elementData( $data ) {
346  // Collect any data here, and we'll run the callback in elementClose
347  $this->elementData[ $this->stackDepth - 1 ] .= trim( $data );
348  }
349 
354  private function processingInstructionHandler( $target, $data ) {
355  $callbackReturn = false;
356  if ( $this->parserOptions['processing_instruction_handler'] ) {
357  $callbackReturn = call_user_func(
358  $this->parserOptions['processing_instruction_handler'],
359  $target,
360  $data
361  );
362  }
363  if ( $callbackReturn ) {
364  // Filter hit!
365  $this->filterMatch = true;
366  $this->filterMatchType = $callbackReturn;
367  }
368  }
369 
375  private function dtdHandler( XMLReader $reader ) {
376  $externalCallback = $this->parserOptions['external_dtd_handler'];
377  $generalCallback = $this->parserOptions['dtd_handler'];
378  $checkIfSafe = $this->parserOptions['require_safe_dtd'];
379  if ( !$externalCallback && !$generalCallback && !$checkIfSafe ) {
380  return;
381  }
382  $dtd = $reader->readOuterXml();
383  $callbackReturn = false;
384 
385  if ( $generalCallback ) {
386  $callbackReturn = call_user_func( $generalCallback, $dtd );
387  }
388  if ( $callbackReturn ) {
389  // Filter hit!
390  $this->filterMatch = true;
391  $this->filterMatchType = $callbackReturn;
392  $callbackReturn = false;
393  }
394 
395  $parsedDTD = $this->parseDTD( $dtd );
396  if ( $externalCallback && isset( $parsedDTD['type'] ) ) {
397  $callbackReturn = call_user_func(
398  $externalCallback,
399  $parsedDTD['type'],
400  $parsedDTD['publicid'] ?? null,
401  $parsedDTD['systemid'] ?? null
402  );
403  }
404  if ( $callbackReturn ) {
405  // Filter hit!
406  $this->filterMatch = true;
407  $this->filterMatchType = $callbackReturn;
408  }
409 
410  if ( $checkIfSafe && isset( $parsedDTD['internal'] ) &&
411  !$this->checkDTDIsSafe( $parsedDTD['internal'] )
412  ) {
413  $this->wellFormed = false;
414  }
415  }
416 
437  private function checkDTDIsSafe( $internalSubset ) {
438  $res = preg_match(
439  '/^(?:\s*<!ENTITY\s+\S+\s+' .
440  '(?:"(?:&[^"%&;]{1,64};|(?:[^"%&]|&amp;|&quot;){0,255})"' .
441  '|\'(?:&[^"%&;]{1,64};|(?:[^\'%&]|&amp;|&apos;){0,255})\')\s*>' .
442  '|\s*<!--(?:[^-]|-[^-])*-->' .
443  '|\s*<!ATTLIST svg xmlns:xlink CDATA #FIXED ' .
444  '"http:\/\/www.w3.org\/1999\/xlink">)*\s*$/',
445  $internalSubset
446  );
447 
448  return (bool)$res;
449  }
450 
459  private function parseDTD( $dtd ) {
460  $m = [];
461  $res = preg_match(
462  '/^<!DOCTYPE\s*\S+\s*' .
463  '(?:(?P<typepublic>PUBLIC)\s*' .
464  '(?:"(?P<pubquote>[^"]*)"|\'(?P<pubapos>[^\']*)\')' . // public identifer
465  '\s*"(?P<pubsysquote>[^"]*)"|\'(?P<pubsysapos>[^\']*)\'' . // system identifier
466  '|(?P<typesystem>SYSTEM)\s*' .
467  '(?:"(?P<sysquote>[^"]*)"|\'(?P<sysapos>[^\']*)\')' .
468  ')?\s*' .
469  '(?:\[\s*(?P<internal>.*)\])?\s*>$/s',
470  $dtd,
471  $m
472  );
473  if ( !$res ) {
474  $this->wellFormed = false;
475  return [];
476  }
477  $parsed = [];
478  foreach ( $m as $field => $value ) {
479  if ( $value === '' || is_numeric( $field ) ) {
480  continue;
481  }
482  switch ( $field ) {
483  case 'typepublic':
484  case 'typesystem':
485  $parsed['type'] = $value;
486  break;
487  case 'pubquote':
488  case 'pubapos':
489  $parsed['publicid'] = $value;
490  break;
491  case 'pubsysquote':
492  case 'pubsysapos':
493  case 'sysquote':
494  case 'sysapos':
495  $parsed['systemid'] = $value;
496  break;
497  case 'internal':
498  $parsed['internal'] = $value;
499  break;
500  }
501  }
502  return $parsed;
503  }
504 }
processingInstructionHandler( $target, $data)
readNext(XMLReader $reader)
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
bool null $wellFormed
Will be set to true or false to indicate whether the file is well-formed XML.
validate( $reader)
elementData( $data)
validateFromInput( $xml, $isFile)
array __construct( $input, $filterCallback=null, $isFile=true, $options=[])
Allow filtering an XML file.
getRootElement()
Get the root element.
checkDTDIsSafe( $internalSubset)
Check if the internal subset of the DTD is safe.
static newFromFilename( $fname, $filterCallback=null)
Alternative constructor: from filename.
elementOpen( $name, $attribs)
static newFromString( $string, $filterCallback=null)
Alternative constructor: from string.
int $stackDepth
Current depth of the data stack.
bool $filterMatch
Will be set to true if the optional element filter returned a match at some point.
mixed $filterMatchType
Will contain the type of filter hit if the optional element filter returned a match at some point...
parseDTD( $dtd)
Parse DTD into parts.
string [] $elementData
A stack of strings containing the data of each xml element as it&#39;s processed.
callable null $filterCallback
getAttributesArray(XMLReader $r)
Get all of the attributes for an XMLReader&#39;s current node.
expandNS( $name, $namespaceURI)
$line
Definition: mcc.php:119
array $elementDataContext
A stack of element names and attributes, as we process them.
string $rootElement
Name of the document&#39;s root element, including any namespace as an expanded URL.
dtdHandler(XMLReader $reader)
Handle coming across a <!DOCTYPE declaration.
return true
Definition: router.php:92
array $parserOptions
Additional parsing options.