PageRenderTime 28ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/phpunit/includes/api/RandomImageGenerator.php

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