fix invocation of static function
[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 * Given array( array('x' => 10, 'y' => 20), array( 'x' => 30, y=> 5 ) )
166 * returns "10,20 30,5"
167 * Useful for SVG and imagemagick command line arguments
168 * @param $shape: Array of arrays, each array containing x & y keys mapped to numeric values
169 * @return string
170 */
171 static function shapePointsToString( $shape ) {
172 $points = array();
173 foreach ( $shape as $point ) {
174 $points[] = $point['x'] . ',' . $point['y'];
175 }
176 return join( " ", $points );
177 }
178
179 /**
180 * Based on image specification, write a very simple SVG file to disk.
181 * Ignores the background spec because transparency is cool. :)
182 * @param $spec: spec describing background and circles to draw
183 * @param $format: file format to write (which is obviously always svg here)
184 * @param $filename: filename to write to
185 */
186 public function writeSvg( $spec, $format, $filename ) {
187 $svg = new SimpleXmlElement( '<svg/>' );
188 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
189 $svg->addAttribute( 'version', '1.1' );
190 $svg->addAttribute( 'width', $spec['width'] );
191 $svg->addAttribute( 'height', $spec['height'] );
192 $g = $svg->addChild( 'g' );
193 foreach ( $spec['draws'] as $drawSpec ) {
194 $shape = $g->addChild( 'polygon' );
195 $shape->addAttribute( 'fill', $drawSpec['fill'] );
196 $shape->addAttribute( 'points', self::shapePointsToString( $drawSpec['shape'] ) );
197 };
198 if ( ! $fh = fopen( $filename, 'w' ) ) {
199 throw new Exception( "couldn't open $filename for writing" );
200 }
201 fwrite( $fh, $svg->asXML() );
202 if ( !fclose($fh) ) {
203 throw new Exception( "couldn't close $filename" );
204 }
205 }
206
207 /**
208 * Based on an image specification, write such an image to disk, using Imagick PHP extension
209 * @param $spec: spec describing background and circles to draw
210 * @param $format: file format to write
211 * @param $filename: filename to write to
212 */
213 public function writeImageWithApi( $spec, $format, $filename ) {
214 $image = new Imagick();
215 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
216
217 foreach ( $spec['draws'] as $drawSpec ) {
218 $draw = new ImagickDraw();
219 $draw->setFillColor( $drawSpec['fill'] );
220 $draw->polygon( $drawSpec['shape'] );
221 $image->drawImage( $draw );
222 }
223
224 $image->setImageFormat( $format );
225 $image->writeImage( $filename );
226 }
227
228
229 /**
230 * Based on an image specification, write such an image to disk, using the command line ImageMagick program ('convert').
231 *
232 * Sample command line:
233 * $ convert -size 100x60 xc:rgb(90,87,45) \
234 * -draw 'fill rgb(12,34,56) polygon 41,39 44,57 50,57 41,39' \
235 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
236 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
237 *
238 * @param $spec: spec describing background and circles to draw
239 * @param $format: file format to write (unused by this method but kept so it has the same signature as writeImageWithApi)
240 * @param $filename: filename to write to
241 */
242 public function writeImageWithCommandLine( $spec, $format, $filename ) {
243 global $wgImageMagickConvertCommand;
244 $args = array();
245 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
246 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
247 foreach( $spec['draws'] as $draw ) {
248 $fill = $draw['fill'];
249 $polygon = self::shapePointsToString( $draw['shape'] );
250 $drawCommand = "fill $fill polygon $polygon";
251 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
252 }
253 $args[] = wfEscapeShellArg( $filename );
254
255 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
256 $retval = null;
257 wfShellExec( $command, $retval );
258 return ( $retval === 0 );
259 }
260
261 /**
262 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
263 *
264 * @return {String}
265 */
266 public function getRandomColor() {
267 $components = array();
268 for ($i = 0; $i <= 2; $i++ ) {
269 $components[] = mt_rand( 0, 255 );
270 }
271 return 'rgb(' . join(', ', $components) . ')';
272 }
273
274 /**
275 * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
276 *
277 * @param $number Integer: number of pairs
278 * @return Array: of two-element arrays
279 */
280 private function getRandomWordPairs( $number ) {
281 $lines = $this->getRandomLines( $number * 2 );
282 // construct pairs of words
283 $pairs = array();
284 $count = count( $lines );
285 for( $i = 0; $i < $count; $i += 2 ) {
286 $pairs[] = array( $lines[$i], $lines[$i+1] );
287 }
288 return $pairs;
289 }
290
291
292 /**
293 * Return N random lines from a file
294 *
295 * Will throw exception if the file could not be read or if it had fewer lines than requested.
296 *
297 * @param $number_desired Integer: number of lines desired
298 * @return Array: of exactly n elements, drawn randomly from lines the file
299 */
300 private function getRandomLines( $number_desired ) {
301 $filepath = $this->dictionaryFile;
302
303 // initialize array of lines
304 $lines = array();
305 for ( $i = 0; $i < $number_desired; $i++ ) {
306 $lines[] = null;
307 }
308
309 /*
310 * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
311 * a fixed-size array of lines, less and less frequently as it reads the file.
312 */
313 $fh = fopen( $filepath, "r" );
314 if ( !$fh ) {
315 throw new Exception( "couldn't open $filepath" );
316 }
317 $line_number = 0;
318 $max_index = $number_desired - 1;
319 while( !feof( $fh ) ) {
320 $line = fgets( $fh );
321 if ( $line !== false ) {
322 $line_number++;
323 $line = trim( $line );
324 if ( mt_rand( 0, $line_number ) <= $max_index ) {
325 $lines[ mt_rand( 0, $max_index ) ] = $line;
326 }
327 }
328 }
329 fclose( $fh );
330 if ( $line_number < $number_desired ) {
331 throw new Exception( "not enough lines in $filepath" );
332 }
333
334 return $lines;
335 }
336
337 }