Remove hard deprecation of PasswordPolicyChecks::checkPopularPasswordBlacklist
[lhc/web/wiklou.git] / tests / phpunit / includes / api / RandomImageGenerator.php
1 <?php
2 /**
3 * RandomImageGenerator -- does what it says on the tin.
4 * Requires Imagick, the ImageMagick library for PHP, or the command line
5 * equivalent (usually 'convert').
6 *
7 * Because MediaWiki tests the uniqueness of media upload content, and
8 * filenames, it is sometimes useful to generate files that are guaranteed (or
9 * at least very likely) to be unique in both those ways. This generates a
10 * number of filenames with random names and random content (colored triangles).
11 *
12 * It is also useful to have fresh content because our tests currently run in a
13 * "destructive" mode, and don't create a fresh new wiki for each test run.
14 * Consequently, if we just had a few static files we kept re-uploading, we'd
15 * get lots of warnings about matching content or filenames, and even if we
16 * deleted those files, we'd get warnings about archived files.
17 *
18 * This can also be used with a cronjob to generate random files all the time.
19 * I use it to have a constant, never ending supply when I'm testing
20 * interactively.
21 *
22 * @file
23 * @author Neil Kandalgaonkar <neilk@wikimedia.org>
24 */
25
26 use MediaWiki\Shell\Shell;
27
28 /**
29 * RandomImageGenerator: does what it says on the tin.
30 * Can fetch a random image, or also write a number of them to disk with random filenames.
31 */
32 class RandomImageGenerator {
33 private $dictionaryFile;
34 private $minWidth = 400;
35 private $maxWidth = 800;
36 private $minHeight = 400;
37 private $maxHeight = 800;
38 private $shapesToDraw = 5;
39
40 /**
41 * Orientations: 0th row, 0th column, Exif orientation code, rotation 2x2
42 * matrix that is opposite of orientation. N.b. we do not handle the
43 * 'flipped' orientations, which is why there is no entry for 2, 4, 5, or 7.
44 * Those seem to be rare in real images anyway (we also would need a
45 * non-symmetric shape for the images to test those, like a letter F).
46 */
47 private static $orientations = [
48 [
49 '0thRow' => 'top',
50 '0thCol' => 'left',
51 'exifCode' => 1,
52 'counterRotation' => [ [ 1, 0 ], [ 0, 1 ] ]
53 ],
54 [
55 '0thRow' => 'bottom',
56 '0thCol' => 'right',
57 'exifCode' => 3,
58 'counterRotation' => [ [ -1, 0 ], [ 0, -1 ] ]
59 ],
60 [
61 '0thRow' => 'right',
62 '0thCol' => 'top',
63 'exifCode' => 6,
64 'counterRotation' => [ [ 0, 1 ], [ 1, 0 ] ]
65 ],
66 [
67 '0thRow' => 'left',
68 '0thCol' => 'bottom',
69 'exifCode' => 8,
70 'counterRotation' => [ [ 0, -1 ], [ -1, 0 ] ]
71 ]
72 ];
73
74 public function __construct( $options = [] ) {
75 foreach ( [ 'dictionaryFile', 'minWidth', 'minHeight',
76 'maxWidth', 'maxHeight', 'shapesToDraw' ] as $property
77 ) {
78 if ( isset( $options[$property] ) ) {
79 $this->$property = $options[$property];
80 }
81 }
82
83 // find the dictionary file, to generate random names
84 if ( !isset( $this->dictionaryFile ) ) {
85 foreach (
86 [
87 '/usr/share/dict/words',
88 '/usr/dict/words',
89 __DIR__ . '/words.txt'
90 ] as $dictionaryFile
91 ) {
92 if ( is_file( $dictionaryFile ) && is_readable( $dictionaryFile ) ) {
93 $this->dictionaryFile = $dictionaryFile;
94 break;
95 }
96 }
97 }
98 if ( !isset( $this->dictionaryFile ) ) {
99 throw new Exception( "RandomImageGenerator: dictionary file not "
100 . "found or not specified properly" );
101 }
102 }
103
104 /**
105 * Writes random images with random filenames to disk in the directory you
106 * specify, or current working directory.
107 *
108 * @param int $number Number of filenames to write
109 * @param string $format Optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
110 * @param string|null $dir Directory, optional (will default to current working directory)
111 * @return array Filenames we just wrote
112 */
113 function writeImages( $number, $format = 'jpg', $dir = null ) {
114 $filenames = $this->getRandomFilenames( $number, $format, $dir );
115 $imageWriteMethod = $this->getImageWriteMethod( $format );
116 foreach ( $filenames as $filename ) {
117 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
118 }
119
120 return $filenames;
121 }
122
123 /**
124 * Figure out how we write images. This is a factor of both format and the local system
125 *
126 * @param string $format (a typical extension like 'svg', 'jpg', etc.)
127 *
128 * @throws Exception
129 * @return string
130 */
131 function getImageWriteMethod( $format ) {
132 global $wgUseImageMagick, $wgImageMagickConvertCommand;
133 if ( $format === 'svg' ) {
134 return 'writeSvg';
135 } else {
136 // figure out how to write images
137 global $wgExiv2Command;
138 if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
139 return 'writeImageWithApi';
140 } elseif ( $wgUseImageMagick
141 && $wgImageMagickConvertCommand
142 && is_executable( $wgImageMagickConvertCommand )
143 ) {
144 return 'writeImageWithCommandLine';
145 }
146 }
147 throw new Exception( "RandomImageGenerator: could not find a suitable "
148 . "method to write images in '$format' format" );
149 }
150
151 /**
152 * Return a number of randomly-generated filenames
153 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
154 *
155 * @param int $number Number of filenames to generate
156 * @param string $extension Optional, defaults to 'jpg'
157 * @param string $dir Optional, defaults to current working directory
158 * @return array Array of filenames
159 */
160 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
161 if ( is_null( $dir ) ) {
162 $dir = getcwd();
163 }
164 $filenames = [];
165 foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
166 $basename = $pair[0] . '_' . $pair[1];
167 if ( !is_null( $extension ) ) {
168 $basename .= '.' . $extension;
169 }
170 $basename = preg_replace( '/\s+/', '', $basename );
171 $filenames[] = "$dir/$basename";
172 }
173
174 return $filenames;
175 }
176
177 /**
178 * Generate data representing an image of random size (within limits),
179 * consisting of randomly colored and sized upward pointing triangles
180 * against a random background color. (This data is used in the
181 * writeImage* methods).
182 *
183 * @return mixed
184 */
185 public function getImageSpec() {
186 $spec = [];
187
188 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
189 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
190 $spec['fill'] = $this->getRandomColor();
191
192 $diagonalLength = sqrt( $spec['width'] ** 2 + $spec['height'] ** 2 );
193
194 $draws = [];
195 for ( $i = 0; $i <= $this->shapesToDraw; $i++ ) {
196 $radius = mt_rand( 0, $diagonalLength / 4 );
197 if ( $radius == 0 ) {
198 continue;
199 }
200 $originX = mt_rand( -1 * $radius, $spec['width'] + $radius );
201 $originY = mt_rand( -1 * $radius, $spec['height'] + $radius );
202 $angle = mt_rand( 0, ( 3.141592 / 2 ) * $radius ) / $radius;
203 $legDeltaX = round( $radius * sin( $angle ) );
204 $legDeltaY = round( $radius * cos( $angle ) );
205
206 $draw = [];
207 $draw['fill'] = $this->getRandomColor();
208 $draw['shape'] = [
209 [ 'x' => $originX, 'y' => $originY - $radius ],
210 [ 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ],
211 [ 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ],
212 [ 'x' => $originX, 'y' => $originY - $radius ]
213 ];
214 $draws[] = $draw;
215 }
216
217 $spec['draws'] = $draws;
218
219 return $spec;
220 }
221
222 /**
223 * Given [ [ 'x' => 10, 'y' => 20 ], [ 'x' => 30, y=> 5 ] ]
224 * returns "10,20 30,5"
225 * Useful for SVG and imagemagick command line arguments
226 * @param array $shape Array of arrays, each array containing x & y keys mapped to numeric values
227 * @return string
228 */
229 static function shapePointsToString( $shape ) {
230 $points = [];
231 foreach ( $shape as $point ) {
232 $points[] = $point['x'] . ',' . $point['y'];
233 }
234
235 return implode( " ", $points );
236 }
237
238 /**
239 * Based on image specification, write a very simple SVG file to disk.
240 * Ignores the background spec because transparency is cool. :)
241 *
242 * @param array $spec Spec describing background and shapes to draw
243 * @param string $format File format to write (which is obviously always svg here)
244 * @param string $filename Filename to write to
245 *
246 * @throws Exception
247 */
248 public function writeSvg( $spec, $format, $filename ) {
249 $svg = new SimpleXmlElement( '<svg/>' );
250 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
251 $svg->addAttribute( 'version', '1.1' );
252 $svg->addAttribute( 'width', $spec['width'] );
253 $svg->addAttribute( 'height', $spec['height'] );
254 $g = $svg->addChild( 'g' );
255 foreach ( $spec['draws'] as $drawSpec ) {
256 $shape = $g->addChild( 'polygon' );
257 $shape->addAttribute( 'fill', $drawSpec['fill'] );
258 $shape->addAttribute( 'points', self::shapePointsToString( $drawSpec['shape'] ) );
259 }
260
261 $fh = fopen( $filename, 'w' );
262 if ( !$fh ) {
263 throw new Exception( "couldn't open $filename for writing" );
264 }
265 fwrite( $fh, $svg->asXML() );
266 if ( !fclose( $fh ) ) {
267 throw new Exception( "couldn't close $filename" );
268 }
269 }
270
271 /**
272 * Based on an image specification, write such an image to disk, using Imagick PHP extension
273 * @param array $spec Spec describing background and circles to draw
274 * @param string $format File format to write
275 * @param string $filename Filename to write to
276 */
277 public function writeImageWithApi( $spec, $format, $filename ) {
278 // this is a hack because I can't get setImageOrientation() to work. See below.
279 global $wgExiv2Command;
280
281 $image = new Imagick();
282 /**
283 * If the format is 'jpg', will also add a random orientation -- the
284 * image will be drawn rotated with triangle points facing in some
285 * direction (0, 90, 180 or 270 degrees) and a countering rotation
286 * should turn the triangle points upward again.
287 */
288 $orientation = self::$orientations[0]; // default is normal orientation
289 if ( $format == 'jpg' ) {
290 $orientation = self::$orientations[array_rand( self::$orientations )];
291 $spec = self::rotateImageSpec( $spec, $orientation['counterRotation'] );
292 }
293
294 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
295
296 foreach ( $spec['draws'] as $drawSpec ) {
297 $draw = new ImagickDraw();
298 $draw->setFillColor( $drawSpec['fill'] );
299 $draw->polygon( $drawSpec['shape'] );
300 $image->drawImage( $draw );
301 }
302
303 $image->setImageFormat( $format );
304
305 // this doesn't work, even though it's documented to do so...
306 // $image->setImageOrientation( $orientation['exifCode'] );
307
308 $image->writeImage( $filename );
309
310 // because the above setImageOrientation call doesn't work... nor can I
311 // get an external imagemagick binary to do this either... Hacking this
312 // for now (only works if you have exiv2 installed, a program to read
313 // and manipulate exif).
314 if ( $wgExiv2Command ) {
315 $command = Shell::command( $wgExiv2Command,
316 '-M',
317 "set Exif.Image.Orientation {$orientation['exifCode']}",
318 $filename
319 )->includeStderr();
320
321 $result = $command->execute();
322 $retval = $result->getExitCode();
323 if ( $retval !== 0 ) {
324 print "Error with $command: $retval, {$result->getStdout()}\n";
325 }
326 }
327 }
328
329 /**
330 * Given an image specification, produce rotated version
331 * This is used when simulating a rotated image capture with Exif orientation
332 * @param array $spec Returned by getImageSpec
333 * @param array $matrix 2x2 transformation matrix
334 * @return array Transformed Spec
335 */
336 private static function rotateImageSpec( &$spec, $matrix ) {
337 $tSpec = [];
338 $dims = self::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] );
339 $correctionX = 0;
340 $correctionY = 0;
341 if ( $dims['x'] < 0 ) {
342 $correctionX = abs( $dims['x'] );
343 }
344 if ( $dims['y'] < 0 ) {
345 $correctionY = abs( $dims['y'] );
346 }
347 $tSpec['width'] = abs( $dims['x'] );
348 $tSpec['height'] = abs( $dims['y'] );
349 $tSpec['fill'] = $spec['fill'];
350 $tSpec['draws'] = [];
351 foreach ( $spec['draws'] as $draw ) {
352 $tDraw = [
353 'fill' => $draw['fill'],
354 'shape' => []
355 ];
356 foreach ( $draw['shape'] as $point ) {
357 $tPoint = self::matrixMultiply2x2( $matrix, $point['x'], $point['y'] );
358 $tPoint['x'] += $correctionX;
359 $tPoint['y'] += $correctionY;
360 $tDraw['shape'][] = $tPoint;
361 }
362 $tSpec['draws'][] = $tDraw;
363 }
364
365 return $tSpec;
366 }
367
368 /**
369 * Given a matrix and a pair of images, return new position
370 * @param array $matrix 2x2 rotation matrix
371 * @param int $x The x-coordinate number
372 * @param int $y The y-coordinate number
373 * @return array Transformed with properties x, y
374 */
375 private static function matrixMultiply2x2( $matrix, $x, $y ) {
376 return [
377 'x' => $x * $matrix[0][0] + $y * $matrix[0][1],
378 'y' => $x * $matrix[1][0] + $y * $matrix[1][1]
379 ];
380 }
381
382 /**
383 * Based on an image specification, write such an image to disk, using the
384 * command line ImageMagick program ('convert').
385 *
386 * Sample command line:
387 * $ convert -size 100x60 xc:rgb(90,87,45) \
388 * -draw 'fill rgb(12,34,56) polygon 41,39 44,57 50,57 41,39' \
389 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
390 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
391 *
392 * @param array $spec Spec describing background and shapes to draw
393 * @param string $format File format to write (unused by this method but
394 * kept so it has the same signature as writeImageWithApi).
395 * @param string $filename Filename to write to
396 *
397 * @return bool
398 */
399 public function writeImageWithCommandLine( $spec, $format, $filename ) {
400 global $wgImageMagickConvertCommand;
401
402 $args = [
403 $wgImageMagickConvertCommand,
404 '-size',
405 $spec['width'] . 'x' . $spec['height'],
406 "xc:{$spec['fill']}",
407 ];
408 foreach ( $spec['draws'] as $draw ) {
409 $fill = $draw['fill'];
410 $polygon = self::shapePointsToString( $draw['shape'] );
411 $drawCommand = "fill $fill polygon $polygon";
412 $args[] = '-draw';
413 $args[] = $drawCommand;
414 }
415 $args[] = $filename;
416
417 $result = Shell::command( $args )->execute();
418
419 return ( $result->getExitCode() === 0 );
420 }
421
422 /**
423 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
424 *
425 * @return string
426 */
427 public function getRandomColor() {
428 $components = [];
429 for ( $i = 0; $i <= 2; $i++ ) {
430 $components[] = mt_rand( 0, 255 );
431 }
432
433 return 'rgb(' . implode( ', ', $components ) . ')';
434 }
435
436 /**
437 * Get an array of random pairs of random words, like
438 * [ [ 'foo', 'bar' ], [ 'quux', 'baz' ] ];
439 *
440 * @param int $number Number of pairs
441 * @return array Two-element arrays
442 */
443 private function getRandomWordPairs( $number ) {
444 $lines = $this->getRandomLines( $number * 2 );
445 // construct pairs of words
446 $pairs = [];
447 $count = count( $lines );
448 for ( $i = 0; $i < $count; $i += 2 ) {
449 $pairs[] = [ $lines[$i], $lines[$i + 1] ];
450 }
451
452 return $pairs;
453 }
454
455 /**
456 * Return N random lines from a file
457 *
458 * Will throw exception if the file could not be read or if it had fewer lines than requested.
459 *
460 * @param int $number_desired Number of lines desired
461 *
462 * @throws Exception
463 * @return array Array of exactly n elements, drawn randomly from lines the file
464 */
465 private function getRandomLines( $number_desired ) {
466 $filepath = $this->dictionaryFile;
467
468 // initialize array of lines
469 $lines = [];
470 for ( $i = 0; $i < $number_desired; $i++ ) {
471 $lines[] = null;
472 }
473
474 /*
475 * This algorithm obtains N random lines from a file in one single pass.
476 * It does this by replacing elements of a fixed-size array of lines,
477 * less and less frequently as it reads the file.
478 */
479 $fh = fopen( $filepath, "r" );
480 if ( !$fh ) {
481 throw new Exception( "couldn't open $filepath" );
482 }
483 $line_number = 0;
484 $max_index = $number_desired - 1;
485 while ( !feof( $fh ) ) {
486 $line = fgets( $fh );
487 if ( $line !== false ) {
488 $line_number++;
489 $line = trim( $line );
490 if ( mt_rand( 0, $line_number ) <= $max_index ) {
491 $lines[mt_rand( 0, $max_index )] = $line;
492 }
493 }
494 }
495 fclose( $fh );
496 if ( $line_number < $number_desired ) {
497 throw new Exception( "not enough lines in $filepath" );
498 }
499
500 return $lines;
501 }
502 }