Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / tests / phpunit / includes / api / RandomImageGenerator.php
blob6374cfac81a565dcbbc39aaea1d00c401fcbbaf4
1 <?php
2 /**
3 * RandomImageGenerator -- does what it says on the tin.
4 * Requires Imagick, the ImageMagick library for PHP, or the command line
5 * equivalent (usually 'convert').
7 * Because MediaWiki tests the uniqueness of media upload content, and
8 * filenames, it is sometimes useful to generate files that are guaranteed (or
9 * at least very likely) to be unique in both those ways. This generates a
10 * number of filenames with random names and random content (colored triangles).
12 * It is also useful to have fresh content because our tests currently run in a
13 * "destructive" mode, and don't create a fresh new wiki for each test run.
14 * Consequently, if we just had a few static files we kept re-uploading, we'd
15 * get lots of warnings about matching content or filenames, and even if we
16 * deleted those files, we'd get warnings about archived files.
18 * This can also be used with a cronjob to generate random files all the time.
19 * I use it to have a constant, never ending supply when I'm testing
20 * interactively.
22 * @file
23 * @author Neil Kandalgaonkar <neilk@wikimedia.org>
26 /**
27 * RandomImageGenerator: does what it says on the tin.
28 * Can fetch a random image, or also write a number of them to disk with random filenames.
30 class RandomImageGenerator {
31 private $dictionaryFile;
32 private $minWidth = 400;
33 private $maxWidth = 800;
34 private $minHeight = 400;
35 private $maxHeight = 800;
36 private $shapesToDraw = 5;
38 /**
39 * Orientations: 0th row, 0th column, Exif orientation code, rotation 2x2
40 * matrix that is opposite of orientation. N.b. we do not handle the
41 * 'flipped' orientations, which is why there is no entry for 2, 4, 5, or 7.
42 * Those seem to be rare in real images anyway (we also would need a
43 * non-symmetric shape for the images to test those, like a letter F).
45 private static $orientations = array(
46 array(
47 '0thRow' => 'top',
48 '0thCol' => 'left',
49 'exifCode' => 1,
50 'counterRotation' => array( array( 1, 0 ), array( 0, 1 ) )
52 array(
53 '0thRow' => 'bottom',
54 '0thCol' => 'right',
55 'exifCode' => 3,
56 'counterRotation' => array( array( -1, 0 ), array( 0, -1 ) )
58 array(
59 '0thRow' => 'right',
60 '0thCol' => 'top',
61 'exifCode' => 6,
62 'counterRotation' => array( array( 0, 1 ), array( 1, 0 ) )
64 array(
65 '0thRow' => 'left',
66 '0thCol' => 'bottom',
67 'exifCode' => 8,
68 'counterRotation' => array( array( 0, -1 ), array( -1, 0 ) )
72 public function __construct( $options = array() ) {
73 foreach ( array( 'dictionaryFile', 'minWidth', 'minHeight',
74 'maxWidth', 'maxHeight', 'shapesToDraw' ) as $property
75 ) {
76 if ( isset( $options[$property] ) ) {
77 $this->$property = $options[$property];
81 // find the dictionary file, to generate random names
82 if ( !isset( $this->dictionaryFile ) ) {
83 foreach (
84 array(
85 '/usr/share/dict/words',
86 '/usr/dict/words',
87 __DIR__ . '/words.txt'
88 ) as $dictionaryFile
89 ) {
90 if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) {
91 $this->dictionaryFile = $dictionaryFile;
92 break;
96 if ( !isset( $this->dictionaryFile ) ) {
97 throw new Exception( "RandomImageGenerator: dictionary file not "
98 . "found or not specified properly" );
103 * Writes random images with random filenames to disk in the directory you
104 * specify, or current working directory.
106 * @param int $number Number of filenames to write
107 * @param string $format Optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
108 * @param string $dir Directory, optional (will default to current working directory)
109 * @return array Filenames we just wrote
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 );
118 return $filenames;
122 * Figure out how we write images. This is a factor of both format and the local system
124 * @param string $format (a typical extension like 'svg', 'jpg', etc.)
126 * @throws Exception
127 * @return string
129 function getImageWriteMethod( $format ) {
130 global $wgUseImageMagick, $wgImageMagickConvertCommand;
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
139 && $wgImageMagickConvertCommand
140 && is_executable( $wgImageMagickConvertCommand )
142 return 'writeImageWithCommandLine';
145 throw new Exception( "RandomImageGenerator: could not find a suitable "
146 . "method to write images in '$format' format" );
150 * Return a number of randomly-generated filenames
151 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
153 * @param int $number Number of filenames to generate
154 * @param string $extension Optional, defaults to 'jpg'
155 * @param string $dir Optional, defaults to current working directory
156 * @return array Array of filenames
158 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
159 if ( is_null( $dir ) ) {
160 $dir = getcwd();
162 $filenames = array();
163 foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
164 $basename = $pair[0] . '_' . $pair[1];
165 if ( !is_null( $extension ) ) {
166 $basename .= '.' . $extension;
168 $basename = preg_replace( '/\s+/', '', $basename );
169 $filenames[] = "$dir/$basename";
172 return $filenames;
176 * Generate data representing an image of random size (within limits),
177 * consisting of randomly colored and sized upward pointing triangles
178 * against a random background color. (This data is used in the
179 * writeImage* methods).
181 * @return mixed
183 public function getImageSpec() {
184 $spec = array();
186 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
187 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
188 $spec['fill'] = $this->getRandomColor();
190 $diagonalLength = sqrt( pow( $spec['width'], 2 ) + pow( $spec['height'], 2 ) );
192 $draws = array();
193 for ( $i = 0; $i <= $this->shapesToDraw; $i++ ) {
194 $radius = mt_rand( 0, $diagonalLength / 4 );
195 if ( $radius == 0 ) {
196 continue;
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 ) );
204 $draw = array();
205 $draw['fill'] = $this->getRandomColor();
206 $draw['shape'] = array(
207 array( 'x' => $originX, 'y' => $originY - $radius ),
208 array( 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ),
209 array( 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ),
210 array( 'x' => $originX, 'y' => $originY - $radius )
212 $draws[] = $draw;
215 $spec['draws'] = $draws;
217 return $spec;
221 * Given array( array('x' => 10, 'y' => 20), array( 'x' => 30, y=> 5 ) )
222 * returns "10,20 30,5"
223 * Useful for SVG and imagemagick command line arguments
224 * @param array $shape Array of arrays, each array containing x & y keys mapped to numeric values
225 * @return string
227 static function shapePointsToString( $shape ) {
228 $points = array();
229 foreach ( $shape as $point ) {
230 $points[] = $point['x'] . ',' . $point['y'];
233 return join( " ", $points );
237 * Based on image specification, write a very simple SVG file to disk.
238 * Ignores the background spec because transparency is cool. :)
240 * @param array $spec Spec describing background and shapes to draw
241 * @param string $format File format to write (which is obviously always svg here)
242 * @param string $filename Filename to write to
244 * @throws Exception
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'] ) );
259 if ( !$fh = fopen( $filename, 'w' ) ) {
260 throw new Exception( "couldn't open $filename for writing" );
262 fwrite( $fh, $svg->asXML() );
263 if ( !fclose( $fh ) ) {
264 throw new Exception( "couldn't close $filename" );
269 * Based on an image specification, write such an image to disk, using Imagick PHP extension
270 * @param array $spec Spec describing background and circles to draw
271 * @param string $format File format to write
272 * @param string $filename Filename to write to
274 public function writeImageWithApi( $spec, $format, $filename ) {
275 // this is a hack because I can't get setImageOrientation() to work. See below.
276 global $wgExiv2Command;
278 $image = new Imagick();
280 * If the format is 'jpg', will also add a random orientation -- the
281 * image will be drawn rotated with triangle points facing in some
282 * direction (0, 90, 180 or 270 degrees) and a countering rotation
283 * should turn the triangle points upward again.
285 $orientation = self::$orientations[0]; // default is normal orientation
286 if ( $format == 'jpg' ) {
287 $orientation = self::$orientations[array_rand( self::$orientations )];
288 $spec = self::rotateImageSpec( $spec, $orientation['counterRotation'] );
291 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
293 foreach ( $spec['draws'] as $drawSpec ) {
294 $draw = new ImagickDraw();
295 $draw->setFillColor( $drawSpec['fill'] );
296 $draw->polygon( $drawSpec['shape'] );
297 $image->drawImage( $draw );
300 $image->setImageFormat( $format );
302 // this doesn't work, even though it's documented to do so...
303 // $image->setImageOrientation( $orientation['exifCode'] );
305 $image->writeImage( $filename );
307 // because the above setImageOrientation call doesn't work... nor can I
308 // get an external imagemagick binary to do this either... Hacking this
309 // for now (only works if you have exiv2 installed, a program to read
310 // and manipulate exif).
311 if ( $wgExiv2Command ) {
312 $cmd = wfEscapeShellArg( $wgExiv2Command )
313 . " -M "
314 . wfEscapeShellArg( "set Exif.Image.Orientation " . $orientation['exifCode'] )
315 . " "
316 . wfEscapeShellArg( $filename );
318 $retval = 0;
319 $err = wfShellExec( $cmd, $retval );
320 if ( $retval !== 0 ) {
321 print "Error with $cmd: $retval, $err\n";
327 * Given an image specification, produce rotated version
328 * This is used when simulating a rotated image capture with Exif orientation
329 * @param array $spec Returned by getImageSpec
330 * @param array $matrix 2x2 transformation matrix
331 * @return array Transformed Spec
333 private static function rotateImageSpec( &$spec, $matrix ) {
334 $tSpec = array();
335 $dims = self::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] );
336 $correctionX = 0;
337 $correctionY = 0;
338 if ( $dims['x'] < 0 ) {
339 $correctionX = abs( $dims['x'] );
341 if ( $dims['y'] < 0 ) {
342 $correctionY = abs( $dims['y'] );
344 $tSpec['width'] = abs( $dims['x'] );
345 $tSpec['height'] = abs( $dims['y'] );
346 $tSpec['fill'] = $spec['fill'];
347 $tSpec['draws'] = array();
348 foreach ( $spec['draws'] as $draw ) {
349 $tDraw = array(
350 'fill' => $draw['fill'],
351 'shape' => array()
353 foreach ( $draw['shape'] as $point ) {
354 $tPoint = self::matrixMultiply2x2( $matrix, $point['x'], $point['y'] );
355 $tPoint['x'] += $correctionX;
356 $tPoint['y'] += $correctionY;
357 $tDraw['shape'][] = $tPoint;
359 $tSpec['draws'][] = $tDraw;
362 return $tSpec;
366 * Given a matrix and a pair of images, return new position
367 * @param array $matrix 2x2 rotation matrix
368 * @param int $x The x-coordinate number
369 * @param int $y The y-coordinate number
370 * @return array Transformed with properties x, y
372 private static function matrixMultiply2x2( $matrix, $x, $y ) {
373 return array(
374 'x' => $x * $matrix[0][0] + $y * $matrix[0][1],
375 'y' => $x * $matrix[1][0] + $y * $matrix[1][1]
380 * Based on an image specification, write such an image to disk, using the
381 * command line ImageMagick program ('convert').
383 * Sample command line:
384 * $ convert -size 100x60 xc:rgb(90,87,45) \
385 * -draw 'fill rgb(12,34,56) polygon 41,39 44,57 50,57 41,39' \
386 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
387 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
389 * @param array $spec Spec describing background and shapes to draw
390 * @param string $format File format to write (unused by this method but
391 * kept so it has the same signature as writeImageWithApi).
392 * @param string $filename Filename to write to
394 * @return bool
396 public function writeImageWithCommandLine( $spec, $format, $filename ) {
397 global $wgImageMagickConvertCommand;
398 $args = array();
399 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
400 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
401 foreach ( $spec['draws'] as $draw ) {
402 $fill = $draw['fill'];
403 $polygon = self::shapePointsToString( $draw['shape'] );
404 $drawCommand = "fill $fill polygon $polygon";
405 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
407 $args[] = wfEscapeShellArg( $filename );
409 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
410 $retval = null;
411 wfShellExec( $command, $retval );
413 return ( $retval === 0 );
417 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
419 * @return string
421 public function getRandomColor() {
422 $components = array();
423 for ( $i = 0; $i <= 2; $i++ ) {
424 $components[] = mt_rand( 0, 255 );
427 return 'rgb(' . join( ', ', $components ) . ')';
431 * Get an array of random pairs of random words, like
432 * array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
434 * @param int $number Number of pairs
435 * @return array Two-element arrays
437 private function getRandomWordPairs( $number ) {
438 $lines = $this->getRandomLines( $number * 2 );
439 // construct pairs of words
440 $pairs = array();
441 $count = count( $lines );
442 for ( $i = 0; $i < $count; $i += 2 ) {
443 $pairs[] = array( $lines[$i], $lines[$i + 1] );
446 return $pairs;
450 * Return N random lines from a file
452 * Will throw exception if the file could not be read or if it had fewer lines than requested.
454 * @param int $number_desired Number of lines desired
456 * @throws Exception
457 * @return array Array of exactly n elements, drawn randomly from lines the file
459 private function getRandomLines( $number_desired ) {
460 $filepath = $this->dictionaryFile;
462 // initialize array of lines
463 $lines = array();
464 for ( $i = 0; $i < $number_desired; $i++ ) {
465 $lines[] = null;
469 * This algorithm obtains N random lines from a file in one single pass.
470 * It does this by replacing elements of a fixed-size array of lines,
471 * less and less frequently as it reads the file.
473 $fh = fopen( $filepath, "r" );
474 if ( !$fh ) {
475 throw new Exception( "couldn't open $filepath" );
477 $line_number = 0;
478 $max_index = $number_desired - 1;
479 while ( !feof( $fh ) ) {
480 $line = fgets( $fh );
481 if ( $line !== false ) {
482 $line_number++;
483 $line = trim( $line );
484 if ( mt_rand( 0, $line_number ) <= $max_index ) {
485 $lines[mt_rand( 0, $max_index )] = $line;
489 fclose( $fh );
490 if ( $line_number < $number_desired ) {
491 throw new Exception( "not enough lines in $filepath" );
494 return $lines;