generate random triangles (so we can test EXIF orientation, eventually)
[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 circles)
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 $circlesToDraw = 5;
35 private $imageWriteMethod;
36
37 public function __construct( $options = array() ) {
38 foreach ( array( 'dictionaryFile', 'minWidth', 'minHeight', 'maxHeight', 'circlesToDraw' ) as $property ) {
39 if ( isset( $options[$property] ) ) {
40 $this->$property = $options[$property];
41 }
42 }
43
44 // find the dictionary file, to generate random names
45 if ( !isset( $this->dictionaryFile ) ) {
46 foreach ( array( '/usr/share/dict/words', '/usr/dict/words' ) as $dictionaryFile ) {
47 if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) {
48 $this->dictionaryFile = $dictionaryFile;
49 break;
50 }
51 }
52 }
53 if ( !isset( $this->dictionaryFile ) ) {
54 throw new Exception( "RandomImageGenerator: dictionary file not found or not specified properly" );
55 }
56 }
57
58 /**
59 * Writes random images with random filenames to disk in the directory you specify, or current working directory
60 *
61 * @param $number Integer: number of filenames to write
62 * @param $format String: optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
63 * @param $dir String: directory, optional (will default to current working directory)
64 * @return Array: filenames we just wrote
65 */
66 function writeImages( $number, $format = 'jpg', $dir = null ) {
67 $filenames = $this->getRandomFilenames( $number, $format, $dir );
68 $imageWriteMethod = $this->getImageWriteMethod( $format );
69 foreach( $filenames as $filename ) {
70 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
71 }
72 return $filenames;
73 }
74
75
76 /**
77 * Figure out how we write images. This is a factor of both format and the local system
78 * @param $format (a typical extension like 'svg', 'jpg', etc.)
79 */
80 function getImageWriteMethod( $format ) {
81 global $wgUseImageMagick, $wgImageMagickConvertCommand;
82 if ( $format === 'svg' ) {
83 return 'writeSvg';
84 } else {
85 // figure out how to write images
86 if ( class_exists( 'Imagick' ) ) {
87 return 'writeImageWithApi';
88 } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) {
89 return 'writeImageWithCommandLine';
90 }
91 }
92 throw new Exception( "RandomImageGenerator: could not find a suitable method to write images in '$format' format" );
93 }
94
95 /**
96 * Return a number of randomly-generated filenames
97 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
98 *
99 * @param $number Integer: of filenames to generate
100 * @param $extension String: optional, defaults to 'jpg'
101 * @param $dir String: optional, defaults to current working directory
102 * @return Array: of filenames
103 */
104 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
105 if ( is_null( $dir ) ) {
106 $dir = getcwd();
107 }
108 $filenames = array();
109 foreach( $this->getRandomWordPairs( $number ) as $pair ) {
110 $basename = $pair[0] . '_' . $pair[1];
111 if ( !is_null( $extension ) ) {
112 $basename .= '.' . $extension;
113 }
114 $basename = preg_replace( '/\s+/', '', $basename );
115 $filenames[] = "$dir/$basename";
116 }
117
118 return $filenames;
119
120 }
121
122
123 /**
124 * Generate data representing an image of random size (within limits),
125 * consisting of randomly colored and sized upward pointing triangles against a random background color
126 * (This data is used in the writeImage* methods).
127 * @return {Mixed}
128 */
129 public function getImageSpec() {
130 $spec = array();
131
132 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
133 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
134 $spec['fill'] = $this->getRandomColor();
135
136 $diagonalLength = sqrt( pow( $spec['width'], 2 ) + pow( $spec['height'], 2 ) );
137
138 $draws = array();
139 for ( $i = 0; $i <= $this->circlesToDraw; $i++ ) {
140 $radius = mt_rand( 0, $diagonalLength / 4 );
141 $originX = mt_rand( -1 * $radius, $spec['width'] + $radius );
142 $originY = mt_rand( -1 * $radius, $spec['height'] + $radius );
143 $angle = mt_rand( 0, ( 3.141592/2 ) * $radius ) / $radius;
144 $legDeltaX = round( $radius * sin( $angle ) );
145 $legDeltaY = round( $radius * cos( $angle ) );
146
147 $draw = array();
148 $draw['fill'] = $this->getRandomColor();
149 $draw['shape'] = array(
150 array( 'x' => $originX, 'y' => $originY - $radius ),
151 array( 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ),
152 array( 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ),
153 array( 'x' => $originX, 'y' => $originY - $radius )
154 );
155 $draws[] = $draw;
156
157 }
158
159 $spec['draws'] = $draws;
160
161 return $spec;
162 }
163
164
165 /**
166 * Based on image specification, write a very simple SVG file to disk.
167 * Ignores the background spec because transparency is cool. :)
168 * @param $spec: spec describing background and circles to draw
169 * @param $format: file format to write (which is obviously always svg here)
170 * @param $filename: filename to write to
171 */
172 public function writeSvg( $spec, $format, $filename ) {
173 $svg = new SimpleXmlElement( '<svg/>' );
174 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
175 $svg->addAttribute( 'version', '1.1' );
176 $svg->addAttribute( 'width', $spec['width'] );
177 $svg->addAttribute( 'height', $spec['height'] );
178 $g = $svg->addChild( 'g' );
179 foreach ( $spec['draws'] as $drawSpec ) {
180 $shape = $g->addChild( 'polygon' );
181 $shape->addAttribute( 'fill', $drawSpec['fill'] );
182 $shape->addAttribute( 'points', shapePointsToString( $drawSpec['shape'] ) );
183 };
184 if ( ! $fh = fopen( $filename, 'w' ) ) {
185 throw new Exception( "couldn't open $filename for writing" );
186 }
187 fwrite( $fh, $svg->asXML() );
188 if ( !fclose($fh) ) {
189 throw new Exception( "couldn't close $filename" );
190 }
191 }
192
193 public function shapePointsToString( $shape ) {
194 $points = array();
195 foreach ( $shape as $point ) {
196 $points[] = $point['x'] . ',' . $point['y'];
197 }
198 return join( " ", $points );
199 }
200
201 /**
202 * Based on an image specification, write such an image to disk, using Imagick PHP extension
203 * @param $spec: spec describing background and circles to draw
204 * @param $format: file format to write
205 * @param $filename: filename to write to
206 */
207 public function writeImageWithApi( $spec, $format, $filename ) {
208 $image = new Imagick();
209 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
210
211 foreach ( $spec['draws'] as $drawSpec ) {
212 $draw = new ImagickDraw();
213 $draw->setFillColor( $drawSpec['fill'] );
214 $draw->polygon( $drawSpec['shape'] );
215 $image->drawImage( $draw );
216 }
217
218 $image->setImageFormat( $format );
219 $image->writeImage( $filename );
220 }
221
222
223 /**
224 * Based on an image specification, write such an image to disk, using the command line ImageMagick program ('convert').
225 *
226 * Sample command line:
227 * $ convert -size 100x60 xc:rgb(90,87,45) \
228 * -draw 'fill rgb(12,34,56) polygon 41,39 44,57 50,57 41,39' \
229 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
230 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
231 *
232 * @param $spec: spec describing background and circles to draw
233 * @param $format: file format to write (unused by this method but kept so it has the same signature as writeImageWithApi)
234 * @param $filename: filename to write to
235 */
236 public function writeImageWithCommandLine( $spec, $format, $filename ) {
237 global $wgImageMagickConvertCommand;
238 $args = array();
239 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
240 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
241 foreach( $spec['draws'] as $draw ) {
242 $fill = $draw['fill'];
243 $polygon = shapePointsToString( $draw['shape'] );
244 $drawCommand = "fill $fill polygon $polygon";
245 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
246 }
247 $args[] = wfEscapeShellArg( $filename );
248
249 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
250 $retval = null;
251 wfShellExec( $command, $retval );
252 return ( $retval === 0 );
253 }
254
255 /**
256 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
257 *
258 * @return {String}
259 */
260 public function getRandomColor() {
261 $components = array();
262 for ($i = 0; $i <= 2; $i++ ) {
263 $components[] = mt_rand( 0, 255 );
264 }
265 return 'rgb(' . join(', ', $components) . ')';
266 }
267
268 /**
269 * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
270 *
271 * @param $number Integer: number of pairs
272 * @return Array: of two-element arrays
273 */
274 private function getRandomWordPairs( $number ) {
275 $lines = $this->getRandomLines( $number * 2 );
276 // construct pairs of words
277 $pairs = array();
278 $count = count( $lines );
279 for( $i = 0; $i < $count; $i += 2 ) {
280 $pairs[] = array( $lines[$i], $lines[$i+1] );
281 }
282 return $pairs;
283 }
284
285
286 /**
287 * Return N random lines from a file
288 *
289 * Will throw exception if the file could not be read or if it had fewer lines than requested.
290 *
291 * @param $number_desired Integer: number of lines desired
292 * @return Array: of exactly n elements, drawn randomly from lines the file
293 */
294 private function getRandomLines( $number_desired ) {
295 $filepath = $this->dictionaryFile;
296
297 // initialize array of lines
298 $lines = array();
299 for ( $i = 0; $i < $number_desired; $i++ ) {
300 $lines[] = null;
301 }
302
303 /*
304 * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
305 * a fixed-size array of lines, less and less frequently as it reads the file.
306 */
307 $fh = fopen( $filepath, "r" );
308 if ( !$fh ) {
309 throw new Exception( "couldn't open $filepath" );
310 }
311 $line_number = 0;
312 $max_index = $number_desired - 1;
313 while( !feof( $fh ) ) {
314 $line = fgets( $fh );
315 if ( $line !== false ) {
316 $line_number++;
317 $line = trim( $line );
318 if ( mt_rand( 0, $line_number ) <= $max_index ) {
319 $lines[ mt_rand( 0, $max_index ) ] = $line;
320 }
321 }
322 }
323 fclose( $fh );
324 if ( $line_number < $number_desired ) {
325 throw new Exception( "not enough lines in $filepath" );
326 }
327
328 return $lines;
329 }
330
331 }