MediaWiki  1.27.2
preprocessorFuzzTest.php
Go to the documentation of this file.
1 <?php
24 $optionsWithoutArgs = [ 'verbose' ];
25 require_once __DIR__ . '/commandLine.inc';
26 
27 $wgHooks['BeforeParserFetchTemplateAndtitle'][] = 'PPFuzzTester::templateHook';
28 
29 class PPFuzzTester {
30  public $hairs = [
31  '[[', ']]', '{{', '{{', '}}', '}}', '{{{', '}}}',
32  '<', '>', '<nowiki', '<gallery', '</nowiki>', '</gallery>', '<nOwIkI>', '</NoWiKi>',
33  '<!--', '-->',
34  "\n==", "==\n",
35  '|', '=', "\n", ' ', "\t", "\x7f",
36  '~~', '~~~', '~~~~', 'subst:',
37  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
38  'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
39 
40  // extensions
41  // '<ref>', '</ref>', '<references/>',
42  ];
43  public $minLength = 0;
44  public $maxLength = 20;
45  public $maxTemplates = 5;
46  // public $outputTypes = array( 'OT_HTML', 'OT_WIKI', 'OT_PREPROCESS' );
47  public $entryPoints = [ 'testSrvus', 'testPst', 'testPreprocess' ];
48  public $verbose = false;
49 
50  private static $currentTest = false;
51 
52  function execute() {
53  if ( !file_exists( 'results' ) ) {
54  mkdir( 'results' );
55  }
56  if ( !is_dir( 'results' ) ) {
57  echo "Unable to create 'results' directory\n";
58  exit( 1 );
59  }
60  $overallStart = microtime( true );
61  $reportInterval = 1000;
62  for ( $i = 1; true; $i++ ) {
63  $t = -microtime( true );
64  try {
65  self::$currentTest = new PPFuzzTest( $this );
66  self::$currentTest->execute();
67  $passed = 'passed';
68  } catch ( Exception $e ) {
69  $testReport = self::$currentTest->getReport();
70  $exceptionReport = $e->getText();
71  $hash = md5( $testReport );
72  file_put_contents( "results/ppft-$hash.in", serialize( self::$currentTest ) );
73  file_put_contents( "results/ppft-$hash.fail",
74  "Input:\n$testReport\n\nException report:\n$exceptionReport\n" );
75  print "Test $hash failed\n";
76  $passed = 'failed';
77  }
78  $t += microtime( true );
79 
80  if ( $this->verbose ) {
81  printf( "Test $passed in %.3f seconds\n", $t );
82  print self::$currentTest->getReport();
83  }
84 
85  $reportMetric = ( microtime( true ) - $overallStart ) / $i * $reportInterval;
86  if ( $reportMetric > 25 ) {
87  if ( substr( $reportInterval, 0, 1 ) === '1' ) {
88  $reportInterval /= 2;
89  } else {
90  $reportInterval /= 5;
91  }
92  } elseif ( $reportMetric < 4 ) {
93  if ( substr( $reportInterval, 0, 1 ) === '1' ) {
94  $reportInterval *= 5;
95  } else {
96  $reportInterval *= 2;
97  }
98  }
99  if ( $i % $reportInterval == 0 ) {
100  print "$i tests done\n";
101  /*
102  $testReport = self::$currentTest->getReport();
103  $filename = 'results/ppft-' . md5( $testReport ) . '.pass';
104  file_put_contents( $filename, "Input:\n$testReport\n" );*/
105  }
106  }
107  }
108 
109  function makeInputText( $max = false ) {
110  if ( $max === false ) {
111  $max = $this->maxLength;
112  }
113  $length = mt_rand( $this->minLength, $max );
114  $s = '';
115  for ( $i = 0; $i < $length; $i++ ) {
116  $hairIndex = mt_rand( 0, count( $this->hairs ) - 1 );
117  $s .= $this->hairs[$hairIndex];
118  }
119  // Send through the UTF-8 normaliser
120  // This resolves a few differences between the old preprocessor and the
121  // XML-based one, which doesn't like illegals and converts line endings.
122  // It's done by the MW UI, so it's a reasonably legitimate thing to do.
124  $s = $wgContLang->normalize( $s );
125 
126  return $s;
127  }
128 
129  function makeTitle() {
130  return Title::newFromText( mt_rand( 0, 1000000 ), mt_rand( 0, 10 ) );
131  }
132 
133  /*
134  function pickOutputType() {
135  $count = count( $this->outputTypes );
136  return $this->outputTypes[ mt_rand( 0, $count - 1 ) ];
137  }*/
138 
139  function pickEntryPoint() {
140  $count = count( $this->entryPoints );
141 
142  return $this->entryPoints[mt_rand( 0, $count - 1 )];
143  }
144 }
145 
146 class PPFuzzTest {
148 
149  function __construct( $tester ) {
150  global $wgMaxSigChars;
151  $this->parent = $tester;
152  $this->mainText = $tester->makeInputText();
153  $this->title = $tester->makeTitle();
154  // $this->outputType = $tester->pickOutputType();
155  $this->entryPoint = $tester->pickEntryPoint();
156  $this->nickname = $tester->makeInputText( $wgMaxSigChars + 10 );
157  $this->fancySig = (bool)mt_rand( 0, 1 );
158  $this->templates = [];
159  }
160 
165  function templateHook( $title ) {
166  $titleText = $title->getPrefixedDBkey();
167 
168  if ( !isset( $this->templates[$titleText] ) ) {
169  $finalTitle = $title;
170  if ( count( $this->templates ) >= $this->parent->maxTemplates ) {
171  // Too many templates
172  $text = false;
173  } else {
174  if ( !mt_rand( 0, 1 ) ) {
175  // Redirect
176  $finalTitle = $this->parent->makeTitle();
177  }
178  if ( !mt_rand( 0, 5 ) ) {
179  // Doesn't exist
180  $text = false;
181  } else {
182  $text = $this->parent->makeInputText();
183  }
184  }
185  $this->templates[$titleText] = [
186  'text' => $text,
187  'finalTitle' => $finalTitle ];
188  }
189 
190  return $this->templates[$titleText];
191  }
192 
193  function execute() {
195 
196  $wgUser = new PPFuzzUser;
197  $wgUser->mName = 'Fuzz';
198  $wgUser->mFrom = 'name';
199  $wgUser->ppfz_test = $this;
200 
202  $options->setTemplateCallback( [ $this, 'templateHook' ] );
203  $options->setTimestamp( wfTimestampNow() );
204  $this->output = call_user_func(
205  [ $wgParser, $this->entryPoint ],
206  $this->mainText,
207  $this->title,
208  $options
209  );
210 
211  return $this->output;
212  }
213 
214  function getReport() {
215  $s = "Title: " . $this->title->getPrefixedDBkey() . "\n" .
216 // "Output type: {$this->outputType}\n" .
217  "Entry point: {$this->entryPoint}\n" .
218  "User: " . ( $this->fancySig ? 'fancy' : 'no-fancy' ) .
219  ' ' . var_export( $this->nickname, true ) . "\n" .
220  "Main text: " . var_export( $this->mainText, true ) . "\n";
221  foreach ( $this->templates as $titleText => $template ) {
222  $finalTitle = $template['finalTitle'];
223  if ( $finalTitle != $titleText ) {
224  $s .= "[[$titleText]] -> [[$finalTitle]]: " . var_export( $template['text'], true ) . "\n";
225  } else {
226  $s .= "[[$titleText]]: " . var_export( $template['text'], true ) . "\n";
227  }
228  }
229  $s .= "Output: " . var_export( $this->output, true ) . "\n";
230 
231  return $s;
232  }
233 }
234 
235 class PPFuzzUser extends User {
237 
238  function load() {
239  if ( $this->mDataLoaded ) {
240  return;
241  }
242  $this->mDataLoaded = true;
243  $this->loadDefaults( $this->mName );
244  }
245 
246  function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
247  if ( $oname === 'fancysig' ) {
248  return $this->ppfz_test->fancySig;
249  } elseif ( $oname === 'nickname' ) {
250  return $this->ppfz_test->nickname;
251  } else {
252  return parent::getOption( $oname, $defaultOverride, $ignoreHidden );
253  }
254  }
255 }
256 
257 ini_set( 'memory_limit', '50M' );
258 if ( isset( $args[0] ) ) {
259  $testText = file_get_contents( $args[0] );
260  if ( !$testText ) {
261  print "File not found\n";
262  exit( 1 );
263  }
264  $test = unserialize( $testText );
265  $result = $test->execute();
266  print "Test passed.\n";
267 } else {
268  $tester = new PPFuzzTester;
269  $tester->verbose = isset( $options['verbose'] );
270  $tester->execute();
271 }
makeInputText($max=false)
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
$wgParser
Definition: Setup.php:809
if(isset($options['help'])) if($wgDBtype== 'sqlite') $tester
Definition: parserTests.php:75
$optionsWithoutArgs
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static newFromUser($user)
Get a ParserOptions object from a given user.
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':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:1796
if($line===false) $args
Definition: cdb.php:64
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping $template
Definition: hooks.txt:762
loadDefaults($name=false)
Set cached properties to default.
Definition: User.php:1134
unserialize($serialized)
Definition: ApiMessage.php:102
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
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
title
getOption($oname, $defaultOverride=null, $ignoreHidden=false)
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
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
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
$count
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 in any and then calling output() to send it all.It could be easily changed to send incrementally if that becomes useful
serialize()
Definition: ApiMessage.php:94
$tester verbose
$wgHooks['BeforeParserFetchTemplateAndtitle'][]
$wgUser
Definition: Setup.php:794