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