Use __DIR__ instead of dirname( __FILE__ )
[lhc/web/wiklou.git] / tests / phpunit / includes / api / RandomImageGenerator.php
1 <?php
2
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').
6 *
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)
10 *
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.
15 *
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.
18 *
19 * @file
20 * @author Neil Kandalgaonkar <neilk@wikimedia.org>
21 */
22
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.
26 */
27 class RandomImageGenerator {
28
29 private $dictionaryFile;
30 private $minWidth = 400 ;
31 private $maxWidth = 800 ;
32 private $minHeight = 400 ;
33 private $maxHeight = 800 ;
34 private $shapesToDraw = 5 ;
35
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)
41 */
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 ) )
48 ),
49 array(
50 '0thRow' => 'bottom',
51 '0thCol' => 'right',
52 'exifCode' => 3,
53 'counterRotation' => array( array( -1, 0 ), array( 0, -1 ) )
54 ),
55 array(
56 '0thRow' => 'right',
57 '0thCol' => 'top',
58 'exifCode' => 6,
59 'counterRotation' => array( array( 0, 1 ), array( 1, 0 ) )
60 ),
61 array(
62 '0thRow' => 'left',
63 '0thCol' => 'bottom',
64 'exifCode' => 8,
65 'counterRotation' => array( array( 0, -1 ), array( -1, 0 ) )
66 )
67 );
68
69
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];
74 }
75 }
76
77 // find the dictionary file, to generate random names
78 if ( !isset( $this->dictionaryFile ) ) {
79 foreach ( array(
80 '/usr/share/dict/words',
81 '/usr/dict/words',
82 __DIR__ . '/words.txt' )
83 as $dictionaryFile ) {
84 if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) {
85 $this->dictionaryFile = $dictionaryFile;
86 break;
87 }
88 }
89 }
90 if ( !isset( $this->dictionaryFile ) ) {
91 throw new Exception( "RandomImageGenerator: dictionary file not found or not specified properly" );
92 }
93 }
94
95 /**
96 * Writes random images with random filenames to disk in the directory you specify, or current working directory
97 *
98 * @param $number Integer: number of filenames to write
99 * @param $format String: optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
100 * @param $dir String: directory, optional (will default to current working directory)
101 * @return Array: filenames we just wrote
102 */
103 function writeImages( $number, $format = 'jpg', $dir = null ) {
104 $filenames = $this->getRandomFilenames( $number, $format, $dir );
105 $imageWriteMethod = $this->getImageWriteMethod( $format );
106 foreach( $filenames as $filename ) {
107 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
108 }
109 return $filenames;
110 }
111
112
113 /**
114 * Figure out how we write images. This is a factor of both format and the local system
115 * @param $format (a typical extension like 'svg', 'jpg', etc.)
116 */
117 function getImageWriteMethod( $format ) {
118 global $wgUseImageMagick, $wgImageMagickConvertCommand;
119 if ( $format === 'svg' ) {
120 return 'writeSvg';
121 } else {
122 // figure out how to write images
123 global $wgExiv2Command;
124 if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
125 return 'writeImageWithApi';
126 } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) {
127 return 'writeImageWithCommandLine';
128 }
129 }
130 throw new Exception( "RandomImageGenerator: could not find a suitable method to write images in '$format' format" );
131 }
132
133 /**
134 * Return a number of randomly-generated filenames
135 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
136 *
137 * @param $number Integer: of filenames to generate
138 * @param $extension String: optional, defaults to 'jpg'
139 * @param $dir String: optional, defaults to current working directory
140 * @return Array: of filenames
141 */
142 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
143 if ( is_null( $dir ) ) {
144 $dir = getcwd();
145 }
146 $filenames = array();
147 foreach( $this->getRandomWordPairs( $number ) as $pair ) {
148 $basename = $pair[0] . '_' . $pair[1];
149 if ( !is_null( $extension ) ) {
150 $basename .= '.' . $extension;
151 }
152 $basename = preg_replace( '/\s+/', '', $basename );
153 $filenames[] = "$dir/$basename";
154 }
155
156 return $filenames;
157
158 }
159
160
161 /**
162 * Generate data representing an image of random size (within limits),
163 * consisting of randomly colored and sized upward pointing triangles against a random background color
164 * (This data is used in the writeImage* methods).
165 * @return {Mixed}
166 */
167 public function getImageSpec() {
168 $spec = array();
169
170 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
171 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
172 $spec['fill'] = $this->getRandomColor();
173
174 $diagonalLength = sqrt( pow( $spec['width'], 2 ) + pow( $spec['height'], 2 ) );
175
176 $draws = array();
177 for ( $i = 0; $i <= $this->shapesToDraw; $i++ ) {
178 $radius = mt_rand( 0, $diagonalLength / 4 );
179 if ( $radius == 0 ) {
180 continue;
181 }
182 $originX = mt_rand( -1 * $radius, $spec['width'] + $radius );
183 $originY = mt_rand( -1 * $radius, $spec['height'] + $radius );
184 $angle = mt_rand( 0, ( 3.141592/2 ) * $radius ) / $radius;
185 $legDeltaX = round( $radius * sin( $angle ) );
186 $legDeltaY = round( $radius * cos( $angle ) );
187
188 $draw = array();
189 $draw['fill'] = $this->getRandomColor();
190 $draw['shape'] = array(
191 array( 'x' => $originX, 'y' => $originY - $radius ),
192 array( 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ),
193 array( 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ),
194 array( 'x' => $originX, 'y' => $originY - $radius )
195 );
196 $draws[] = $draw;
197
198 }
199
200 $spec['draws'] = $draws;
201
202 return $spec;
203 }
204
205 /**
206 * Given array( array('x' => 10, 'y' => 20), array( 'x' => 30, y=> 5 ) )
207 * returns "10,20 30,5"
208 * Useful for SVG and imagemagick command line arguments
209 * @param $shape: Array of arrays, each array containing x & y keys mapped to numeric values
210 * @return string
211 */
212 static function shapePointsToString( $shape ) {
213 $points = array();
214 foreach ( $shape as $point ) {
215 $points[] = $point['x'] . ',' . $point['y'];
216 }
217 return join( " ", $points );
218 }
219
220 /**
221 * Based on image specification, write a very simple SVG file to disk.
222 * Ignores the background spec because transparency is cool. :)
223 * @param $spec: spec describing background and shapes to draw
224 * @param $format: file format to write (which is obviously always svg here)
225 * @param $filename: filename to write to
226 */
227 public function writeSvg( $spec, $format, $filename ) {
228 $svg = new SimpleXmlElement( '<svg/>' );
229 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
230 $svg->addAttribute( 'version', '1.1' );
231 $svg->addAttribute( 'width', $spec['width'] );
232 $svg->addAttribute( 'height', $spec['height'] );
233 $g = $svg->addChild( 'g' );
234 foreach ( $spec['draws'] as $drawSpec ) {
235 $shape = $g->addChild( 'polygon' );
236 $shape->addAttribute( 'fill', $drawSpec['fill'] );
237 $shape->addAttribute( 'points', self::shapePointsToString( $drawSpec['shape'] ) );
238 };
239 if ( ! $fh = fopen( $filename, 'w' ) ) {
240 throw new Exception( "couldn't open $filename for writing" );
241 }
242 fwrite( $fh, $svg->asXML() );
243 if ( !fclose($fh) ) {
244 throw new Exception( "couldn't close $filename" );
245 }
246 }
247
248 /**
249 * Based on an image specification, write such an image to disk, using Imagick PHP extension
250 * @param $spec: spec describing background and circles to draw
251 * @param $format: file format to write
252 * @param $filename: filename to write to
253 */
254 public function writeImageWithApi( $spec, $format, $filename ) {
255 // this is a hack because I can't get setImageOrientation() to work. See below.
256 global $wgExiv2Command;
257
258 $image = new Imagick();
259 /**
260 * If the format is 'jpg', will also add a random orientation -- the image will be drawn rotated with triangle points
261 * facing in some direction (0, 90, 180 or 270 degrees) and a countering rotation should turn the triangle points upward again
262 */
263 $orientation = self::$orientations[0]; // default is normal orientation
264 if ( $format == 'jpg' ) {
265 $orientation = self::$orientations[ array_rand( self::$orientations ) ];
266 $spec = self::rotateImageSpec( $spec, $orientation['counterRotation'] );
267 }
268
269 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
270
271 foreach ( $spec['draws'] as $drawSpec ) {
272 $draw = new ImagickDraw();
273 $draw->setFillColor( $drawSpec['fill'] );
274 $draw->polygon( $drawSpec['shape'] );
275 $image->drawImage( $draw );
276 }
277
278 $image->setImageFormat( $format );
279
280 // this doesn't work, even though it's documented to do so...
281 // $image->setImageOrientation( $orientation['exifCode'] );
282
283 $image->writeImage( $filename );
284
285 // because the above setImageOrientation call doesn't work... nor can I get an external imagemagick binary to do this either...
286 // hacking this for now (only works if you have exiv2 installed, a program to read and manipulate exif)
287 if ( $wgExiv2Command ) {
288 $cmd = wfEscapeShellArg( $wgExiv2Command )
289 . " -M "
290 . wfEscapeShellArg( "set Exif.Image.Orientation " . $orientation['exifCode'] )
291 . " "
292 . wfEscapeShellArg( $filename );
293
294 $retval = 0;
295 $err = wfShellExec( $cmd, $retval );
296 if ( $retval !== 0 ) {
297 print "Error with $cmd: $retval, $err\n";
298 }
299 }
300 }
301
302 /**
303 * Given an image specification, produce rotated version
304 * This is used when simulating a rotated image capture with EXIF orientation
305 * @param $spec Object returned by getImageSpec
306 * @param $matrix 2x2 transformation matrix
307 * @return transformed Spec
308 */
309 private static function rotateImageSpec( &$spec, $matrix ) {
310 $tSpec = array();
311 $dims = self::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] );
312 $correctionX = 0;
313 $correctionY = 0;
314 if ( $dims['x'] < 0 ) {
315 $correctionX = abs( $dims['x'] );
316 }
317 if ( $dims['y'] < 0 ) {
318 $correctionY = abs( $dims['y'] );
319 }
320 $tSpec['width'] = abs( $dims['x'] );
321 $tSpec['height'] = abs( $dims['y'] );
322 $tSpec['fill'] = $spec['fill'];
323 $tSpec['draws'] = array();
324 foreach( $spec['draws'] as $draw ) {
325 $tDraw = array(
326 'fill' => $draw['fill'],
327 'shape' => array()
328 );
329 foreach( $draw['shape'] as $point ) {
330 $tPoint = self::matrixMultiply2x2( $matrix, $point['x'], $point['y'] );
331 $tPoint['x'] += $correctionX;
332 $tPoint['y'] += $correctionY;
333 $tDraw['shape'][] = $tPoint;
334 }
335 $tSpec['draws'][] = $tDraw;
336 }
337 return $tSpec;
338 }
339
340 /**
341 * Given a matrix and a pair of images, return new position
342 * @param $matrix: 2x2 rotation matrix
343 * @param $x: x-coordinate number
344 * @param $y: y-coordinate number
345 * @return Array transformed with properties x, y
346 */
347 private static function matrixMultiply2x2( $matrix, $x, $y ) {
348 return array(
349 'x' => $x * $matrix[0][0] + $y * $matrix[0][1],
350 'y' => $x * $matrix[1][0] + $y * $matrix[1][1]
351 );
352 }
353
354
355 /**
356 * Based on an image specification, write such an image to disk, using the command line ImageMagick program ('convert').
357 *
358 * Sample command line:
359 * $ convert -size 100x60 xc:rgb(90,87,45) \
360 * -draw 'fill rgb(12,34,56) polygon 41,39 44,57 50,57 41,39' \
361 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
362 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
363 *
364 * @param $spec: spec describing background and shapes to draw
365 * @param $format: file format to write (unused by this method but kept so it has the same signature as writeImageWithApi)
366 * @param $filename: filename to write to
367 */
368 public function writeImageWithCommandLine( $spec, $format, $filename ) {
369 global $wgImageMagickConvertCommand;
370 $args = array();
371 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
372 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
373 foreach( $spec['draws'] as $draw ) {
374 $fill = $draw['fill'];
375 $polygon = self::shapePointsToString( $draw['shape'] );
376 $drawCommand = "fill $fill polygon $polygon";
377 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
378 }
379 $args[] = wfEscapeShellArg( $filename );
380
381 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
382 $retval = null;
383 wfShellExec( $command, $retval );
384 return ( $retval === 0 );
385 }
386
387 /**
388 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
389 *
390 * @return {String}
391 */
392 public function getRandomColor() {
393 $components = array();
394 for ($i = 0; $i <= 2; $i++ ) {
395 $components[] = mt_rand( 0, 255 );
396 }
397 return 'rgb(' . join(', ', $components) . ')';
398 }
399
400 /**
401 * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
402 *
403 * @param $number Integer: number of pairs
404 * @return Array: of two-element arrays
405 */
406 private function getRandomWordPairs( $number ) {
407 $lines = $this->getRandomLines( $number * 2 );
408 // construct pairs of words
409 $pairs = array();
410 $count = count( $lines );
411 for( $i = 0; $i < $count; $i += 2 ) {
412 $pairs[] = array( $lines[$i], $lines[$i+1] );
413 }
414 return $pairs;
415 }
416
417
418 /**
419 * Return N random lines from a file
420 *
421 * Will throw exception if the file could not be read or if it had fewer lines than requested.
422 *
423 * @param $number_desired Integer: number of lines desired
424 * @return Array: of exactly n elements, drawn randomly from lines the file
425 */
426 private function getRandomLines( $number_desired ) {
427 $filepath = $this->dictionaryFile;
428
429 // initialize array of lines
430 $lines = array();
431 for ( $i = 0; $i < $number_desired; $i++ ) {
432 $lines[] = null;
433 }
434
435 /*
436 * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
437 * a fixed-size array of lines, less and less frequently as it reads the file.
438 */
439 $fh = fopen( $filepath, "r" );
440 if ( !$fh ) {
441 throw new Exception( "couldn't open $filepath" );
442 }
443 $line_number = 0;
444 $max_index = $number_desired - 1;
445 while( !feof( $fh ) ) {
446 $line = fgets( $fh );
447 if ( $line !== false ) {
448 $line_number++;
449 $line = trim( $line );
450 if ( mt_rand( 0, $line_number ) <= $max_index ) {
451 $lines[ mt_rand( 0, $max_index ) ] = $line;
452 }
453 }
454 }
455 fclose( $fh );
456 if ( $line_number < $number_desired ) {
457 throw new Exception( "not enough lines in $filepath" );
458 }
459
460 return $lines;
461 }
462
463 }