BitmapMetadataHandler.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. /**
  3. * Extraction of metadata from different bitmap image types.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup Media
  22. */
  23. use MediaWiki\Logger\LoggerFactory;
  24. use Wikimedia\XMPReader\Reader as XMPReader;
  25. /**
  26. * Class to deal with reconciling and extracting metadata from bitmap images.
  27. * This is meant to comply with http://www.metadataworkinggroup.org/pdf/mwg_guidance.pdf
  28. *
  29. * This sort of acts as an intermediary between MediaHandler::getMetadata
  30. * and the various metadata extractors.
  31. *
  32. * @todo Other image formats.
  33. * @ingroup Media
  34. */
  35. class BitmapMetadataHandler {
  36. /** @var array */
  37. private $metadata = [];
  38. /** @var array Metadata priority */
  39. private $metaPriority = [
  40. 20 => [ 'other' ],
  41. 40 => [ 'native' ],
  42. 60 => [ 'iptc-good-hash', 'iptc-no-hash' ],
  43. 70 => [ 'xmp-deprecated' ],
  44. 80 => [ 'xmp-general' ],
  45. 90 => [ 'xmp-exif' ],
  46. 100 => [ 'iptc-bad-hash' ],
  47. 120 => [ 'exif' ],
  48. ];
  49. /** @var string */
  50. private $iptcType = 'iptc-no-hash';
  51. /**
  52. * This does the photoshop image resource app13 block
  53. * of interest, IPTC-IIM metadata is stored here.
  54. *
  55. * Mostly just calls doPSIR and doIPTC
  56. *
  57. * @param string $app13 String containing app13 block from jpeg file
  58. */
  59. private function doApp13( $app13 ) {
  60. try {
  61. $this->iptcType = JpegMetadataExtractor::doPSIR( $app13 );
  62. } catch ( Exception $e ) {
  63. // Error reading the iptc hash information.
  64. // This probably means the App13 segment is something other than what we expect.
  65. // However, still try to read it, and treat it as if the hash didn't exist.
  66. wfDebug( "Error parsing iptc data of file: " . $e->getMessage() . "\n" );
  67. $this->iptcType = 'iptc-no-hash';
  68. }
  69. $iptc = IPTC::parse( $app13 );
  70. $this->addMetadata( $iptc, $this->iptcType );
  71. }
  72. /**
  73. * Get exif info using exif class.
  74. * Basically what used to be in BitmapHandler::getMetadata().
  75. * Just calls stuff in the Exif class.
  76. *
  77. * Parameters are passed to the Exif class.
  78. *
  79. * @param string $filename
  80. * @param string $byteOrder
  81. */
  82. function getExif( $filename, $byteOrder ) {
  83. global $wgShowEXIF;
  84. if ( file_exists( $filename ) && $wgShowEXIF ) {
  85. $exif = new Exif( $filename, $byteOrder );
  86. $data = $exif->getFilteredData();
  87. if ( $data ) {
  88. $this->addMetadata( $data, 'exif' );
  89. }
  90. }
  91. }
  92. /** Add misc metadata. Warning: atm if the metadata category
  93. * doesn't have a priority, it will be silently discarded.
  94. *
  95. * @param array $metaArray Array of metadata values
  96. * @param string $type Type. defaults to other. if two things have the same type they're merged
  97. */
  98. function addMetadata( $metaArray, $type = 'other' ) {
  99. if ( isset( $this->metadata[$type] ) ) {
  100. /* merge with old data */
  101. $metaArray = $metaArray + $this->metadata[$type];
  102. }
  103. $this->metadata[$type] = $metaArray;
  104. }
  105. /**
  106. * Merge together the various types of metadata
  107. * the different types have different priorites,
  108. * and are merged in order.
  109. *
  110. * This function is generally called by the media handlers' getMetadata()
  111. *
  112. * @return array Metadata array
  113. */
  114. function getMetadataArray() {
  115. // this seems a bit ugly... This is all so its merged in right order
  116. // based on the MWG recommendation.
  117. $temp = [];
  118. krsort( $this->metaPriority );
  119. foreach ( $this->metaPriority as $pri ) {
  120. foreach ( $pri as $type ) {
  121. if ( isset( $this->metadata[$type] ) ) {
  122. // Do some special casing for multilingual values.
  123. // Don't discard translations if also as a simple value.
  124. foreach ( $this->metadata[$type] as $itemName => $item ) {
  125. if ( is_array( $item ) && isset( $item['_type'] ) && $item['_type'] === 'lang' &&
  126. isset( $temp[$itemName] ) && !is_array( $temp[$itemName] )
  127. ) {
  128. $default = $temp[$itemName];
  129. $temp[$itemName] = $item;
  130. $temp[$itemName]['x-default'] = $default;
  131. unset( $this->metadata[$type][$itemName] );
  132. }
  133. }
  134. $temp = $temp + $this->metadata[$type];
  135. }
  136. }
  137. }
  138. return $temp;
  139. }
  140. /** Main entry point for jpeg's.
  141. *
  142. * @param string $filename Filename (with full path)
  143. * @return array Metadata result array.
  144. * @throws MWException On invalid file.
  145. */
  146. static function Jpeg( $filename ) {
  147. $showXMP = XMPReader::isSupported();
  148. $meta = new self();
  149. $seg = JpegMetadataExtractor::segmentSplitter( $filename );
  150. if ( isset( $seg['COM'] ) && isset( $seg['COM'][0] ) ) {
  151. $meta->addMetadata( [ 'JPEGFileComment' => $seg['COM'] ], 'native' );
  152. }
  153. if ( isset( $seg['PSIR'] ) && count( $seg['PSIR'] ) > 0 ) {
  154. foreach ( $seg['PSIR'] as $curPSIRValue ) {
  155. $meta->doApp13( $curPSIRValue );
  156. }
  157. }
  158. if ( isset( $seg['XMP'] ) && $showXMP ) {
  159. $xmp = new XMPReader( LoggerFactory::getInstance( 'XMP' ), $filename );
  160. $xmp->parse( $seg['XMP'] );
  161. foreach ( $seg['XMP_ext'] as $xmpExt ) {
  162. /* Support for extended xmp in jpeg files
  163. * is not well tested and a bit fragile.
  164. */
  165. $xmp->parseExtended( $xmpExt );
  166. }
  167. $res = $xmp->getResults();
  168. foreach ( $res as $type => $array ) {
  169. $meta->addMetadata( $array, $type );
  170. }
  171. }
  172. $meta->getExif( $filename, $seg['byteOrder'] ?? 'BE' );
  173. return $meta->getMetadataArray();
  174. }
  175. /** Entry point for png
  176. * At some point in the future this might
  177. * merge the png various tEXt chunks to that
  178. * are interesting, but for now it only does XMP
  179. *
  180. * @param string $filename Full path to file
  181. * @return array Array for storage in img_metadata.
  182. */
  183. public static function PNG( $filename ) {
  184. $showXMP = XMPReader::isSupported();
  185. $meta = new self();
  186. $array = PNGMetadataExtractor::getMetadata( $filename );
  187. if ( isset( $array['text']['xmp']['x-default'] )
  188. && $array['text']['xmp']['x-default'] !== '' && $showXMP
  189. ) {
  190. $xmp = new XMPReader( LoggerFactory::getInstance( 'XMP' ), $filename );
  191. $xmp->parse( $array['text']['xmp']['x-default'] );
  192. $xmpRes = $xmp->getResults();
  193. foreach ( $xmpRes as $type => $xmpSection ) {
  194. $meta->addMetadata( $xmpSection, $type );
  195. }
  196. }
  197. unset( $array['text']['xmp'] );
  198. $meta->addMetadata( $array['text'], 'native' );
  199. unset( $array['text'] );
  200. $array['metadata'] = $meta->getMetadataArray();
  201. $array['metadata']['_MW_PNG_VERSION'] = PNGMetadataExtractor::VERSION;
  202. return $array;
  203. }
  204. /** function for gif images.
  205. *
  206. * They don't really have native metadata, so just merges together
  207. * XMP and image comment.
  208. *
  209. * @param string $filename Full path to file
  210. * @return array Metadata array
  211. */
  212. public static function GIF( $filename ) {
  213. $meta = new self();
  214. $baseArray = GIFMetadataExtractor::getMetadata( $filename );
  215. if ( count( $baseArray['comment'] ) > 0 ) {
  216. $meta->addMetadata( [ 'GIFFileComment' => $baseArray['comment'] ], 'native' );
  217. }
  218. if ( $baseArray['xmp'] !== '' && XMPReader::isSupported() ) {
  219. $xmp = new XMPReader( LoggerFactory::getInstance( 'XMP' ), $filename );
  220. $xmp->parse( $baseArray['xmp'] );
  221. $xmpRes = $xmp->getResults();
  222. foreach ( $xmpRes as $type => $xmpSection ) {
  223. $meta->addMetadata( $xmpSection, $type );
  224. }
  225. }
  226. unset( $baseArray['comment'] );
  227. unset( $baseArray['xmp'] );
  228. $baseArray['metadata'] = $meta->getMetadataArray();
  229. $baseArray['metadata']['_MW_GIF_VERSION'] = GIFMetadataExtractor::VERSION;
  230. return $baseArray;
  231. }
  232. /**
  233. * This doesn't do much yet, but eventually I plan to add
  234. * XMP support for Tiff. (PHP's exif support already extracts
  235. * but needs some further processing because PHP's exif support
  236. * is stupid...)
  237. *
  238. * @todo Add XMP support, so this function actually makes sense to put here.
  239. *
  240. * The various exceptions this throws are caught later.
  241. * @param string $filename
  242. * @throws MWException
  243. * @return array The metadata.
  244. */
  245. public static function Tiff( $filename ) {
  246. if ( file_exists( $filename ) ) {
  247. $byteOrder = self::getTiffByteOrder( $filename );
  248. if ( !$byteOrder ) {
  249. throw new MWException( "Error determining byte order of $filename" );
  250. }
  251. $exif = new Exif( $filename, $byteOrder );
  252. $data = $exif->getFilteredData();
  253. if ( $data ) {
  254. $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
  255. return $data;
  256. } else {
  257. throw new MWException( "Could not extract data from tiff file $filename" );
  258. }
  259. } else {
  260. throw new MWException( "File doesn't exist - $filename" );
  261. }
  262. }
  263. /**
  264. * Read the first 2 bytes of a tiff file to figure out
  265. * Little Endian or Big Endian. Needed for exif stuff.
  266. *
  267. * @param string $filename
  268. * @return string 'BE' or 'LE' or false
  269. */
  270. static function getTiffByteOrder( $filename ) {
  271. $fh = fopen( $filename, 'rb' );
  272. if ( !$fh ) {
  273. return false;
  274. }
  275. $head = fread( $fh, 2 );
  276. fclose( $fh );
  277. switch ( $head ) {
  278. case 'II':
  279. return 'LE'; // II for intel.
  280. case 'MM':
  281. return 'BE'; // MM for motorla.
  282. default:
  283. return false; // Something went wrong.
  284. }
  285. }
  286. }