MediaWiki REL1_33
RandomImageGenerator.php
Go to the documentation of this file.
1<?php
27
34 private $minWidth = 400;
35 private $maxWidth = 800;
36 private $minHeight = 400;
37 private $maxHeight = 800;
38 private $shapesToDraw = 5;
39
47 private static $orientations = [
48 [
49 '0thRow' => 'top',
50 '0thCol' => 'left',
51 'exifCode' => 1,
52 'counterRotation' => [ [ 1, 0 ], [ 0, 1 ] ]
53 ],
54 [
55 '0thRow' => 'bottom',
56 '0thCol' => 'right',
57 'exifCode' => 3,
58 'counterRotation' => [ [ -1, 0 ], [ 0, -1 ] ]
59 ],
60 [
61 '0thRow' => 'right',
62 '0thCol' => 'top',
63 'exifCode' => 6,
64 'counterRotation' => [ [ 0, 1 ], [ 1, 0 ] ]
65 ],
66 [
67 '0thRow' => 'left',
68 '0thCol' => 'bottom',
69 'exifCode' => 8,
70 'counterRotation' => [ [ 0, -1 ], [ -1, 0 ] ]
71 ]
72 ];
73
74 public function __construct( $options = [] ) {
75 foreach ( [ 'dictionaryFile', 'minWidth', 'minHeight',
76 'maxWidth', 'maxHeight', 'shapesToDraw' ] as $property
77 ) {
78 if ( isset( $options[$property] ) ) {
79 $this->$property = $options[$property];
80 }
81 }
82
83 // find the dictionary file, to generate random names
84 if ( !isset( $this->dictionaryFile ) ) {
85 foreach (
86 [
87 '/usr/share/dict/words',
88 '/usr/dict/words',
89 __DIR__ . '/words.txt'
91 ) {
92 if ( is_file( $dictionaryFile ) && is_readable( $dictionaryFile ) ) {
93 $this->dictionaryFile = $dictionaryFile;
94 break;
95 }
96 }
97 }
98 if ( !isset( $this->dictionaryFile ) ) {
99 throw new Exception( "RandomImageGenerator: dictionary file not "
100 . "found or not specified properly" );
101 }
102 }
103
113 function writeImages( $number, $format = 'jpg', $dir = null ) {
114 $filenames = $this->getRandomFilenames( $number, $format, $dir );
115 $imageWriteMethod = $this->getImageWriteMethod( $format );
116 foreach ( $filenames as $filename ) {
117 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
118 }
119
120 return $filenames;
121 }
122
131 function getImageWriteMethod( $format ) {
133 if ( $format === 'svg' ) {
134 return 'writeSvg';
135 } else {
136 // figure out how to write images
137 global $wgExiv2Command;
138 if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
139 return 'writeImageWithApi';
140 } elseif ( $wgUseImageMagick
142 && is_executable( $wgImageMagickConvertCommand )
143 ) {
144 return 'writeImageWithCommandLine';
145 }
146 }
147 throw new Exception( "RandomImageGenerator: could not find a suitable "
148 . "method to write images in '$format' format" );
149 }
150
160 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
161 if ( is_null( $dir ) ) {
162 $dir = getcwd();
163 }
164 $filenames = [];
165 foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
166 $basename = $pair[0] . '_' . $pair[1];
167 if ( !is_null( $extension ) ) {
168 $basename .= '.' . $extension;
169 }
170 $basename = preg_replace( '/\s+/', '', $basename );
171 $filenames[] = "$dir/$basename";
172 }
173
174 return $filenames;
175 }
176
185 public function getImageSpec() {
186 $spec = [];
187
188 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
189 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
190 $spec['fill'] = $this->getRandomColor();
191
192 $diagonalLength = sqrt( $spec['width'] ** 2 + $spec['height'] ** 2 );
193
194 $draws = [];
195 for ( $i = 0; $i <= $this->shapesToDraw; $i++ ) {
196 $radius = mt_rand( 0, $diagonalLength / 4 );
197 if ( $radius == 0 ) {
198 continue;
199 }
200 $originX = mt_rand( -1 * $radius, $spec['width'] + $radius );
201 $originY = mt_rand( -1 * $radius, $spec['height'] + $radius );
202 $angle = mt_rand( 0, ( 3.141592 / 2 ) * $radius ) / $radius;
203 $legDeltaX = round( $radius * sin( $angle ) );
204 $legDeltaY = round( $radius * cos( $angle ) );
205
206 $draw = [];
207 $draw['fill'] = $this->getRandomColor();
208 $draw['shape'] = [
209 [ 'x' => $originX, 'y' => $originY - $radius ],
210 [ 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ],
211 [ 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ],
212 [ 'x' => $originX, 'y' => $originY - $radius ]
213 ];
214 $draws[] = $draw;
215 }
216
217 $spec['draws'] = $draws;
218
219 return $spec;
220 }
221
229 static function shapePointsToString( $shape ) {
230 $points = [];
231 foreach ( $shape as $point ) {
232 $points[] = $point['x'] . ',' . $point['y'];
233 }
234
235 return implode( " ", $points );
236 }
237
248 public function writeSvg( $spec, $format, $filename ) {
249 $svg = new SimpleXmlElement( '<svg/>' );
250 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
251 $svg->addAttribute( 'version', '1.1' );
252 $svg->addAttribute( 'width', $spec['width'] );
253 $svg->addAttribute( 'height', $spec['height'] );
254 $g = $svg->addChild( 'g' );
255 foreach ( $spec['draws'] as $drawSpec ) {
256 $shape = $g->addChild( 'polygon' );
257 $shape->addAttribute( 'fill', $drawSpec['fill'] );
258 $shape->addAttribute( 'points', self::shapePointsToString( $drawSpec['shape'] ) );
259 }
260
261 $fh = fopen( $filename, 'w' );
262 if ( !$fh ) {
263 throw new Exception( "couldn't open $filename for writing" );
264 }
265 fwrite( $fh, $svg->asXML() );
266 if ( !fclose( $fh ) ) {
267 throw new Exception( "couldn't close $filename" );
268 }
269 }
270
277 public function writeImageWithApi( $spec, $format, $filename ) {
278 // this is a hack because I can't get setImageOrientation() to work. See below.
279 global $wgExiv2Command;
280
281 $image = new Imagick();
288 $orientation = self::$orientations[0]; // default is normal orientation
289 if ( $format == 'jpg' ) {
290 $orientation = self::$orientations[array_rand( self::$orientations )];
291 $spec = self::rotateImageSpec( $spec, $orientation['counterRotation'] );
292 }
293
294 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
295
296 foreach ( $spec['draws'] as $drawSpec ) {
297 $draw = new ImagickDraw();
298 $draw->setFillColor( $drawSpec['fill'] );
299 $draw->polygon( $drawSpec['shape'] );
300 $image->drawImage( $draw );
301 }
302
303 $image->setImageFormat( $format );
304
305 // this doesn't work, even though it's documented to do so...
306 // $image->setImageOrientation( $orientation['exifCode'] );
307
308 $image->writeImage( $filename );
309
310 // because the above setImageOrientation call doesn't work... nor can I
311 // get an external imagemagick binary to do this either... Hacking this
312 // for now (only works if you have exiv2 installed, a program to read
313 // and manipulate exif).
314 if ( $wgExiv2Command ) {
315 $command = Shell::command( $wgExiv2Command,
316 '-M',
317 "set Exif.Image.Orientation {$orientation['exifCode']}",
318 $filename
319 )->includeStderr();
320
321 $result = $command->execute();
322 $retval = $result->getExitCode();
323 if ( $retval !== 0 ) {
324 print "Error with $command: $retval, {$result->getStdout()}\n";
325 }
326 }
327 }
328
336 private static function rotateImageSpec( &$spec, $matrix ) {
337 $tSpec = [];
338 $dims = self::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] );
339 $correctionX = 0;
340 $correctionY = 0;
341 if ( $dims['x'] < 0 ) {
342 $correctionX = abs( $dims['x'] );
343 }
344 if ( $dims['y'] < 0 ) {
345 $correctionY = abs( $dims['y'] );
346 }
347 $tSpec['width'] = abs( $dims['x'] );
348 $tSpec['height'] = abs( $dims['y'] );
349 $tSpec['fill'] = $spec['fill'];
350 $tSpec['draws'] = [];
351 foreach ( $spec['draws'] as $draw ) {
352 $tDraw = [
353 'fill' => $draw['fill'],
354 'shape' => []
355 ];
356 foreach ( $draw['shape'] as $point ) {
357 $tPoint = self::matrixMultiply2x2( $matrix, $point['x'], $point['y'] );
358 $tPoint['x'] += $correctionX;
359 $tPoint['y'] += $correctionY;
360 $tDraw['shape'][] = $tPoint;
361 }
362 $tSpec['draws'][] = $tDraw;
363 }
364
365 return $tSpec;
366 }
367
375 private static function matrixMultiply2x2( $matrix, $x, $y ) {
376 return [
377 'x' => $x * $matrix[0][0] + $y * $matrix[0][1],
378 'y' => $x * $matrix[1][0] + $y * $matrix[1][1]
379 ];
380 }
381
399 public function writeImageWithCommandLine( $spec, $format, $filename ) {
401
402 $args = [
404 '-size',
405 $spec['width'] . 'x' . $spec['height'],
406 "xc:{$spec['fill']}",
407 ];
408 foreach ( $spec['draws'] as $draw ) {
409 $fill = $draw['fill'];
410 $polygon = self::shapePointsToString( $draw['shape'] );
411 $drawCommand = "fill $fill polygon $polygon";
412 $args[] = '-draw';
413 $args[] = $drawCommand;
414 }
415 $args[] = $filename;
416
417 $result = Shell::command( $args )->execute();
418
419 return ( $result->getExitCode() === 0 );
420 }
421
427 public function getRandomColor() {
428 $components = [];
429 for ( $i = 0; $i <= 2; $i++ ) {
430 $components[] = mt_rand( 0, 255 );
431 }
432
433 return 'rgb(' . implode( ', ', $components ) . ')';
434 }
435
443 private function getRandomWordPairs( $number ) {
444 $lines = $this->getRandomLines( $number * 2 );
445 // construct pairs of words
446 $pairs = [];
447 $count = count( $lines );
448 for ( $i = 0; $i < $count; $i += 2 ) {
449 $pairs[] = [ $lines[$i], $lines[$i + 1] ];
450 }
451
452 return $pairs;
453 }
454
465 private function getRandomLines( $number_desired ) {
466 $filepath = $this->dictionaryFile;
467
468 // initialize array of lines
469 $lines = [];
470 for ( $i = 0; $i < $number_desired; $i++ ) {
471 $lines[] = null;
472 }
473
474 /*
475 * This algorithm obtains N random lines from a file in one single pass.
476 * It does this by replacing elements of a fixed-size array of lines,
477 * less and less frequently as it reads the file.
478 */
479 $fh = fopen( $filepath, "r" );
480 if ( !$fh ) {
481 throw new Exception( "couldn't open $filepath" );
482 }
483 $line_number = 0;
484 $max_index = $number_desired - 1;
485 while ( !feof( $fh ) ) {
486 $line = fgets( $fh );
487 if ( $line !== false ) {
488 $line_number++;
489 $line = trim( $line );
490 if ( mt_rand( 0, $line_number ) <= $max_index ) {
491 $lines[mt_rand( 0, $max_index )] = $line;
492 }
493 }
494 }
495 fclose( $fh );
496 if ( $line_number < $number_desired ) {
497 throw new Exception( "not enough lines in $filepath" );
498 }
499
500 return $lines;
501 }
502}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgUseImageMagick
Resizing can be done using PHP's internal image libraries or using ImageMagick or another third-party...
$wgExiv2Command
Some tests and extensions use exiv2 to manipulate the Exif metadata in some image formats.
$wgImageMagickConvertCommand
The convert command shipped with ImageMagick.
$line
Definition cdb.php:59
$command
Definition cdb.php:65
if( $line===false) $args
Definition cdb.php:64
Executes shell commands.
Definition Shell.php:44
RandomImageGenerator: does what it says on the tin.
static shapePointsToString( $shape)
Given [ [ 'x' => 10, 'y' => 20 ], [ 'x' => 30, y=> 5 ] ] returns "10,20 30,5" Useful for SVG and imag...
getImageSpec()
Generate data representing an image of random size (within limits), consisting of randomly colored an...
getImageWriteMethod( $format)
Figure out how we write images.
static rotateImageSpec(&$spec, $matrix)
Given an image specification, produce rotated version This is used when simulating a rotated image ca...
writeSvg( $spec, $format, $filename)
Based on image specification, write a very simple SVG file to disk.
static $orientations
Orientations: 0th row, 0th column, Exif orientation code, rotation 2x2 matrix that is opposite of ori...
static matrixMultiply2x2( $matrix, $x, $y)
Given a matrix and a pair of images, return new position.
getRandomLines( $number_desired)
Return N random lines from a file.
getRandomWordPairs( $number)
Get an array of random pairs of random words, like [ [ 'foo', 'bar' ], [ 'quux', 'baz' ] ];.
getRandomFilenames( $number, $extension='jpg', $dir=null)
Return a number of randomly-generated filenames Each filename uses two words randomly drawn from the ...
writeImageWithCommandLine( $spec, $format, $filename)
Based on an image specification, write such an image to disk, using the command line ImageMagick prog...
writeImageWithApi( $spec, $format, $filename)
Based on an image specification, write such an image to disk, using Imagick PHP extension.
getRandomColor()
Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)".
writeImages( $number, $format='jpg', $dir=null)
Writes random images with random filenames to disk in the directory you specify, or current working d...
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
while(( $__line=Maintenance::readconsole()) !==false) print
Definition eval.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 When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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 see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition hooks.txt:886
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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. '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 '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:Array with elements of the form "language:title" in the order that they will be output. & $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 since 1.28! 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:1991
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 & $options
Definition hooks.txt:1999
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:37
$points
$lines
Definition router.php:61
$property