MediaWiki REL1_30
RandomImageGenerator.php
Go to the documentation of this file.
1<?php
32 private $minWidth = 400;
33 private $maxWidth = 800;
34 private $minHeight = 400;
35 private $maxHeight = 800;
36 private $shapesToDraw = 5;
37
45 private static $orientations = [
46 [
47 '0thRow' => 'top',
48 '0thCol' => 'left',
49 'exifCode' => 1,
50 'counterRotation' => [ [ 1, 0 ], [ 0, 1 ] ]
51 ],
52 [
53 '0thRow' => 'bottom',
54 '0thCol' => 'right',
55 'exifCode' => 3,
56 'counterRotation' => [ [ -1, 0 ], [ 0, -1 ] ]
57 ],
58 [
59 '0thRow' => 'right',
60 '0thCol' => 'top',
61 'exifCode' => 6,
62 'counterRotation' => [ [ 0, 1 ], [ 1, 0 ] ]
63 ],
64 [
65 '0thRow' => 'left',
66 '0thCol' => 'bottom',
67 'exifCode' => 8,
68 'counterRotation' => [ [ 0, -1 ], [ -1, 0 ] ]
69 ]
70 ];
71
72 public function __construct( $options = [] ) {
73 foreach ( [ 'dictionaryFile', 'minWidth', 'minHeight',
74 'maxWidth', 'maxHeight', 'shapesToDraw' ] as $property
75 ) {
76 if ( isset( $options[$property] ) ) {
77 $this->$property = $options[$property];
78 }
79 }
80
81 // find the dictionary file, to generate random names
82 if ( !isset( $this->dictionaryFile ) ) {
83 foreach (
84 [
85 '/usr/share/dict/words',
86 '/usr/dict/words',
87 __DIR__ . '/words.txt'
89 ) {
90 if ( is_file( $dictionaryFile ) && is_readable( $dictionaryFile ) ) {
91 $this->dictionaryFile = $dictionaryFile;
92 break;
93 }
94 }
95 }
96 if ( !isset( $this->dictionaryFile ) ) {
97 throw new Exception( "RandomImageGenerator: dictionary file not "
98 . "found or not specified properly" );
99 }
100 }
101
111 function writeImages( $number, $format = 'jpg', $dir = null ) {
112 $filenames = $this->getRandomFilenames( $number, $format, $dir );
113 $imageWriteMethod = $this->getImageWriteMethod( $format );
114 foreach ( $filenames as $filename ) {
115 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
116 }
117
118 return $filenames;
119 }
120
129 function getImageWriteMethod( $format ) {
131 if ( $format === 'svg' ) {
132 return 'writeSvg';
133 } else {
134 // figure out how to write images
135 global $wgExiv2Command;
136 if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
137 return 'writeImageWithApi';
138 } elseif ( $wgUseImageMagick
140 && is_executable( $wgImageMagickConvertCommand )
141 ) {
142 return 'writeImageWithCommandLine';
143 }
144 }
145 throw new Exception( "RandomImageGenerator: could not find a suitable "
146 . "method to write images in '$format' format" );
147 }
148
158 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
159 if ( is_null( $dir ) ) {
160 $dir = getcwd();
161 }
162 $filenames = [];
163 foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
164 $basename = $pair[0] . '_' . $pair[1];
165 if ( !is_null( $extension ) ) {
166 $basename .= '.' . $extension;
167 }
168 $basename = preg_replace( '/\s+/', '', $basename );
169 $filenames[] = "$dir/$basename";
170 }
171
172 return $filenames;
173 }
174
183 public function getImageSpec() {
184 $spec = [];
185
186 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
187 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
188 $spec['fill'] = $this->getRandomColor();
189
190 $diagonalLength = sqrt( pow( $spec['width'], 2 ) + pow( $spec['height'], 2 ) );
191
192 $draws = [];
193 for ( $i = 0; $i <= $this->shapesToDraw; $i++ ) {
194 $radius = mt_rand( 0, $diagonalLength / 4 );
195 if ( $radius == 0 ) {
196 continue;
197 }
198 $originX = mt_rand( -1 * $radius, $spec['width'] + $radius );
199 $originY = mt_rand( -1 * $radius, $spec['height'] + $radius );
200 $angle = mt_rand( 0, ( 3.141592 / 2 ) * $radius ) / $radius;
201 $legDeltaX = round( $radius * sin( $angle ) );
202 $legDeltaY = round( $radius * cos( $angle ) );
203
204 $draw = [];
205 $draw['fill'] = $this->getRandomColor();
206 $draw['shape'] = [
207 [ 'x' => $originX, 'y' => $originY - $radius ],
208 [ 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ],
209 [ 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ],
210 [ 'x' => $originX, 'y' => $originY - $radius ]
211 ];
212 $draws[] = $draw;
213 }
214
215 $spec['draws'] = $draws;
216
217 return $spec;
218 }
219
227 static function shapePointsToString( $shape ) {
228 $points = [];
229 foreach ( $shape as $point ) {
230 $points[] = $point['x'] . ',' . $point['y'];
231 }
232
233 return implode( " ", $points );
234 }
235
246 public function writeSvg( $spec, $format, $filename ) {
247 $svg = new SimpleXmlElement( '<svg/>' );
248 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
249 $svg->addAttribute( 'version', '1.1' );
250 $svg->addAttribute( 'width', $spec['width'] );
251 $svg->addAttribute( 'height', $spec['height'] );
252 $g = $svg->addChild( 'g' );
253 foreach ( $spec['draws'] as $drawSpec ) {
254 $shape = $g->addChild( 'polygon' );
255 $shape->addAttribute( 'fill', $drawSpec['fill'] );
256 $shape->addAttribute( 'points', self::shapePointsToString( $drawSpec['shape'] ) );
257 }
258
259 $fh = fopen( $filename, 'w' );
260 if ( !$fh ) {
261 throw new Exception( "couldn't open $filename for writing" );
262 }
263 fwrite( $fh, $svg->asXML() );
264 if ( !fclose( $fh ) ) {
265 throw new Exception( "couldn't close $filename" );
266 }
267 }
268
275 public function writeImageWithApi( $spec, $format, $filename ) {
276 // this is a hack because I can't get setImageOrientation() to work. See below.
277 global $wgExiv2Command;
278
279 $image = new Imagick();
286 $orientation = self::$orientations[0]; // default is normal orientation
287 if ( $format == 'jpg' ) {
288 $orientation = self::$orientations[array_rand( self::$orientations )];
289 $spec = self::rotateImageSpec( $spec, $orientation['counterRotation'] );
290 }
291
292 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
293
294 foreach ( $spec['draws'] as $drawSpec ) {
295 $draw = new ImagickDraw();
296 $draw->setFillColor( $drawSpec['fill'] );
297 $draw->polygon( $drawSpec['shape'] );
298 $image->drawImage( $draw );
299 }
300
301 $image->setImageFormat( $format );
302
303 // this doesn't work, even though it's documented to do so...
304 // $image->setImageOrientation( $orientation['exifCode'] );
305
306 $image->writeImage( $filename );
307
308 // because the above setImageOrientation call doesn't work... nor can I
309 // get an external imagemagick binary to do this either... Hacking this
310 // for now (only works if you have exiv2 installed, a program to read
311 // and manipulate exif).
312 if ( $wgExiv2Command ) {
314 . " -M "
315 . wfEscapeShellArg( "set Exif.Image.Orientation " . $orientation['exifCode'] )
316 . " "
317 . wfEscapeShellArg( $filename );
318
319 $retval = 0;
320 $err = wfShellExec( $cmd, $retval );
321 if ( $retval !== 0 ) {
322 print "Error with $cmd: $retval, $err\n";
323 }
324 }
325 }
326
334 private static function rotateImageSpec( &$spec, $matrix ) {
335 $tSpec = [];
336 $dims = self::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] );
337 $correctionX = 0;
338 $correctionY = 0;
339 if ( $dims['x'] < 0 ) {
340 $correctionX = abs( $dims['x'] );
341 }
342 if ( $dims['y'] < 0 ) {
343 $correctionY = abs( $dims['y'] );
344 }
345 $tSpec['width'] = abs( $dims['x'] );
346 $tSpec['height'] = abs( $dims['y'] );
347 $tSpec['fill'] = $spec['fill'];
348 $tSpec['draws'] = [];
349 foreach ( $spec['draws'] as $draw ) {
350 $tDraw = [
351 'fill' => $draw['fill'],
352 'shape' => []
353 ];
354 foreach ( $draw['shape'] as $point ) {
355 $tPoint = self::matrixMultiply2x2( $matrix, $point['x'], $point['y'] );
356 $tPoint['x'] += $correctionX;
357 $tPoint['y'] += $correctionY;
358 $tDraw['shape'][] = $tPoint;
359 }
360 $tSpec['draws'][] = $tDraw;
361 }
362
363 return $tSpec;
364 }
365
373 private static function matrixMultiply2x2( $matrix, $x, $y ) {
374 return [
375 'x' => $x * $matrix[0][0] + $y * $matrix[0][1],
376 'y' => $x * $matrix[1][0] + $y * $matrix[1][1]
377 ];
378 }
379
397 public function writeImageWithCommandLine( $spec, $format, $filename ) {
399 $args = [];
400 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
401 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
402 foreach ( $spec['draws'] as $draw ) {
403 $fill = $draw['fill'];
404 $polygon = self::shapePointsToString( $draw['shape'] );
405 $drawCommand = "fill $fill polygon $polygon";
406 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
407 }
408 $args[] = wfEscapeShellArg( $filename );
409
410 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
411 $retval = null;
413
414 return ( $retval === 0 );
415 }
416
422 public function getRandomColor() {
423 $components = [];
424 for ( $i = 0; $i <= 2; $i++ ) {
425 $components[] = mt_rand( 0, 255 );
426 }
427
428 return 'rgb(' . implode( ', ', $components ) . ')';
429 }
430
438 private function getRandomWordPairs( $number ) {
439 $lines = $this->getRandomLines( $number * 2 );
440 // construct pairs of words
441 $pairs = [];
442 $count = count( $lines );
443 for ( $i = 0; $i < $count; $i += 2 ) {
444 $pairs[] = [ $lines[$i], $lines[$i + 1] ];
445 }
446
447 return $pairs;
448 }
449
460 private function getRandomLines( $number_desired ) {
461 $filepath = $this->dictionaryFile;
462
463 // initialize array of lines
464 $lines = [];
465 for ( $i = 0; $i < $number_desired; $i++ ) {
466 $lines[] = null;
467 }
468
469 /*
470 * This algorithm obtains N random lines from a file in one single pass.
471 * It does this by replacing elements of a fixed-size array of lines,
472 * less and less frequently as it reads the file.
473 */
474 $fh = fopen( $filepath, "r" );
475 if ( !$fh ) {
476 throw new Exception( "couldn't open $filepath" );
477 }
478 $line_number = 0;
479 $max_index = $number_desired - 1;
480 while ( !feof( $fh ) ) {
481 $line = fgets( $fh );
482 if ( $line !== false ) {
483 $line_number++;
484 $line = trim( $line );
485 if ( mt_rand( 0, $line_number ) <= $max_index ) {
486 $lines[mt_rand( 0, $max_index )] = $line;
487 }
488 }
489 }
490 fclose( $fh );
491 if ( $line_number < $number_desired ) {
492 throw new Exception( "not enough lines in $filepath" );
493 }
494
495 return $lines;
496 }
497}
$dir
Definition Autoload.php:8
$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.
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
wfEscapeShellArg()
Version of escapeshellarg() that works better on Windows.
$line
Definition cdb.php:58
$command
Definition cdb.php:64
if( $line===false) $args
Definition cdb.php:63
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...
print
Definition cleanup.php:99
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition hooks.txt:266
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 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:893
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:1971
$points
$lines
Definition router.php:61
$property