test: coverage recording now needs to be explicit
[mediawiki.git] / tests / phpunit / includes / api / RandomImageGenerator.php
blob59756b21e1dd3ced6c0b58512a12cf40d72c1fc8
1 <?php
3 /**
4 * RandomImageGenerator -- does what it says on the tin.
5 * Requires Imagick, the ImageMagick library for PHP, or the command line equivalent (usually 'convert').
7 * Because MediaWiki tests the uniqueness of media upload content, and filenames, it is sometimes useful to generate
8 * files that are guaranteed (or at least very likely) to be unique in both those ways.
9 * This generates a number of filenames with random names and random content (colored triangles)
11 * It is also useful to have fresh content because our tests currently run in a "destructive" mode, and don't create a fresh new wiki for each
12 * test run.
13 * Consequently, if we just had a few static files we kept re-uploading, we'd get lots of warnings about matching content or filenames,
14 * and even if we deleted those files, we'd get warnings about archived files.
16 * This can also be used with a cronjob to generate random files all the time -- I use it to have a constant, never ending supply when I'm
17 * testing interactively.
19 * @file
20 * @author Neil Kandalgaonkar <neilk@wikimedia.org>
23 /**
24 * RandomImageGenerator: does what it says on the tin.
25 * Can fetch a random image, or also write a number of them to disk with random filenames.
27 class RandomImageGenerator {
29 private $dictionaryFile;
30 private $minWidth = 400;
31 private $maxWidth = 800;
32 private $minHeight = 400;
33 private $maxHeight = 800;
34 private $shapesToDraw = 5;
36 /**
37 * Orientations: 0th row, 0th column, Exif orientation code, rotation 2x2 matrix that is opposite of orientation
38 * n.b. we do not handle the 'flipped' orientations, which is why there is no entry for 2, 4, 5, or 7. Those
39 * seem to be rare in real images anyway
40 * (we also would need a non-symmetric shape for the images to test those, like a letter F)
42 private static $orientations = array(
43 array(
44 '0thRow' => 'top',
45 '0thCol' => 'left',
46 'exifCode' => 1,
47 'counterRotation' => array( array( 1, 0 ), array( 0, 1 ) )
49 array(
50 '0thRow' => 'bottom',
51 '0thCol' => 'right',
52 'exifCode' => 3,
53 'counterRotation' => array( array( -1, 0 ), array( 0, -1 ) )
55 array(
56 '0thRow' => 'right',
57 '0thCol' => 'top',
58 'exifCode' => 6,
59 'counterRotation' => array( array( 0, 1 ), array( 1, 0 ) )
61 array(
62 '0thRow' => 'left',
63 '0thCol' => 'bottom',
64 'exifCode' => 8,
65 'counterRotation' => array( array( 0, -1 ), array( -1, 0 ) )
70 public function __construct( $options = array() ) {
71 foreach ( array( 'dictionaryFile', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'shapesToDraw' ) as $property ) {
72 if ( isset( $options[$property] ) ) {
73 $this->$property = $options[$property];
77 // find the dictionary file, to generate random names
78 if ( !isset( $this->dictionaryFile ) ) {
79 foreach (
80 array(
81 '/usr/share/dict/words',
82 '/usr/dict/words',
83 __DIR__ . '/words.txt'
84 ) as $dictionaryFile
85 ) {
86 if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) {
87 $this->dictionaryFile = $dictionaryFile;
88 break;
92 if ( !isset( $this->dictionaryFile ) ) {
93 throw new Exception( "RandomImageGenerator: dictionary file not found or not specified properly" );
97 /**
98 * Writes random images with random filenames to disk in the directory you specify, or current working directory
100 * @param $number Integer: number of filenames to write
101 * @param $format String: optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
102 * @param $dir String: directory, optional (will default to current working directory)
103 * @return Array: filenames we just wrote
105 function writeImages( $number, $format = 'jpg', $dir = null ) {
106 $filenames = $this->getRandomFilenames( $number, $format, $dir );
107 $imageWriteMethod = $this->getImageWriteMethod( $format );
108 foreach ( $filenames as $filename ) {
109 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
112 return $filenames;
117 * Figure out how we write images. This is a factor of both format and the local system
118 * @param $format (a typical extension like 'svg', 'jpg', etc.)
120 function getImageWriteMethod( $format ) {
121 global $wgUseImageMagick, $wgImageMagickConvertCommand;
122 if ( $format === 'svg' ) {
123 return 'writeSvg';
124 } else {
125 // figure out how to write images
126 global $wgExiv2Command;
127 if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
128 return 'writeImageWithApi';
129 } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) {
130 return 'writeImageWithCommandLine';
133 throw new Exception( "RandomImageGenerator: could not find a suitable method to write images in '$format' format" );
137 * Return a number of randomly-generated filenames
138 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
140 * @param $number Integer: of filenames to generate
141 * @param $extension String: optional, defaults to 'jpg'
142 * @param $dir String: optional, defaults to current working directory
143 * @return Array: of filenames
145 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
146 if ( is_null( $dir ) ) {
147 $dir = getcwd();
149 $filenames = array();
150 foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
151 $basename = $pair[0] . '_' . $pair[1];
152 if ( !is_null( $extension ) ) {
153 $basename .= '.' . $extension;
155 $basename = preg_replace( '/\s+/', '', $basename );
156 $filenames[] = "$dir/$basename";
159 return $filenames;
164 * Generate data representing an image of random size (within limits),
165 * consisting of randomly colored and sized upward pointing triangles against a random background color
166 * (This data is used in the writeImage* methods).
167 * @return {Mixed}
169 public function getImageSpec() {
170 $spec = array();
172 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
173 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
174 $spec['fill'] = $this->getRandomColor();
176 $diagonalLength = sqrt( pow( $spec['width'], 2 ) + pow( $spec['height'], 2 ) );
178 $draws = array();
179 for ( $i = 0; $i <= $this->shapesToDraw; $i++ ) {
180 $radius = mt_rand( 0, $diagonalLength / 4 );
181 if ( $radius == 0 ) {
182 continue;
184 $originX = mt_rand( -1 * $radius, $spec['width'] + $radius );
185 $originY = mt_rand( -1 * $radius, $spec['height'] + $radius );
186 $angle = mt_rand( 0, ( 3.141592 / 2 ) * $radius ) / $radius;
187 $legDeltaX = round( $radius * sin( $angle ) );
188 $legDeltaY = round( $radius * cos( $angle ) );
190 $draw = array();
191 $draw['fill'] = $this->getRandomColor();
192 $draw['shape'] = array(
193 array( 'x' => $originX, 'y' => $originY - $radius ),
194 array( 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ),
195 array( 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ),
196 array( 'x' => $originX, 'y' => $originY - $radius )
198 $draws[] = $draw;
201 $spec['draws'] = $draws;
203 return $spec;
207 * Given array( array('x' => 10, 'y' => 20), array( 'x' => 30, y=> 5 ) )
208 * returns "10,20 30,5"
209 * Useful for SVG and imagemagick command line arguments
210 * @param $shape: Array of arrays, each array containing x & y keys mapped to numeric values
211 * @return string
213 static function shapePointsToString( $shape ) {
214 $points = array();
215 foreach ( $shape as $point ) {
216 $points[] = $point['x'] . ',' . $point['y'];
219 return join( " ", $points );
223 * Based on image specification, write a very simple SVG file to disk.
224 * Ignores the background spec because transparency is cool. :)
225 * @param $spec: spec describing background and shapes to draw
226 * @param $format: file format to write (which is obviously always svg here)
227 * @param $filename: filename to write to
229 public function writeSvg( $spec, $format, $filename ) {
230 $svg = new SimpleXmlElement( '<svg/>' );
231 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
232 $svg->addAttribute( 'version', '1.1' );
233 $svg->addAttribute( 'width', $spec['width'] );
234 $svg->addAttribute( 'height', $spec['height'] );
235 $g = $svg->addChild( 'g' );
236 foreach ( $spec['draws'] as $drawSpec ) {
237 $shape = $g->addChild( 'polygon' );
238 $shape->addAttribute( 'fill', $drawSpec['fill'] );
239 $shape->addAttribute( 'points', self::shapePointsToString( $drawSpec['shape'] ) );
242 if ( !$fh = fopen( $filename, 'w' ) ) {
243 throw new Exception( "couldn't open $filename for writing" );
245 fwrite( $fh, $svg->asXML() );
246 if ( !fclose( $fh ) ) {
247 throw new Exception( "couldn't close $filename" );
252 * Based on an image specification, write such an image to disk, using Imagick PHP extension
253 * @param $spec: spec describing background and circles to draw
254 * @param $format: file format to write
255 * @param $filename: filename to write to
257 public function writeImageWithApi( $spec, $format, $filename ) {
258 // this is a hack because I can't get setImageOrientation() to work. See below.
259 global $wgExiv2Command;
261 $image = new Imagick();
263 * If the format is 'jpg', will also add a random orientation -- the image will be drawn rotated with triangle points
264 * facing in some direction (0, 90, 180 or 270 degrees) and a countering rotation should turn the triangle points upward again
266 $orientation = self::$orientations[0]; // default is normal orientation
267 if ( $format == 'jpg' ) {
268 $orientation = self::$orientations[array_rand( self::$orientations )];
269 $spec = self::rotateImageSpec( $spec, $orientation['counterRotation'] );
272 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
274 foreach ( $spec['draws'] as $drawSpec ) {
275 $draw = new ImagickDraw();
276 $draw->setFillColor( $drawSpec['fill'] );
277 $draw->polygon( $drawSpec['shape'] );
278 $image->drawImage( $draw );
281 $image->setImageFormat( $format );
283 // this doesn't work, even though it's documented to do so...
284 // $image->setImageOrientation( $orientation['exifCode'] );
286 $image->writeImage( $filename );
288 // because the above setImageOrientation call doesn't work... nor can I get an external imagemagick binary to do this either...
289 // hacking this for now (only works if you have exiv2 installed, a program to read and manipulate exif)
290 if ( $wgExiv2Command ) {
291 $cmd = wfEscapeShellArg( $wgExiv2Command )
292 . " -M "
293 . wfEscapeShellArg( "set Exif.Image.Orientation " . $orientation['exifCode'] )
294 . " "
295 . wfEscapeShellArg( $filename );
297 $retval = 0;
298 $err = wfShellExec( $cmd, $retval );
299 if ( $retval !== 0 ) {
300 print "Error with $cmd: $retval, $err\n";
306 * Given an image specification, produce rotated version
307 * This is used when simulating a rotated image capture with Exif orientation
308 * @param $spec Object returned by getImageSpec
309 * @param $matrix 2x2 transformation matrix
310 * @return transformed Spec
312 private static function rotateImageSpec( &$spec, $matrix ) {
313 $tSpec = array();
314 $dims = self::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] );
315 $correctionX = 0;
316 $correctionY = 0;
317 if ( $dims['x'] < 0 ) {
318 $correctionX = abs( $dims['x'] );
320 if ( $dims['y'] < 0 ) {
321 $correctionY = abs( $dims['y'] );
323 $tSpec['width'] = abs( $dims['x'] );
324 $tSpec['height'] = abs( $dims['y'] );
325 $tSpec['fill'] = $spec['fill'];
326 $tSpec['draws'] = array();
327 foreach ( $spec['draws'] as $draw ) {
328 $tDraw = array(
329 'fill' => $draw['fill'],
330 'shape' => array()
332 foreach ( $draw['shape'] as $point ) {
333 $tPoint = self::matrixMultiply2x2( $matrix, $point['x'], $point['y'] );
334 $tPoint['x'] += $correctionX;
335 $tPoint['y'] += $correctionY;
336 $tDraw['shape'][] = $tPoint;
338 $tSpec['draws'][] = $tDraw;
341 return $tSpec;
345 * Given a matrix and a pair of images, return new position
346 * @param $matrix: 2x2 rotation matrix
347 * @param $x: x-coordinate number
348 * @param $y: y-coordinate number
349 * @return Array transformed with properties x, y
351 private static function matrixMultiply2x2( $matrix, $x, $y ) {
352 return array(
353 'x' => $x * $matrix[0][0] + $y * $matrix[0][1],
354 'y' => $x * $matrix[1][0] + $y * $matrix[1][1]
360 * Based on an image specification, write such an image to disk, using the command line ImageMagick program ('convert').
362 * Sample command line:
363 * $ convert -size 100x60 xc:rgb(90,87,45) \
364 * -draw 'fill rgb(12,34,56) polygon 41,39 44,57 50,57 41,39' \
365 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
366 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
368 * @param $spec: spec describing background and shapes to draw
369 * @param $format: file format to write (unused by this method but kept so it has the same signature as writeImageWithApi)
370 * @param $filename: filename to write to
372 public function writeImageWithCommandLine( $spec, $format, $filename ) {
373 global $wgImageMagickConvertCommand;
374 $args = array();
375 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
376 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
377 foreach ( $spec['draws'] as $draw ) {
378 $fill = $draw['fill'];
379 $polygon = self::shapePointsToString( $draw['shape'] );
380 $drawCommand = "fill $fill polygon $polygon";
381 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
383 $args[] = wfEscapeShellArg( $filename );
385 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
386 $retval = null;
387 wfShellExec( $command, $retval );
389 return ( $retval === 0 );
393 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
395 * @return {String}
397 public function getRandomColor() {
398 $components = array();
399 for ( $i = 0; $i <= 2; $i++ ) {
400 $components[] = mt_rand( 0, 255 );
403 return 'rgb(' . join( ', ', $components ) . ')';
407 * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
409 * @param $number Integer: number of pairs
410 * @return Array: of two-element arrays
412 private function getRandomWordPairs( $number ) {
413 $lines = $this->getRandomLines( $number * 2 );
414 // construct pairs of words
415 $pairs = array();
416 $count = count( $lines );
417 for ( $i = 0; $i < $count; $i += 2 ) {
418 $pairs[] = array( $lines[$i], $lines[$i + 1] );
421 return $pairs;
425 * Return N random lines from a file
427 * Will throw exception if the file could not be read or if it had fewer lines than requested.
429 * @param $number_desired Integer: number of lines desired
430 * @return Array: of exactly n elements, drawn randomly from lines the file
432 private function getRandomLines( $number_desired ) {
433 $filepath = $this->dictionaryFile;
435 // initialize array of lines
436 $lines = array();
437 for ( $i = 0; $i < $number_desired; $i++ ) {
438 $lines[] = null;
442 * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
443 * a fixed-size array of lines, less and less frequently as it reads the file.
445 $fh = fopen( $filepath, "r" );
446 if ( !$fh ) {
447 throw new Exception( "couldn't open $filepath" );
449 $line_number = 0;
450 $max_index = $number_desired - 1;
451 while ( !feof( $fh ) ) {
452 $line = fgets( $fh );
453 if ( $line !== false ) {
454 $line_number++;
455 $line = trim( $line );
456 if ( mt_rand( 0, $line_number ) <= $max_index ) {
457 $lines[mt_rand( 0, $max_index )] = $line;
461 fclose( $fh );
462 if ( $line_number < $number_desired ) {
463 throw new Exception( "not enough lines in $filepath" );
466 return $lines;