also generate random SVG files
[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 global $wgUseImageMagick, $wgImageMagickConvertCommand;
39 foreach ( array( 'dictionaryFile', 'minWidth', 'minHeight', 'maxHeight', 'circlesToDraw' ) as $property ) {
40 if ( isset( $options[$property] ) ) {
41 $this->$property = $options[$property];
42 }
43 }
44
45 // find the dictionary file, to generate random names
46 if ( !isset( $this->dictionaryFile ) ) {
47 foreach ( array( '/usr/share/dict/words', '/usr/dict/words' ) as $dictionaryFile ) {
48 if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) {
49 $this->dictionaryFile = $dictionaryFile;
50 break;
51 }
52 }
53 }
54 if ( !isset( $this->dictionaryFile ) ) {
55 throw new Exception( "RandomImageGenerator: dictionary file not found or not specified properly" );
56 }
57 }
58
59 /**
60 * Writes random images with random filenames to disk in the directory you specify, or current working directory
61 *
62 * @param $number Integer: number of filenames to write
63 * @param $format String: optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
64 * @param $dir String: directory, optional (will default to current working directory)
65 * @return Array: filenames we just wrote
66 */
67 function writeImages( $number, $format = 'jpg', $dir = null ) {
68 $filenames = $this->getRandomFilenames( $number, $format, $dir );
69 $imageWriteMethod = $this->getImageWriteMethod( $format );
70 foreach( $filenames as $filename ) {
71 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
72 }
73 return $filenames;
74 }
75
76
77 /**
78 * Figure out how we write images. This is a factor of both format and the local system
79 * @param $format (a typical extension like 'svg', 'jpg', etc.)
80 */
81 function getImageWriteMethod( $format ) {
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 circles 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 $perimeterX = $originX + $radius;
144 $perimeterY = $originY + $radius;
145
146 $draw = array();
147 $draw['fill'] = $this->getRandomColor();
148 $draw['circle'] = array(
149 'originX' => $originX,
150 'originY' => $originY,
151 'radius' => $radius,
152 'perimeterX' => $perimeterX,
153 'perimeterY' => $perimeterY
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 $circle = $g->addChild( 'circle' );
181 $circle->addAttribute( 'fill', $drawSpec['fill'] );
182 $circleSpec = $drawSpec['circle'];
183 $circle->addAttribute( 'cx', $circleSpec['originX'] );
184 $circle->addAttribute( 'cy', $circleSpec['originY'] );
185 $circle->addAttribute( 'r', $circleSpec['radius'] );
186 };
187 if ( ! $fh = fopen( $filename, 'w' ) ) {
188 throw new Exception( "couldn't open $filename for writing" );
189 }
190 fwrite( $fh, $svg->asXML() );
191 if ( !fclose($fh) ) {
192 throw new Exception( "couldn't close $filename" );
193 }
194 }
195
196 /**
197 * Based on an image specification, write such an image to disk, using Imagick PHP extension
198 * @param $spec: spec describing background and circles to draw
199 * @param $format: file format to write
200 * @param $filename: filename to write to
201 */
202 public function writeImageWithApi( $spec, $format, $filename ) {
203 $image = new Imagick();
204 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
205
206 foreach ( $spec['draws'] as $drawSpec ) {
207 $draw = new ImagickDraw();
208 $draw->setFillColor( $drawSpec['fill'] );
209 $circle = $drawSpec['circle'];
210 $draw->circle( $circle['originX'], $circle['originY'], $circle['perimeterX'], $circle['perimeterY'] );
211 $image->drawImage( $draw );
212 }
213
214 $image->setImageFormat( $format );
215 $image->writeImage( $filename );
216 }
217
218
219 /**
220 * Based on an image specification, write such an image to disk, using the command line ImageMagick program ('convert').
221 *
222 * Sample command line:
223 * $ convert -size 100x60 xc:rgb(90,87,45) \
224 * -draw 'fill rgb(12,34,56) circle 41,39 44,57' \
225 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
226 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
227 *
228 * @param $spec: spec describing background and circles to draw
229 * @param $format: file format to write (unused by this method but kept so it has the same signature as writeImageWithApi)
230 * @param $filename: filename to write to
231 */
232 public function writeImageWithCommandLine( $spec, $format, $filename ) {
233 global $wgImageMagickConvertCommand;
234 $args = array();
235 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
236 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
237 foreach( $spec['draws'] as $draw ) {
238 $fill = $draw['fill'];
239 $originX = $draw['circle']['originX'];
240 $originY = $draw['circle']['originY'];
241 $perimeterX = $draw['circle']['perimeterX'];
242 $perimeterY = $draw['circle']['perimeterY'];
243 $drawCommand = "fill $fill circle $originX,$originY $perimeterX,$perimeterY";
244 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
245 }
246 $args[] = wfEscapeShellArg( $filename );
247
248 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
249 $retval = null;
250 wfShellExec( $command, $retval );
251 return ( $retval === 0 );
252 }
253
254 /**
255 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
256 *
257 * @return {String}
258 */
259 public function getRandomColor() {
260 $components = array();
261 for ($i = 0; $i <= 2; $i++ ) {
262 $components[] = mt_rand( 0, 255 );
263 }
264 return 'rgb(' . join(', ', $components) . ')';
265 }
266
267 /**
268 * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
269 *
270 * @param $number Integer: number of pairs
271 * @return Array: of two-element arrays
272 */
273 private function getRandomWordPairs( $number ) {
274 $lines = $this->getRandomLines( $number * 2 );
275 // construct pairs of words
276 $pairs = array();
277 $count = count( $lines );
278 for( $i = 0; $i < $count; $i += 2 ) {
279 $pairs[] = array( $lines[$i], $lines[$i+1] );
280 }
281 return $pairs;
282 }
283
284
285 /**
286 * Return N random lines from a file
287 *
288 * Will throw exception if the file could not be read or if it had fewer lines than requested.
289 *
290 * @param $number_desired Integer: number of lines desired
291 * @return Array: of exactly n elements, drawn randomly from lines the file
292 */
293 private function getRandomLines( $number_desired ) {
294 $filepath = $this->dictionaryFile;
295
296 // initialize array of lines
297 $lines = array();
298 for ( $i = 0; $i < $number_desired; $i++ ) {
299 $lines[] = null;
300 }
301
302 /*
303 * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
304 * a fixed-size array of lines, less and less frequently as it reads the file.
305 */
306 $fh = fopen( $filepath, "r" );
307 if ( !$fh ) {
308 throw new Exception( "couldn't open $filepath" );
309 }
310 $line_number = 0;
311 $max_index = $number_desired - 1;
312 while( !feof( $fh ) ) {
313 $line = fgets( $fh );
314 if ( $line !== false ) {
315 $line_number++;
316 $line = trim( $line );
317 if ( mt_rand( 0, $line_number ) <= $max_index ) {
318 $lines[ mt_rand( 0, $max_index ) ] = $line;
319 }
320 }
321 }
322 fclose( $fh );
323 if ( $line_number < $number_desired ) {
324 throw new Exception( "not enough lines in $filepath" );
325 }
326
327 return $lines;
328 }
329
330 }