Merge "Remove 'prefsnologin' message, don't use 'watchnologin' where inappropriate"
[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 * @param $format (a typical extension like 'svg', 'jpg', etc.)
117 */
118 function getImageWriteMethod( $format ) {
119 global $wgUseImageMagick, $wgImageMagickConvertCommand;
120 if ( $format === 'svg' ) {
121 return 'writeSvg';
122 } else {
123 // figure out how to write images
124 global $wgExiv2Command;
125 if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
126 return 'writeImageWithApi';
127 } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) {
128 return 'writeImageWithCommandLine';
129 }
130 }
131 throw new Exception( "RandomImageGenerator: could not find a suitable method to write images in '$format' format" );
132 }
133
134 /**
135 * Return a number of randomly-generated filenames
136 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
137 *
138 * @param $number Integer: of filenames to generate
139 * @param $extension String: optional, defaults to 'jpg'
140 * @param $dir String: optional, defaults to current working directory
141 * @return Array: of filenames
142 */
143 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
144 if ( is_null( $dir ) ) {
145 $dir = getcwd();
146 }
147 $filenames = array();
148 foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
149 $basename = $pair[0] . '_' . $pair[1];
150 if ( !is_null( $extension ) ) {
151 $basename .= '.' . $extension;
152 }
153 $basename = preg_replace( '/\s+/', '', $basename );
154 $filenames[] = "$dir/$basename";
155 }
156
157 return $filenames;
158 }
159
160 /**
161 * Generate data representing an image of random size (within limits),
162 * consisting of randomly colored and sized upward pointing triangles against a random background color
163 * (This data is used in the writeImage* methods).
164 * @return {Mixed}
165 */
166 public function getImageSpec() {
167 $spec = array();
168
169 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
170 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
171 $spec['fill'] = $this->getRandomColor();
172
173 $diagonalLength = sqrt( pow( $spec['width'], 2 ) + pow( $spec['height'], 2 ) );
174
175 $draws = array();
176 for ( $i = 0; $i <= $this->shapesToDraw; $i++ ) {
177 $radius = mt_rand( 0, $diagonalLength / 4 );
178 if ( $radius == 0 ) {
179 continue;
180 }
181 $originX = mt_rand( -1 * $radius, $spec['width'] + $radius );
182 $originY = mt_rand( -1 * $radius, $spec['height'] + $radius );
183 $angle = mt_rand( 0, ( 3.141592 / 2 ) * $radius ) / $radius;
184 $legDeltaX = round( $radius * sin( $angle ) );
185 $legDeltaY = round( $radius * cos( $angle ) );
186
187 $draw = array();
188 $draw['fill'] = $this->getRandomColor();
189 $draw['shape'] = array(
190 array( 'x' => $originX, 'y' => $originY - $radius ),
191 array( 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ),
192 array( 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ),
193 array( 'x' => $originX, 'y' => $originY - $radius )
194 );
195 $draws[] = $draw;
196 }
197
198 $spec['draws'] = $draws;
199
200 return $spec;
201 }
202
203 /**
204 * Given array( array('x' => 10, 'y' => 20), array( 'x' => 30, y=> 5 ) )
205 * returns "10,20 30,5"
206 * Useful for SVG and imagemagick command line arguments
207 * @param $shape: Array of arrays, each array containing x & y keys mapped to numeric values
208 * @return string
209 */
210 static function shapePointsToString( $shape ) {
211 $points = array();
212 foreach ( $shape as $point ) {
213 $points[] = $point['x'] . ',' . $point['y'];
214 }
215
216 return join( " ", $points );
217 }
218
219 /**
220 * Based on image specification, write a very simple SVG file to disk.
221 * Ignores the background spec because transparency is cool. :)
222 * @param $spec: spec describing background and shapes to draw
223 * @param $format: file format to write (which is obviously always svg here)
224 * @param $filename: filename to write to
225 */
226 public function writeSvg( $spec, $format, $filename ) {
227 $svg = new SimpleXmlElement( '<svg/>' );
228 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
229 $svg->addAttribute( 'version', '1.1' );
230 $svg->addAttribute( 'width', $spec['width'] );
231 $svg->addAttribute( 'height', $spec['height'] );
232 $g = $svg->addChild( 'g' );
233 foreach ( $spec['draws'] as $drawSpec ) {
234 $shape = $g->addChild( 'polygon' );
235 $shape->addAttribute( 'fill', $drawSpec['fill'] );
236 $shape->addAttribute( 'points', self::shapePointsToString( $drawSpec['shape'] ) );
237 }
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
338 return $tSpec;
339 }
340
341 /**
342 * Given a matrix and a pair of images, return new position
343 * @param $matrix: 2x2 rotation matrix
344 * @param $x: x-coordinate number
345 * @param $y: y-coordinate number
346 * @return Array transformed with properties x, y
347 */
348 private static function matrixMultiply2x2( $matrix, $x, $y ) {
349 return array(
350 'x' => $x * $matrix[0][0] + $y * $matrix[0][1],
351 'y' => $x * $matrix[1][0] + $y * $matrix[1][1]
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
385 return ( $retval === 0 );
386 }
387
388 /**
389 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
390 *
391 * @return {String}
392 */
393 public function getRandomColor() {
394 $components = array();
395 for ( $i = 0; $i <= 2; $i++ ) {
396 $components[] = mt_rand( 0, 255 );
397 }
398
399 return 'rgb(' . join( ', ', $components ) . ')';
400 }
401
402 /**
403 * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
404 *
405 * @param $number Integer: number of pairs
406 * @return Array: of two-element arrays
407 */
408 private function getRandomWordPairs( $number ) {
409 $lines = $this->getRandomLines( $number * 2 );
410 // construct pairs of words
411 $pairs = array();
412 $count = count( $lines );
413 for ( $i = 0; $i < $count; $i += 2 ) {
414 $pairs[] = array( $lines[$i], $lines[$i + 1] );
415 }
416
417 return $pairs;
418 }
419
420 /**
421 * Return N random lines from a file
422 *
423 * Will throw exception if the file could not be read or if it had fewer lines than requested.
424 *
425 * @param $number_desired Integer: number of lines desired
426 * @return Array: of exactly n elements, drawn randomly from lines the file
427 */
428 private function getRandomLines( $number_desired ) {
429 $filepath = $this->dictionaryFile;
430
431 // initialize array of lines
432 $lines = array();
433 for ( $i = 0; $i < $number_desired; $i++ ) {
434 $lines[] = null;
435 }
436
437 /*
438 * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
439 * a fixed-size array of lines, less and less frequently as it reads the file.
440 */
441 $fh = fopen( $filepath, "r" );
442 if ( !$fh ) {
443 throw new Exception( "couldn't open $filepath" );
444 }
445 $line_number = 0;
446 $max_index = $number_desired - 1;
447 while ( !feof( $fh ) ) {
448 $line = fgets( $fh );
449 if ( $line !== false ) {
450 $line_number++;
451 $line = trim( $line );
452 if ( mt_rand( 0, $line_number ) <= $max_index ) {
453 $lines[mt_rand( 0, $max_index )] = $line;
454 }
455 }
456 }
457 fclose( $fh );
458 if ( $line_number < $number_desired ) {
459 throw new Exception( "not enough lines in $filepath" );
460 }
461
462 return $lines;
463 }
464 }