c2bf39fc3e0a2225f564c7df9e57aa7a2c4104ef
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 */
4
5 /**
6 * NOTE FOR WINDOWS USERS:
7 * To enable EXIF functions, add the folloing lines to the
8 * "Windows extensions" section of php.ini:
9 *
10 * extension=extensions/php_mbstring.dll
11 * extension=extensions/php_exif.dll
12 */
13
14 /**
15 * Bump this number when serialized cache records may be incompatible.
16 */
17 define( 'MW_IMAGE_VERSION', 1 );
18
19 /**
20 * Class to represent an image
21 *
22 * Provides methods to retrieve paths (physical, logical, URL),
23 * to generate thumbnails or for uploading.
24 */
25 class Image
26 {
27 /**#@+
28 * @private
29 */
30 var $name, # name of the image (constructor)
31 $imagePath, # Path of the image (loadFromXxx)
32 $url, # Image URL (accessor)
33 $title, # Title object for this image (constructor)
34 $fileExists, # does the image file exist on disk? (loadFromXxx)
35 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
36 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
37 $historyRes, # result of the query for the image's history (nextHistoryLine)
38 $width, # \
39 $height, # |
40 $bits, # --- returned by getimagesize (loadFromXxx)
41 $attr, # /
42 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
43 $mime, # MIME type, determined by MimeMagic::guessMimeType
44 $size, # Size in bytes (loadFromXxx)
45 $metadata, # Metadata
46 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
47 $page, # Page to render when creating thumbnails
48 $lastError; # Error string associated with a thumbnail display error
49
50
51 /**#@-*/
52
53 /**
54 * Create an Image object from an image name
55 *
56 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
57 * @public
58 */
59 public static function newFromName( $name ) {
60 $title = Title::makeTitleSafe( NS_IMAGE, $name );
61 if ( is_object( $title ) ) {
62 return new Image( $title );
63 } else {
64 return NULL;
65 }
66 }
67
68 /**
69 * Obsolete factory function, use constructor
70 * @deprecated
71 */
72 function newFromTitle( $title ) {
73 return new Image( $title );
74 }
75
76 function Image( $title ) {
77 if( !is_object( $title ) ) {
78 throw new MWException( 'Image constructor given bogus title.' );
79 }
80 $this->title =& $title;
81 $this->name = $title->getDBkey();
82 $this->metadata = serialize ( array() ) ;
83
84 $n = strrpos( $this->name, '.' );
85 $this->extension = Image::normalizeExtension( $n ?
86 substr( $this->name, $n + 1 ) : '' );
87 $this->historyLine = 0;
88 $this->page = 1;
89
90 $this->dataLoaded = false;
91 }
92
93
94 /**
95 * Normalize a file extension to the common form, and ensure it's clean.
96 * Extensions with non-alphanumeric characters will be discarded.
97 *
98 * @param $ext string (without the .)
99 * @return string
100 */
101 static function normalizeExtension( $ext ) {
102 $lower = strtolower( $ext );
103 $squish = array(
104 'htm' => 'html',
105 'jpeg' => 'jpg',
106 'mpeg' => 'mpg',
107 'tiff' => 'tif' );
108 if( isset( $squish[$lower] ) ) {
109 return $squish[$lower];
110 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
111 return $lower;
112 } else {
113 return '';
114 }
115 }
116
117 /**
118 * Get the memcached keys
119 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
120 */
121 function getCacheKeys( ) {
122 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
123
124 $hashedName = md5($this->name);
125 $keys = array( wfMemcKey( 'Image', $hashedName ) );
126 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
127 $keys[] = wfForeignMemcKey( $wgSharedUploadDBname, false, 'Image', $hashedName );
128 }
129 return $keys;
130 }
131
132 /**
133 * Try to load image metadata from memcached. Returns true on success.
134 */
135 function loadFromCache() {
136 global $wgUseSharedUploads, $wgMemc;
137 wfProfileIn( __METHOD__ );
138 $this->dataLoaded = false;
139 $keys = $this->getCacheKeys();
140 $cachedValues = $wgMemc->get( $keys[0] );
141
142 // Check if the key existed and belongs to this version of MediaWiki
143 if (!empty($cachedValues) && is_array($cachedValues)
144 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION )
145 && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
146 {
147 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
148 # if this is shared file, we need to check if image
149 # in shared repository has not changed
150 if ( isset( $keys[1] ) ) {
151 $commonsCachedValues = $wgMemc->get( $keys[1] );
152 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
153 && isset($commonsCachedValues['version'])
154 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION )
155 && isset($commonsCachedValues['mime'])) {
156 wfDebug( "Pulling image metadata from shared repository cache\n" );
157 $this->name = $commonsCachedValues['name'];
158 $this->imagePath = $commonsCachedValues['imagePath'];
159 $this->fileExists = $commonsCachedValues['fileExists'];
160 $this->width = $commonsCachedValues['width'];
161 $this->height = $commonsCachedValues['height'];
162 $this->bits = $commonsCachedValues['bits'];
163 $this->type = $commonsCachedValues['type'];
164 $this->mime = $commonsCachedValues['mime'];
165 $this->metadata = $commonsCachedValues['metadata'];
166 $this->size = $commonsCachedValues['size'];
167 $this->fromSharedDirectory = true;
168 $this->dataLoaded = true;
169 $this->imagePath = $this->getFullPath(true);
170 }
171 }
172 } else {
173 wfDebug( "Pulling image metadata from local cache\n" );
174 $this->name = $cachedValues['name'];
175 $this->imagePath = $cachedValues['imagePath'];
176 $this->fileExists = $cachedValues['fileExists'];
177 $this->width = $cachedValues['width'];
178 $this->height = $cachedValues['height'];
179 $this->bits = $cachedValues['bits'];
180 $this->type = $cachedValues['type'];
181 $this->mime = $cachedValues['mime'];
182 $this->metadata = $cachedValues['metadata'];
183 $this->size = $cachedValues['size'];
184 $this->fromSharedDirectory = false;
185 $this->dataLoaded = true;
186 $this->imagePath = $this->getFullPath();
187 }
188 }
189 if ( $this->dataLoaded ) {
190 wfIncrStats( 'image_cache_hit' );
191 } else {
192 wfIncrStats( 'image_cache_miss' );
193 }
194
195 wfProfileOut( __METHOD__ );
196 return $this->dataLoaded;
197 }
198
199 /**
200 * Save the image metadata to memcached
201 */
202 function saveToCache() {
203 global $wgMemc, $wgUseSharedUploads;
204 $this->load();
205 $keys = $this->getCacheKeys();
206 // We can't cache negative metadata for non-existent files,
207 // because if the file later appears in commons, the local
208 // keys won't be purged.
209 if ( $this->fileExists || !$wgUseSharedUploads ) {
210 $cachedValues = array(
211 'version' => MW_IMAGE_VERSION,
212 'name' => $this->name,
213 'imagePath' => $this->imagePath,
214 'fileExists' => $this->fileExists,
215 'fromShared' => $this->fromSharedDirectory,
216 'width' => $this->width,
217 'height' => $this->height,
218 'bits' => $this->bits,
219 'type' => $this->type,
220 'mime' => $this->mime,
221 'metadata' => $this->metadata,
222 'size' => $this->size );
223
224 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
225 } else {
226 // However we should clear them, so they aren't leftover
227 // if we've deleted the file.
228 $wgMemc->delete( $keys[0] );
229 }
230 }
231
232 /**
233 * Load metadata from the file itself
234 */
235 function loadFromFile() {
236 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang;
237 wfProfileIn( __METHOD__ );
238 $this->imagePath = $this->getFullPath();
239 $this->fileExists = file_exists( $this->imagePath );
240 $this->fromSharedDirectory = false;
241 $gis = array();
242
243 if (!$this->fileExists) wfDebug(__METHOD__.': '.$this->imagePath." not found locally!\n");
244
245 # If the file is not found, and a shared upload directory is used, look for it there.
246 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
247 # In case we're on a wgCapitalLinks=false wiki, we
248 # capitalize the first letter of the filename before
249 # looking it up in the shared repository.
250 $sharedImage = Image::newFromName( $wgContLang->ucfirst($this->name) );
251 $this->fileExists = $sharedImage && file_exists( $sharedImage->getFullPath(true) );
252 if ( $this->fileExists ) {
253 $this->name = $sharedImage->name;
254 $this->imagePath = $this->getFullPath(true);
255 $this->fromSharedDirectory = true;
256 }
257 }
258
259
260 if ( $this->fileExists ) {
261 $magic=& MimeMagic::singleton();
262
263 $this->mime = $magic->guessMimeType($this->imagePath,true);
264 $this->type = $magic->getMediaType($this->imagePath,$this->mime);
265
266 # Get size in bytes
267 $this->size = filesize( $this->imagePath );
268
269 $magic=& MimeMagic::singleton();
270
271 # Height and width
272 wfSuppressWarnings();
273 if( $this->mime == 'image/svg' ) {
274 $gis = wfGetSVGsize( $this->imagePath );
275 } elseif( $this->mime == 'image/vnd.djvu' ) {
276 $deja = new DjVuImage( $this->imagePath );
277 $gis = $deja->getImageSize();
278 } elseif ( !$magic->isPHPImageType( $this->mime ) ) {
279 # Don't try to get the width and height of sound and video files, that's bad for performance
280 $gis = false;
281 } else {
282 $gis = getimagesize( $this->imagePath );
283 }
284 wfRestoreWarnings();
285
286 wfDebug(__METHOD__.': '.$this->imagePath." loaded, ".$this->size." bytes, ".$this->mime.".\n");
287 }
288 else {
289 $this->mime = NULL;
290 $this->type = MEDIATYPE_UNKNOWN;
291 wfDebug(__METHOD__.': '.$this->imagePath." NOT FOUND!\n");
292 }
293
294 if( $gis ) {
295 $this->width = $gis[0];
296 $this->height = $gis[1];
297 } else {
298 $this->width = 0;
299 $this->height = 0;
300 }
301
302 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
303
304 #NOTE: we have to set this flag early to avoid load() to be called
305 # be some of the functions below. This may lead to recursion or other bad things!
306 # as ther's only one thread of execution, this should be safe anyway.
307 $this->dataLoaded = true;
308
309
310 if ( $this->mime == 'image/vnd.djvu' ) {
311 $this->metadata = $deja->retrieveMetaData();
312 } else {
313 $this->metadata = serialize( $this->retrieveExifData( $this->imagePath ) );
314 }
315
316 if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
317 else $this->bits = 0;
318
319 wfProfileOut( __METHOD__ );
320 }
321
322 /**
323 * Load image metadata from the DB
324 */
325 function loadFromDB() {
326 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
327 wfProfileIn( __METHOD__ );
328
329 $dbr = wfGetDB( DB_SLAVE );
330 $this->checkDBSchema($dbr);
331
332 $row = $dbr->selectRow( 'image',
333 array( 'img_size', 'img_width', 'img_height', 'img_bits',
334 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
335 array( 'img_name' => $this->name ), __METHOD__ );
336 if ( $row ) {
337 $this->fromSharedDirectory = false;
338 $this->fileExists = true;
339 $this->loadFromRow( $row );
340 $this->imagePath = $this->getFullPath();
341 // Check for rows from a previous schema, quietly upgrade them
342 if ( is_null($this->type) ) {
343 $this->upgradeRow();
344 }
345 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
346 # In case we're on a wgCapitalLinks=false wiki, we
347 # capitalize the first letter of the filename before
348 # looking it up in the shared repository.
349 $name = $wgContLang->ucfirst($this->name);
350 $dbc = wfGetDB( DB_SLAVE, 'commons' );
351
352 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
353 array(
354 'img_size', 'img_width', 'img_height', 'img_bits',
355 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
356 array( 'img_name' => $name ), __METHOD__ );
357 if ( $row ) {
358 $this->fromSharedDirectory = true;
359 $this->fileExists = true;
360 $this->imagePath = $this->getFullPath(true);
361 $this->name = $name;
362 $this->loadFromRow( $row );
363
364 // Check for rows from a previous schema, quietly upgrade them
365 if ( is_null($this->type) ) {
366 $this->upgradeRow();
367 }
368 }
369 }
370
371 if ( !$row ) {
372 $this->size = 0;
373 $this->width = 0;
374 $this->height = 0;
375 $this->bits = 0;
376 $this->type = 0;
377 $this->fileExists = false;
378 $this->fromSharedDirectory = false;
379 $this->metadata = serialize ( array() ) ;
380 $this->mime = false;
381 }
382
383 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
384 $this->dataLoaded = true;
385 wfProfileOut( __METHOD__ );
386 }
387
388 /*
389 * Load image metadata from a DB result row
390 */
391 function loadFromRow( &$row ) {
392 $this->size = $row->img_size;
393 $this->width = $row->img_width;
394 $this->height = $row->img_height;
395 $this->bits = $row->img_bits;
396 $this->type = $row->img_media_type;
397
398 $major= $row->img_major_mime;
399 $minor= $row->img_minor_mime;
400
401 if (!$major) $this->mime = "unknown/unknown";
402 else {
403 if (!$minor) $minor= "unknown";
404 $this->mime = $major.'/'.$minor;
405 }
406
407 $this->metadata = $row->img_metadata;
408 if ( $this->metadata == "" ) $this->metadata = serialize ( array() ) ;
409
410 $this->dataLoaded = true;
411 }
412
413 /**
414 * Load image metadata from cache or DB, unless already loaded
415 */
416 function load() {
417 global $wgSharedUploadDBname, $wgUseSharedUploads;
418 if ( !$this->dataLoaded ) {
419 if ( !$this->loadFromCache() ) {
420 $this->loadFromDB();
421 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
422 $this->loadFromFile();
423 } elseif ( $this->fileExists || !$wgUseSharedUploads ) {
424 // We can do negative caching for local images, because the cache
425 // will be purged on upload. But we can't do it when shared images
426 // are enabled, since updates to that won't purge foreign caches.
427 $this->saveToCache();
428 }
429 }
430 $this->dataLoaded = true;
431 }
432 }
433
434 /**
435 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
436 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
437 */
438 function upgradeRow() {
439 global $wgDBname, $wgSharedUploadDBname;
440 wfProfileIn( __METHOD__ );
441
442 $this->loadFromFile();
443
444 if ( $this->fromSharedDirectory ) {
445 if ( !$wgSharedUploadDBname ) {
446 wfProfileOut( __METHOD__ );
447 return;
448 }
449
450 // Write to the other DB using selectDB, not database selectors
451 // This avoids breaking replication in MySQL
452 $dbw = wfGetDB( DB_MASTER, 'commons' );
453 $dbw->selectDB( $wgSharedUploadDBname );
454 } else {
455 $dbw = wfGetDB( DB_MASTER );
456 }
457
458 $this->checkDBSchema($dbw);
459
460 list( $major, $minor ) = self::splitMime( $this->mime );
461
462 wfDebug(__METHOD__.': upgrading '.$this->name." to 1.5 schema\n");
463
464 $dbw->update( 'image',
465 array(
466 'img_width' => $this->width,
467 'img_height' => $this->height,
468 'img_bits' => $this->bits,
469 'img_media_type' => $this->type,
470 'img_major_mime' => $major,
471 'img_minor_mime' => $minor,
472 'img_metadata' => $this->metadata,
473 ), array( 'img_name' => $this->name ), __METHOD__
474 );
475 if ( $this->fromSharedDirectory ) {
476 $dbw->selectDB( $wgDBname );
477 }
478 wfProfileOut( __METHOD__ );
479 }
480
481 /**
482 * Split an internet media type into its two components; if not
483 * a two-part name, set the minor type to 'unknown'.
484 *
485 * @param $mime "text/html" etc
486 * @return array ("text", "html") etc
487 */
488 static function splitMime( $mime ) {
489 if( strpos( $mime, '/' ) !== false ) {
490 return explode( '/', $mime, 2 );
491 } else {
492 return array( $mime, 'unknown' );
493 }
494 }
495
496 /**
497 * Return the name of this image
498 * @public
499 */
500 function getName() {
501 return $this->name;
502 }
503
504 /**
505 * Return the associated title object
506 * @public
507 */
508 function getTitle() {
509 return $this->title;
510 }
511
512 /**
513 * Return the URL of the image file
514 * @public
515 */
516 function getURL() {
517 if ( !$this->url ) {
518 $this->load();
519 if($this->fileExists) {
520 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
521 } else {
522 $this->url = '';
523 }
524 }
525 return $this->url;
526 }
527
528 function getViewURL() {
529 if( $this->mustRender()) {
530 if( $this->canRender() ) {
531 return $this->createThumb( $this->getWidth() );
532 }
533 else {
534 wfDebug('Image::getViewURL(): supposed to render '.$this->name.' ('.$this->mime."), but can't!\n");
535 return $this->getURL(); #hm... return NULL?
536 }
537 } else {
538 return $this->getURL();
539 }
540 }
541
542 /**
543 * Return the image path of the image in the
544 * local file system as an absolute path
545 * @public
546 */
547 function getImagePath() {
548 $this->load();
549 return $this->imagePath;
550 }
551
552 /**
553 * Return the width of the image
554 *
555 * Returns -1 if the file specified is not a known image type
556 * @public
557 */
558 function getWidth() {
559 $this->load();
560 return $this->width;
561 }
562
563 /**
564 * Return the height of the image
565 *
566 * Returns -1 if the file specified is not a known image type
567 * @public
568 */
569 function getHeight() {
570 $this->load();
571 return $this->height;
572 }
573
574 /**
575 * Return the size of the image file, in bytes
576 * @public
577 */
578 function getSize() {
579 $this->load();
580 return $this->size;
581 }
582
583 /**
584 * Returns the mime type of the file.
585 */
586 function getMimeType() {
587 $this->load();
588 return $this->mime;
589 }
590
591 /**
592 * Return the type of the media in the file.
593 * Use the value returned by this function with the MEDIATYPE_xxx constants.
594 */
595 function getMediaType() {
596 $this->load();
597 return $this->type;
598 }
599
600 /**
601 * Checks if the file can be presented to the browser as a bitmap.
602 *
603 * Currently, this checks if the file is an image format
604 * that can be converted to a format
605 * supported by all browsers (namely GIF, PNG and JPEG),
606 * or if it is an SVG image and SVG conversion is enabled.
607 *
608 * @todo remember the result of this check.
609 */
610 function canRender() {
611 global $wgUseImageMagick, $wgDjvuRenderer;
612
613 if( $this->getWidth()<=0 || $this->getHeight()<=0 ) return false;
614
615 $mime= $this->getMimeType();
616
617 if (!$mime || $mime==='unknown' || $mime==='unknown/unknown') return false;
618
619 #if it's SVG, check if there's a converter enabled
620 if ($mime === 'image/svg') {
621 global $wgSVGConverters, $wgSVGConverter;
622
623 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
624 wfDebug( "Image::canRender: SVG is ready!\n" );
625 return true;
626 } else {
627 wfDebug( "Image::canRender: SVG renderer missing\n" );
628 }
629 }
630
631 #image formats available on ALL browsers
632 if ( $mime === 'image/gif'
633 || $mime === 'image/png'
634 || $mime === 'image/jpeg' ) return true;
635
636 #image formats that can be converted to the above formats
637 if ($wgUseImageMagick) {
638 #convertable by ImageMagick (there are more...)
639 if ( $mime === 'image/vnd.wap.wbmp'
640 || $mime === 'image/x-xbitmap'
641 || $mime === 'image/x-xpixmap'
642 #|| $mime === 'image/x-icon' #file may be split into multiple parts
643 || $mime === 'image/x-portable-anymap'
644 || $mime === 'image/x-portable-bitmap'
645 || $mime === 'image/x-portable-graymap'
646 || $mime === 'image/x-portable-pixmap'
647 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
648 || $mime === 'image/x-rgb'
649 || $mime === 'image/x-bmp'
650 || $mime === 'image/tiff' ) return true;
651 }
652 else {
653 #convertable by the PHP GD image lib
654 if ( $mime === 'image/vnd.wap.wbmp'
655 || $mime === 'image/x-xbitmap' ) return true;
656 }
657 if ( $mime === 'image/vnd.djvu' && isset( $wgDjvuRenderer ) && $wgDjvuRenderer ) return true;
658
659 return false;
660 }
661
662
663 /**
664 * Return true if the file is of a type that can't be directly
665 * rendered by typical browsers and needs to be re-rasterized.
666 *
667 * This returns true for everything but the bitmap types
668 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
669 * also return true for any non-image formats.
670 *
671 * @return bool
672 */
673 function mustRender() {
674 $mime= $this->getMimeType();
675
676 if ( $mime === "image/gif"
677 || $mime === "image/png"
678 || $mime === "image/jpeg" ) return false;
679
680 return true;
681 }
682
683 /**
684 * Determines if this media file may be shown inline on a page.
685 *
686 * This is currently synonymous to canRender(), but this could be
687 * extended to also allow inline display of other media,
688 * like flash animations or videos. If you do so, please keep in mind that
689 * that could be a security risk.
690 */
691 function allowInlineDisplay() {
692 return $this->canRender();
693 }
694
695 /**
696 * Determines if this media file is in a format that is unlikely to
697 * contain viruses or malicious content. It uses the global
698 * $wgTrustedMediaFormats list to determine if the file is safe.
699 *
700 * This is used to show a warning on the description page of non-safe files.
701 * It may also be used to disallow direct [[media:...]] links to such files.
702 *
703 * Note that this function will always return true if allowInlineDisplay()
704 * or isTrustedFile() is true for this file.
705 */
706 function isSafeFile() {
707 if ($this->allowInlineDisplay()) return true;
708 if ($this->isTrustedFile()) return true;
709
710 global $wgTrustedMediaFormats;
711
712 $type= $this->getMediaType();
713 $mime= $this->getMimeType();
714 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
715
716 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
717 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
718
719 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
720 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
721
722 return false;
723 }
724
725 /** Returns true if the file is flagged as trusted. Files flagged that way
726 * can be linked to directly, even if that is not allowed for this type of
727 * file normally.
728 *
729 * This is a dummy function right now and always returns false. It could be
730 * implemented to extract a flag from the database. The trusted flag could be
731 * set on upload, if the user has sufficient privileges, to bypass script-
732 * and html-filters. It may even be coupled with cryptographics signatures
733 * or such.
734 */
735 function isTrustedFile() {
736 #this could be implemented to check a flag in the databas,
737 #look for signatures, etc
738 return false;
739 }
740
741 /**
742 * Return the escapeLocalURL of this image
743 * @public
744 */
745 function getEscapeLocalURL( $query=false) {
746 $this->getTitle();
747 if ( $query === false ) {
748 if ( $this->page != 1 ) {
749 $query = 'page=' . $this->page;
750 } else {
751 $query = '';
752 }
753 }
754 return $this->title->escapeLocalURL( $query );
755 }
756
757 /**
758 * Return the escapeFullURL of this image
759 * @public
760 */
761 function getEscapeFullURL() {
762 $this->getTitle();
763 return $this->title->escapeFullURL();
764 }
765
766 /**
767 * Return the URL of an image, provided its name.
768 *
769 * @param string $name Name of the image, without the leading "Image:"
770 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
771 * @return string URL of $name image
772 * @public
773 * @static
774 */
775 function imageUrl( $name, $fromSharedDirectory = false ) {
776 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
777 if($fromSharedDirectory) {
778 $base = '';
779 $path = $wgSharedUploadPath;
780 } else {
781 $base = $wgUploadBaseUrl;
782 $path = $wgUploadPath;
783 }
784 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
785 return wfUrlencode( $url );
786 }
787
788 /**
789 * Returns true if the image file exists on disk.
790 * @return boolean Whether image file exist on disk.
791 * @public
792 */
793 function exists() {
794 $this->load();
795 return $this->fileExists;
796 }
797
798 /**
799 * @todo document
800 * @private
801 */
802 function thumbUrl( $width, $subdir='thumb') {
803 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
804 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
805
806 // Generate thumb.php URL if possible
807 $script = false;
808 $url = false;
809
810 if ( $this->fromSharedDirectory ) {
811 if ( $wgSharedThumbnailScriptPath ) {
812 $script = $wgSharedThumbnailScriptPath;
813 }
814 } else {
815 if ( $wgThumbnailScriptPath ) {
816 $script = $wgThumbnailScriptPath;
817 }
818 }
819 if ( $script ) {
820 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
821 if( $this->mustRender() ) {
822 $url.= '&r=1';
823 }
824 } else {
825 $name = $this->thumbName( $width );
826 if($this->fromSharedDirectory) {
827 $base = '';
828 $path = $wgSharedUploadPath;
829 } else {
830 $base = $wgUploadBaseUrl;
831 $path = $wgUploadPath;
832 }
833 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
834 $url = "{$base}{$path}/{$subdir}" .
835 wfGetHashPath($this->name, $this->fromSharedDirectory)
836 . $this->name.'/'.$name;
837 $url = wfUrlencode( $url );
838 } else {
839 $url = "{$base}{$path}/{$subdir}/{$name}";
840 }
841 }
842 return array( $script !== false, $url );
843 }
844
845 /**
846 * Return the file name of a thumbnail of the specified width
847 *
848 * @param integer $width Width of the thumbnail image
849 * @param boolean $shared Does the thumbnail come from the shared repository?
850 * @private
851 */
852 function thumbName( $width ) {
853 $thumb = $width."px-".$this->name;
854 if ( $this->page != 1 ) {
855 $thumb = "page{$this->page}-$thumb";
856 }
857
858 if( $this->mustRender() ) {
859 if( $this->canRender() ) {
860 # Rasterize to PNG (for SVG vector images, etc)
861 $thumb .= '.png';
862 }
863 else {
864 #should we use iconThumb here to get a symbolic thumbnail?
865 #or should we fail with an internal error?
866 return NULL; //can't make bitmap
867 }
868 }
869 return $thumb;
870 }
871
872 /**
873 * Create a thumbnail of the image having the specified width/height.
874 * The thumbnail will not be created if the width is larger than the
875 * image's width. Let the browser do the scaling in this case.
876 * The thumbnail is stored on disk and is only computed if the thumbnail
877 * file does not exist OR if it is older than the image.
878 * Returns the URL.
879 *
880 * Keeps aspect ratio of original image. If both width and height are
881 * specified, the generated image will be no bigger than width x height,
882 * and will also have correct aspect ratio.
883 *
884 * @param integer $width maximum width of the generated thumbnail
885 * @param integer $height maximum height of the image (optional)
886 * @public
887 */
888 function createThumb( $width, $height=-1 ) {
889 $thumb = $this->getThumbnail( $width, $height );
890 if( is_null( $thumb ) ) return '';
891 return $thumb->getUrl();
892 }
893
894 /**
895 * As createThumb, but returns a ThumbnailImage object. This can
896 * provide access to the actual file, the real size of the thumb,
897 * and can produce a convenient <img> tag for you.
898 *
899 * For non-image formats, this may return a filetype-specific icon.
900 *
901 * @param integer $width maximum width of the generated thumbnail
902 * @param integer $height maximum height of the image (optional)
903 * @param boolean $render True to render the thumbnail if it doesn't exist,
904 * false to just return the URL
905 *
906 * @return ThumbnailImage or null on failure
907 * @public
908 */
909 function getThumbnail( $width, $height=-1, $render = true ) {
910 wfProfileIn( __METHOD__ );
911 if ($this->canRender()) {
912 if ( $height > 0 ) {
913 $this->load();
914 if ( $width > $this->width * $height / $this->height ) {
915 $width = wfFitBoxWidth( $this->width, $this->height, $height );
916 }
917 }
918 if ( $render ) {
919 $thumb = $this->renderThumb( $width );
920 } else {
921 // Don't render, just return the URL
922 if ( $this->validateThumbParams( $width, $height ) ) {
923 if ( !$this->mustRender() && $width == $this->width && $height == $this->height ) {
924 $url = $this->getURL();
925 } else {
926 list( /* $isScriptUrl */, $url ) = $this->thumbUrl( $width );
927 }
928 $thumb = new ThumbnailImage( $url, $width, $height );
929 } else {
930 $thumb = null;
931 }
932 }
933 } else {
934 // not a bitmap or renderable image, don't try.
935 $thumb = $this->iconThumb();
936 }
937 wfProfileOut( __METHOD__ );
938 return $thumb;
939 }
940
941 /**
942 * @return ThumbnailImage
943 */
944 function iconThumb() {
945 global $wgStylePath, $wgStyleDirectory;
946
947 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
948 foreach( $try as $icon ) {
949 $path = '/common/images/icons/' . $icon;
950 $filepath = $wgStyleDirectory . $path;
951 if( file_exists( $filepath ) ) {
952 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
953 }
954 }
955 return null;
956 }
957
958 /**
959 * Validate thumbnail parameters and fill in the correct height
960 *
961 * @param integer &$width Specified width (input/output)
962 * @param integer &$height Height (output only)
963 * @return false to indicate that an error should be returned to the user.
964 */
965 function validateThumbParams( &$width, &$height ) {
966 global $wgSVGMaxSize, $wgMaxImageArea;
967
968 $this->load();
969
970 if ( ! $this->exists() )
971 {
972 # If there is no image, there will be no thumbnail
973 return false;
974 }
975
976 $width = intval( $width );
977
978 # Sanity check $width
979 if( $width <= 0 || $this->width <= 0) {
980 # BZZZT
981 return false;
982 }
983
984 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
985 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
986 # an exception for it.
987 if ( $this->getMediaType() == MEDIATYPE_BITMAP &&
988 $this->getMimeType() !== 'image/jpeg' &&
989 $this->width * $this->height > $wgMaxImageArea )
990 {
991 return false;
992 }
993
994 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
995 if ( $this->mustRender() ) {
996 $width = min( $width, $wgSVGMaxSize );
997 } elseif ( $width > $this->width - 1 ) {
998 $width = $this->width;
999 $height = $this->height;
1000 return true;
1001 }
1002
1003 $height = round( $this->height * $width / $this->width );
1004 return true;
1005 }
1006
1007 /**
1008 * Create a thumbnail of the image having the specified width.
1009 * The thumbnail will not be created if the width is larger than the
1010 * image's width. Let the browser do the scaling in this case.
1011 * The thumbnail is stored on disk and is only computed if the thumbnail
1012 * file does not exist OR if it is older than the image.
1013 * Returns an object which can return the pathname, URL, and physical
1014 * pixel size of the thumbnail -- or null on failure.
1015 *
1016 * @return ThumbnailImage or null on failure
1017 * @private
1018 */
1019 function renderThumb( $width, $useScript = true ) {
1020 global $wgUseSquid, $wgThumbnailEpoch;
1021
1022 wfProfileIn( __METHOD__ );
1023
1024 $this->load();
1025 $height = -1;
1026 if ( !$this->validateThumbParams( $width, $height ) ) {
1027 # Validation error
1028 wfProfileOut( __METHOD__ );
1029 return null;
1030 }
1031
1032 if ( !$this->mustRender() && $width == $this->width && $height == $this->height ) {
1033 # validateThumbParams (or the user) wants us to return the unscaled image
1034 $thumb = new ThumbnailImage( $this->getURL(), $width, $height );
1035 wfProfileOut( __METHOD__ );
1036 return $thumb;
1037 }
1038
1039 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
1040 if ( $isScriptUrl && $useScript ) {
1041 // Use thumb.php to render the image
1042 $thumb = new ThumbnailImage( $url, $width, $height );
1043 wfProfileOut( __METHOD__ );
1044 return $thumb;
1045 }
1046
1047 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
1048 $thumbDir = wfImageThumbDir( $this->name, $this->fromSharedDirectory );
1049 $thumbPath = $thumbDir.'/'.$thumbName;
1050
1051 if ( is_dir( $thumbPath ) ) {
1052 // Directory where file should be
1053 // This happened occasionally due to broken migration code in 1.5
1054 // Rename to broken-*
1055 global $wgUploadDirectory;
1056 for ( $i = 0; $i < 100 ; $i++ ) {
1057 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1058 if ( !file_exists( $broken ) ) {
1059 rename( $thumbPath, $broken );
1060 break;
1061 }
1062 }
1063 // Code below will ask if it exists, and the answer is now no
1064 clearstatcache();
1065 }
1066
1067 $done = true;
1068 if ( !file_exists( $thumbPath ) ||
1069 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX, $wgThumbnailEpoch ) )
1070 {
1071 // Create the directory if it doesn't exist
1072 if ( is_file( $thumbDir ) ) {
1073 // File where thumb directory should be, destroy if possible
1074 @unlink( $thumbDir );
1075 }
1076 wfMkdirParents( $thumbDir );
1077
1078 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
1079 '/'.$thumbName;
1080 $done = false;
1081
1082 // Migration from old directory structure
1083 if ( is_file( $oldThumbPath ) ) {
1084 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
1085 if ( file_exists( $thumbPath ) ) {
1086 if ( !is_dir( $thumbPath ) ) {
1087 // Old image in the way of rename
1088 unlink( $thumbPath );
1089 } else {
1090 // This should have been dealt with already
1091 throw new MWException( "Directory where image should be: $thumbPath" );
1092 }
1093 }
1094 // Rename the old image into the new location
1095 rename( $oldThumbPath, $thumbPath );
1096 $done = true;
1097 } else {
1098 unlink( $oldThumbPath );
1099 }
1100 }
1101 if ( !$done ) {
1102 $this->lastError = $this->reallyRenderThumb( $thumbPath, $width, $height );
1103 if ( $this->lastError === true ) {
1104 $done = true;
1105 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1106 // Log the error but output anyway.
1107 // With luck it's a transitory error...
1108 $done = true;
1109 }
1110
1111 # Purge squid
1112 # This has to be done after the image is updated and present for all machines on NFS,
1113 # or else the old version might be stored into the squid again
1114 if ( $wgUseSquid ) {
1115 $urlArr = array( $url );
1116 wfPurgeSquidServers($urlArr);
1117 }
1118 }
1119 }
1120
1121 if ( $done ) {
1122 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1123 } else {
1124 $thumb = null;
1125 }
1126 wfProfileOut( __METHOD__ );
1127 return $thumb;
1128 } // END OF function renderThumb
1129
1130 /**
1131 * Really render a thumbnail
1132 * Call this only for images for which canRender() returns true.
1133 *
1134 * @param string $thumbPath Path to thumbnail
1135 * @param int $width Desired width in pixels
1136 * @param int $height Desired height in pixels
1137 * @return bool True on error, false or error string on failure.
1138 * @private
1139 */
1140 function reallyRenderThumb( $thumbPath, $width, $height ) {
1141 global $wgSVGConverters, $wgSVGConverter;
1142 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1143 global $wgCustomConvertCommand;
1144 global $wgDjvuRenderer, $wgDjvuPostProcessor;
1145
1146 $this->load();
1147
1148 $err = false;
1149 $cmd = "";
1150 $retval = 0;
1151
1152 if( $this->mime === "image/svg" ) {
1153 #Right now we have only SVG
1154
1155 global $wgSVGConverters, $wgSVGConverter;
1156 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1157 global $wgSVGConverterPath;
1158 $cmd = str_replace(
1159 array( '$path/', '$width', '$height', '$input', '$output' ),
1160 array( $wgSVGConverterPath ? "$wgSVGConverterPath/" : "",
1161 intval( $width ),
1162 intval( $height ),
1163 wfEscapeShellArg( $this->imagePath ),
1164 wfEscapeShellArg( $thumbPath ) ),
1165 $wgSVGConverters[$wgSVGConverter] );
1166 wfProfileIn( 'rsvg' );
1167 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1168 $err = wfShellExec( $cmd, $retval );
1169 wfProfileOut( 'rsvg' );
1170 }
1171 } else {
1172 if ( $this->mime === "image/vnd.djvu" && $wgDjvuRenderer ) {
1173 // DJVU image
1174 // The file contains several images. First, extract the
1175 // page in hi-res, if it doesn't yet exist. Then, thumbnail
1176 // it.
1177
1178 $cmd = "{$wgDjvuRenderer} -page={$this->page} -size=${width}x${height} " .
1179 wfEscapeShellArg( $this->imagePath ) .
1180 " | {$wgDjvuPostProcessor} > " . wfEscapeShellArg($thumbPath);
1181 wfProfileIn( 'ddjvu' );
1182 wfDebug( "reallyRenderThumb DJVU: $cmd\n" );
1183 $err = wfShellExec( $cmd, $retval );
1184 wfProfileOut( 'ddjvu' );
1185
1186 } elseif ( $wgUseImageMagick ) {
1187 # use ImageMagick
1188
1189 if ( $this->mime == 'image/jpeg' ) {
1190 $quality = "-quality 80"; // 80%
1191 } elseif ( $this->mime == 'image/png' ) {
1192 $quality = "-quality 95"; // zlib 9, adaptive filtering
1193 } else {
1194 $quality = ''; // default
1195 }
1196
1197 # Specify white background color, will be used for transparent images
1198 # in Internet Explorer/Windows instead of default black.
1199
1200 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1201 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1202 # the wrong size in the second case.
1203
1204 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1205 " {$quality} -background white -size {$width} ".
1206 wfEscapeShellArg($this->imagePath) .
1207 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1208 ' -coalesce ' .
1209 // For the -resize option a "!" is needed to force exact size,
1210 // or ImageMagick may decide your ratio is wrong and slice off
1211 // a pixel.
1212 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1213 " -depth 8 " .
1214 wfEscapeShellArg($thumbPath) . " 2>&1";
1215 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1216 wfProfileIn( 'convert' );
1217 $err = wfShellExec( $cmd, $retval );
1218 wfProfileOut( 'convert' );
1219 } elseif( $wgCustomConvertCommand ) {
1220 # Use a custom convert command
1221 # Variables: %s %d %w %h
1222 $src = wfEscapeShellArg( $this->imagePath );
1223 $dst = wfEscapeShellArg( $thumbPath );
1224 $cmd = $wgCustomConvertCommand;
1225 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1226 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1227 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1228 wfProfileIn( 'convert' );
1229 $err = wfShellExec( $cmd, $retval );
1230 wfProfileOut( 'convert' );
1231 } else {
1232 # Use PHP's builtin GD library functions.
1233 #
1234 # First find out what kind of file this is, and select the correct
1235 # input routine for this.
1236
1237 $typemap = array(
1238 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1239 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1240 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1241 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1242 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1243 );
1244 if( !isset( $typemap[$this->mime] ) ) {
1245 $err = 'Image type not supported';
1246 wfDebug( "$err\n" );
1247 return $err;
1248 }
1249 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime];
1250
1251 if( !function_exists( $loader ) ) {
1252 $err = "Incomplete GD library configuration: missing function $loader";
1253 wfDebug( "$err\n" );
1254 return $err;
1255 }
1256 if( $colorStyle == 'palette' ) {
1257 $truecolor = false;
1258 } elseif( $colorStyle == 'truecolor' ) {
1259 $truecolor = true;
1260 } elseif( $colorStyle == 'bits' ) {
1261 $truecolor = ( $this->bits > 8 );
1262 }
1263
1264 $src_image = call_user_func( $loader, $this->imagePath );
1265 if ( $truecolor ) {
1266 $dst_image = imagecreatetruecolor( $width, $height );
1267 } else {
1268 $dst_image = imagecreate( $width, $height );
1269 }
1270 imagecopyresampled( $dst_image, $src_image,
1271 0,0,0,0,
1272 $width, $height, $this->width, $this->height );
1273 call_user_func( $saveType, $dst_image, $thumbPath );
1274 imagedestroy( $dst_image );
1275 imagedestroy( $src_image );
1276 }
1277 }
1278
1279 #
1280 # Check for zero-sized thumbnails. Those can be generated when
1281 # no disk space is available or some other error occurs
1282 #
1283 if( file_exists( $thumbPath ) ) {
1284 $thumbstat = stat( $thumbPath );
1285 if( $thumbstat['size'] == 0 || $retval != 0 ) {
1286 wfDebugLog( 'thumbnail',
1287 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1288 $thumbstat['size'], $thumbPath ) );
1289 unlink( $thumbPath );
1290 }
1291 }
1292 if ( $retval != 0 ) {
1293 wfDebugLog( 'thumbnail',
1294 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1295 wfHostname(), $retval, trim($err), $cmd ) );
1296 return wfMsg( 'thumbnail_error', $err );
1297 } else {
1298 return true;
1299 }
1300 }
1301
1302 function getLastError() {
1303 return $this->lastError;
1304 }
1305
1306 function imageJpegWrapper( $dst_image, $thumbPath ) {
1307 imageinterlace( $dst_image );
1308 imagejpeg( $dst_image, $thumbPath, 95 );
1309 }
1310
1311 /**
1312 * Get all thumbnail names previously generated for this image
1313 */
1314 function getThumbnails( $shared = false ) {
1315 if ( Image::isHashed( $shared ) ) {
1316 $this->load();
1317 $files = array();
1318 $dir = wfImageThumbDir( $this->name, $shared );
1319
1320 // This generates an error on failure, hence the @
1321 $handle = @opendir( $dir );
1322
1323 if ( $handle ) {
1324 while ( false !== ( $file = readdir($handle) ) ) {
1325 if ( $file{0} != '.' ) {
1326 $files[] = $file;
1327 }
1328 }
1329 closedir( $handle );
1330 }
1331 } else {
1332 $files = array();
1333 }
1334
1335 return $files;
1336 }
1337
1338 /**
1339 * Refresh metadata in memcached, but don't touch thumbnails or squid
1340 */
1341 function purgeMetadataCache() {
1342 clearstatcache();
1343 $this->loadFromFile();
1344 $this->saveToCache();
1345 }
1346
1347 /**
1348 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1349 */
1350 function purgeCache( $archiveFiles = array(), $shared = false ) {
1351 global $wgUseSquid;
1352
1353 // Refresh metadata cache
1354 $this->purgeMetadataCache();
1355
1356 // Delete thumbnails
1357 $files = $this->getThumbnails( $shared );
1358 $dir = wfImageThumbDir( $this->name, $shared );
1359 $urls = array();
1360 foreach ( $files as $file ) {
1361 $m = array();
1362 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1363 list( /* $isScriptUrl */, $url ) = $this->thumbUrl( $m[1] );
1364 $urls[] = $url;
1365 @unlink( "$dir/$file" );
1366 }
1367 }
1368
1369 // Purge the squid
1370 if ( $wgUseSquid ) {
1371 $urls[] = $this->getURL();
1372 foreach ( $archiveFiles as $file ) {
1373 $urls[] = wfImageArchiveUrl( $file );
1374 }
1375 wfPurgeSquidServers( $urls );
1376 }
1377 }
1378
1379 /**
1380 * Purge the image description page, but don't go after
1381 * pages using the image. Use when modifying file history
1382 * but not the current data.
1383 */
1384 function purgeDescription() {
1385 $page = Title::makeTitle( NS_IMAGE, $this->name );
1386 $page->invalidateCache();
1387 $page->purgeSquid();
1388 }
1389
1390 /**
1391 * Purge metadata and all affected pages when the image is created,
1392 * deleted, or majorly updated. A set of additional URLs may be
1393 * passed to purge, such as specific image files which have changed.
1394 * @param $urlArray array
1395 */
1396 function purgeEverything( $urlArr=array() ) {
1397 // Delete thumbnails and refresh image metadata cache
1398 $this->purgeCache();
1399 $this->purgeDescription();
1400
1401 // Purge cache of all pages using this image
1402 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1403 $update->doUpdate();
1404 }
1405
1406 function checkDBSchema(&$db) {
1407 static $checkDone = false;
1408 global $wgCheckDBSchema;
1409 if (!$wgCheckDBSchema || $checkDone) {
1410 return;
1411 }
1412 # img_name must be unique
1413 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1414 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1415 }
1416 $checkDone = true;
1417
1418 # new fields must exist
1419 #
1420 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1421 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1422 # something. The only reason I put the above schema check in was because the absence of that particular
1423 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1424 # uploads. -- TS
1425 /*
1426 if ( !$db->fieldExists( 'image', 'img_media_type' )
1427 || !$db->fieldExists( 'image', 'img_metadata' )
1428 || !$db->fieldExists( 'image', 'img_width' ) ) {
1429
1430 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1431 }
1432 */
1433 }
1434
1435 /**
1436 * Return the image history of this image, line by line.
1437 * starts with current version, then old versions.
1438 * uses $this->historyLine to check which line to return:
1439 * 0 return line for current version
1440 * 1 query for old versions, return first one
1441 * 2, ... return next old version from above query
1442 *
1443 * @public
1444 */
1445 function nextHistoryLine() {
1446 $dbr = wfGetDB( DB_SLAVE );
1447
1448 $this->checkDBSchema($dbr);
1449
1450 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1451 $this->historyRes = $dbr->select( 'image',
1452 array(
1453 'img_size',
1454 'img_description',
1455 'img_user','img_user_text',
1456 'img_timestamp',
1457 'img_width',
1458 'img_height',
1459 "'' AS oi_archive_name"
1460 ),
1461 array( 'img_name' => $this->title->getDBkey() ),
1462 __METHOD__
1463 );
1464 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1465 return FALSE;
1466 }
1467 } else if ( $this->historyLine == 1 ) {
1468 $this->historyRes = $dbr->select( 'oldimage',
1469 array(
1470 'oi_size AS img_size',
1471 'oi_description AS img_description',
1472 'oi_user AS img_user',
1473 'oi_user_text AS img_user_text',
1474 'oi_timestamp AS img_timestamp',
1475 'oi_width as img_width',
1476 'oi_height as img_height',
1477 'oi_archive_name'
1478 ),
1479 array( 'oi_name' => $this->title->getDBkey() ),
1480 __METHOD__,
1481 array( 'ORDER BY' => 'oi_timestamp DESC' )
1482 );
1483 }
1484 $this->historyLine ++;
1485
1486 return $dbr->fetchObject( $this->historyRes );
1487 }
1488
1489 /**
1490 * Reset the history pointer to the first element of the history
1491 * @public
1492 */
1493 function resetHistory() {
1494 $this->historyLine = 0;
1495 }
1496
1497 /**
1498 * Return the full filesystem path to the file. Note that this does
1499 * not mean that a file actually exists under that location.
1500 *
1501 * This path depends on whether directory hashing is active or not,
1502 * i.e. whether the images are all found in the same directory,
1503 * or in hashed paths like /images/3/3c.
1504 *
1505 * @public
1506 * @param boolean $fromSharedDirectory Return the path to the file
1507 * in a shared repository (see $wgUseSharedRepository and related
1508 * options in DefaultSettings.php) instead of a local one.
1509 *
1510 */
1511 function getFullPath( $fromSharedRepository = false ) {
1512 global $wgUploadDirectory, $wgSharedUploadDirectory;
1513
1514 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1515 $wgUploadDirectory;
1516
1517 // $wgSharedUploadDirectory may be false, if thumb.php is used
1518 if ( $dir ) {
1519 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1520 } else {
1521 $fullpath = false;
1522 }
1523
1524 return $fullpath;
1525 }
1526
1527 /**
1528 * @return bool
1529 * @static
1530 */
1531 public static function isHashed( $shared ) {
1532 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1533 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1534 }
1535
1536 /**
1537 * Record an image upload in the upload log and the image table
1538 */
1539 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1540 global $wgUser, $wgUseCopyrightUpload;
1541
1542 $dbw = wfGetDB( DB_MASTER );
1543
1544 $this->checkDBSchema($dbw);
1545
1546 // Delete thumbnails and refresh the metadata cache
1547 $this->purgeCache();
1548
1549 // Fail now if the image isn't there
1550 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1551 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1552 return false;
1553 }
1554
1555 if ( $wgUseCopyrightUpload ) {
1556 if ( $license != '' ) {
1557 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1558 }
1559 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1560 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1561 "$licensetxt" .
1562 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1563 } else {
1564 if ( $license != '' ) {
1565 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1566 $textdesc = $filedesc .
1567 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1568 } else {
1569 $textdesc = $desc;
1570 }
1571 }
1572
1573 $now = $dbw->timestamp();
1574
1575 #split mime type
1576 if (strpos($this->mime,'/')!==false) {
1577 list($major,$minor)= explode('/',$this->mime,2);
1578 }
1579 else {
1580 $major= $this->mime;
1581 $minor= "unknown";
1582 }
1583
1584 # Test to see if the row exists using INSERT IGNORE
1585 # This avoids race conditions by locking the row until the commit, and also
1586 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1587 $dbw->insert( 'image',
1588 array(
1589 'img_name' => $this->name,
1590 'img_size'=> $this->size,
1591 'img_width' => intval( $this->width ),
1592 'img_height' => intval( $this->height ),
1593 'img_bits' => $this->bits,
1594 'img_media_type' => $this->type,
1595 'img_major_mime' => $major,
1596 'img_minor_mime' => $minor,
1597 'img_timestamp' => $now,
1598 'img_description' => $desc,
1599 'img_user' => $wgUser->getID(),
1600 'img_user_text' => $wgUser->getName(),
1601 'img_metadata' => $this->metadata,
1602 ),
1603 __METHOD__,
1604 'IGNORE'
1605 );
1606
1607 if( $dbw->affectedRows() == 0 ) {
1608 # Collision, this is an update of an image
1609 # Insert previous contents into oldimage
1610 $dbw->insertSelect( 'oldimage', 'image',
1611 array(
1612 'oi_name' => 'img_name',
1613 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1614 'oi_size' => 'img_size',
1615 'oi_width' => 'img_width',
1616 'oi_height' => 'img_height',
1617 'oi_bits' => 'img_bits',
1618 'oi_timestamp' => 'img_timestamp',
1619 'oi_description' => 'img_description',
1620 'oi_user' => 'img_user',
1621 'oi_user_text' => 'img_user_text',
1622 ), array( 'img_name' => $this->name ), __METHOD__
1623 );
1624
1625 # Update the current image row
1626 $dbw->update( 'image',
1627 array( /* SET */
1628 'img_size' => $this->size,
1629 'img_width' => intval( $this->width ),
1630 'img_height' => intval( $this->height ),
1631 'img_bits' => $this->bits,
1632 'img_media_type' => $this->type,
1633 'img_major_mime' => $major,
1634 'img_minor_mime' => $minor,
1635 'img_timestamp' => $now,
1636 'img_description' => $desc,
1637 'img_user' => $wgUser->getID(),
1638 'img_user_text' => $wgUser->getName(),
1639 'img_metadata' => $this->metadata,
1640 ), array( /* WHERE */
1641 'img_name' => $this->name
1642 ), __METHOD__
1643 );
1644 } else {
1645 # This is a new image
1646 # Update the image count
1647 $site_stats = $dbw->tableName( 'site_stats' );
1648 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1649 }
1650
1651 $descTitle = $this->getTitle();
1652 $article = new Article( $descTitle );
1653 $minor = false;
1654 $watch = $watch || $wgUser->isWatched( $descTitle );
1655 $suppressRC = true; // There's already a log entry, so don't double the RC load
1656
1657 if( $descTitle->exists() ) {
1658 // TODO: insert a null revision into the page history for this update.
1659 if( $watch ) {
1660 $wgUser->addWatch( $descTitle );
1661 }
1662
1663 # Invalidate the cache for the description page
1664 $descTitle->invalidateCache();
1665 $descTitle->purgeSquid();
1666 } else {
1667 // New image; create the description page.
1668 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1669 }
1670
1671 # Add the log entry
1672 $log = new LogPage( 'upload' );
1673 $log->addEntry( 'upload', $descTitle, $desc );
1674
1675 # Commit the transaction now, in case something goes wrong later
1676 # The most important thing is that images don't get lost, especially archives
1677 $dbw->immediateCommit();
1678
1679 # Invalidate cache for all pages using this image
1680 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1681 $update->doUpdate();
1682
1683 return true;
1684 }
1685
1686 /**
1687 * Get an array of Title objects which are articles which use this image
1688 * Also adds their IDs to the link cache
1689 *
1690 * This is mostly copied from Title::getLinksTo()
1691 *
1692 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1693 */
1694 function getLinksTo( $options = '' ) {
1695 wfProfileIn( __METHOD__ );
1696
1697 if ( $options ) {
1698 $db = wfGetDB( DB_MASTER );
1699 } else {
1700 $db = wfGetDB( DB_SLAVE );
1701 }
1702 $linkCache =& LinkCache::singleton();
1703
1704 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1705 $encName = $db->addQuotes( $this->name );
1706 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1707 $res = $db->query( $sql, __METHOD__ );
1708
1709 $retVal = array();
1710 if ( $db->numRows( $res ) ) {
1711 while ( $row = $db->fetchObject( $res ) ) {
1712 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1713 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1714 $retVal[] = $titleObj;
1715 }
1716 }
1717 }
1718 $db->freeResult( $res );
1719 wfProfileOut( __METHOD__ );
1720 return $retVal;
1721 }
1722
1723 /**
1724 * Retrive Exif data from the file and prune unrecognized tags
1725 * and/or tags with invalid contents
1726 *
1727 * @param $filename
1728 * @return array
1729 */
1730 private function retrieveExifData( $filename ) {
1731 global $wgShowEXIF;
1732
1733 /*
1734 if ( $this->getMimeType() !== "image/jpeg" )
1735 return array();
1736 */
1737
1738 if( $wgShowEXIF && file_exists( $filename ) ) {
1739 $exif = new Exif( $filename );
1740 return $exif->getFilteredData();
1741 }
1742
1743 return array();
1744 }
1745
1746 function getExifData() {
1747 global $wgRequest;
1748 if ( $this->metadata === '0' || $this->mime == 'image/vnd.djvu' )
1749 return array();
1750
1751 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1752 $ret = unserialize( $this->metadata );
1753
1754 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1755 $newver = Exif::version();
1756
1757 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1758 $this->purgeMetadataCache();
1759 $this->updateExifData( $newver );
1760 }
1761 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1762 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1763 $format = new FormatExif( $ret );
1764
1765 return $format->getFormattedData();
1766 }
1767
1768 function updateExifData( $version ) {
1769 if ( $this->getImagePath() === false ) # Not a local image
1770 return;
1771
1772 # Get EXIF data from image
1773 $exif = $this->retrieveExifData( $this->imagePath );
1774 if ( count( $exif ) ) {
1775 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1776 $this->metadata = serialize( $exif );
1777 } else {
1778 $this->metadata = '0';
1779 }
1780
1781 # Update EXIF data in database
1782 $dbw = wfGetDB( DB_MASTER );
1783
1784 $this->checkDBSchema($dbw);
1785
1786 $dbw->update( 'image',
1787 array( 'img_metadata' => $this->metadata ),
1788 array( 'img_name' => $this->name ),
1789 __METHOD__
1790 );
1791 }
1792
1793 /**
1794 * Returns true if the image does not come from the shared
1795 * image repository.
1796 *
1797 * @return bool
1798 */
1799 function isLocal() {
1800 return !$this->fromSharedDirectory;
1801 }
1802
1803 /**
1804 * Was this image ever deleted from the wiki?
1805 *
1806 * @return bool
1807 */
1808 function wasDeleted() {
1809 $title = Title::makeTitle( NS_IMAGE, $this->name );
1810 return ( $title->isDeleted() > 0 );
1811 }
1812
1813 /**
1814 * Delete all versions of the image.
1815 *
1816 * Moves the files into an archive directory (or deletes them)
1817 * and removes the database rows.
1818 *
1819 * Cache purging is done; logging is caller's responsibility.
1820 *
1821 * @param $reason
1822 * @return true on success, false on some kind of failure
1823 */
1824 function delete( $reason ) {
1825 $transaction = new FSTransaction();
1826 $urlArr = array( $this->getURL() );
1827
1828 if( !FileStore::lock() ) {
1829 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1830 return false;
1831 }
1832
1833 try {
1834 $dbw = wfGetDB( DB_MASTER );
1835 $dbw->begin();
1836
1837 // Delete old versions
1838 $result = $dbw->select( 'oldimage',
1839 array( 'oi_archive_name' ),
1840 array( 'oi_name' => $this->name ) );
1841
1842 while( $row = $dbw->fetchObject( $result ) ) {
1843 $oldName = $row->oi_archive_name;
1844
1845 $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
1846
1847 // We'll need to purge this URL from caches...
1848 $urlArr[] = wfImageArchiveUrl( $oldName );
1849 }
1850 $dbw->freeResult( $result );
1851
1852 // And the current version...
1853 $transaction->add( $this->prepareDeleteCurrent( $reason ) );
1854
1855 $dbw->immediateCommit();
1856 } catch( MWException $e ) {
1857 wfDebug( __METHOD__.": db error, rolling back file transactions\n" );
1858 $transaction->rollback();
1859 FileStore::unlock();
1860 throw $e;
1861 }
1862
1863 wfDebug( __METHOD__.": deleted db items, applying file transactions\n" );
1864 $transaction->commit();
1865 FileStore::unlock();
1866
1867
1868 // Update site_stats
1869 $site_stats = $dbw->tableName( 'site_stats' );
1870 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1871
1872 $this->purgeEverything( $urlArr );
1873
1874 return true;
1875 }
1876
1877
1878 /**
1879 * Delete an old version of the image.
1880 *
1881 * Moves the file into an archive directory (or deletes it)
1882 * and removes the database row.
1883 *
1884 * Cache purging is done; logging is caller's responsibility.
1885 *
1886 * @param $reason
1887 * @throws MWException or FSException on database or filestore failure
1888 * @return true on success, false on some kind of failure
1889 */
1890 function deleteOld( $archiveName, $reason ) {
1891 $transaction = new FSTransaction();
1892 $urlArr = array();
1893
1894 if( !FileStore::lock() ) {
1895 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1896 return false;
1897 }
1898
1899 $transaction = new FSTransaction();
1900 try {
1901 $dbw = wfGetDB( DB_MASTER );
1902 $dbw->begin();
1903 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
1904 $dbw->immediateCommit();
1905 } catch( MWException $e ) {
1906 wfDebug( __METHOD__.": db error, rolling back file transaction\n" );
1907 $transaction->rollback();
1908 FileStore::unlock();
1909 throw $e;
1910 }
1911
1912 wfDebug( __METHOD__.": deleted db items, applying file transaction\n" );
1913 $transaction->commit();
1914 FileStore::unlock();
1915
1916 $this->purgeDescription();
1917
1918 // Squid purging
1919 global $wgUseSquid;
1920 if ( $wgUseSquid ) {
1921 $urlArr = array(
1922 wfImageArchiveUrl( $archiveName ),
1923 );
1924 wfPurgeSquidServers( $urlArr );
1925 }
1926 return true;
1927 }
1928
1929 /**
1930 * Delete the current version of a file.
1931 * May throw a database error.
1932 * @return true on success, false on failure
1933 */
1934 private function prepareDeleteCurrent( $reason ) {
1935 return $this->prepareDeleteVersion(
1936 $this->getFullPath(),
1937 $reason,
1938 'image',
1939 array(
1940 'fa_name' => 'img_name',
1941 'fa_archive_name' => 'NULL',
1942 'fa_size' => 'img_size',
1943 'fa_width' => 'img_width',
1944 'fa_height' => 'img_height',
1945 'fa_metadata' => 'img_metadata',
1946 'fa_bits' => 'img_bits',
1947 'fa_media_type' => 'img_media_type',
1948 'fa_major_mime' => 'img_major_mime',
1949 'fa_minor_mime' => 'img_minor_mime',
1950 'fa_description' => 'img_description',
1951 'fa_user' => 'img_user',
1952 'fa_user_text' => 'img_user_text',
1953 'fa_timestamp' => 'img_timestamp' ),
1954 array( 'img_name' => $this->name ),
1955 __METHOD__ );
1956 }
1957
1958 /**
1959 * Delete a given older version of a file.
1960 * May throw a database error.
1961 * @return true on success, false on failure
1962 */
1963 private function prepareDeleteOld( $archiveName, $reason ) {
1964 $oldpath = wfImageArchiveDir( $this->name ) .
1965 DIRECTORY_SEPARATOR . $archiveName;
1966 return $this->prepareDeleteVersion(
1967 $oldpath,
1968 $reason,
1969 'oldimage',
1970 array(
1971 'fa_name' => 'oi_name',
1972 'fa_archive_name' => 'oi_archive_name',
1973 'fa_size' => 'oi_size',
1974 'fa_width' => 'oi_width',
1975 'fa_height' => 'oi_height',
1976 'fa_metadata' => 'NULL',
1977 'fa_bits' => 'oi_bits',
1978 'fa_media_type' => 'NULL',
1979 'fa_major_mime' => 'NULL',
1980 'fa_minor_mime' => 'NULL',
1981 'fa_description' => 'oi_description',
1982 'fa_user' => 'oi_user',
1983 'fa_user_text' => 'oi_user_text',
1984 'fa_timestamp' => 'oi_timestamp' ),
1985 array(
1986 'oi_name' => $this->name,
1987 'oi_archive_name' => $archiveName ),
1988 __METHOD__ );
1989 }
1990
1991 /**
1992 * Do the dirty work of backing up an image row and its file
1993 * (if $wgSaveDeletedFiles is on) and removing the originals.
1994 *
1995 * Must be run while the file store is locked and a database
1996 * transaction is open to avoid race conditions.
1997 *
1998 * @return FSTransaction
1999 */
2000 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
2001 global $wgUser, $wgSaveDeletedFiles;
2002
2003 // Dupe the file into the file store
2004 if( file_exists( $path ) ) {
2005 if( $wgSaveDeletedFiles ) {
2006 $group = 'deleted';
2007
2008 $store = FileStore::get( $group );
2009 $key = FileStore::calculateKey( $path, $this->extension );
2010 $transaction = $store->insert( $key, $path,
2011 FileStore::DELETE_ORIGINAL );
2012 } else {
2013 $group = null;
2014 $key = null;
2015 $transaction = FileStore::deleteFile( $path );
2016 }
2017 } else {
2018 wfDebug( __METHOD__." deleting already-missing '$path'; moving on to database\n" );
2019 $group = null;
2020 $key = null;
2021 $transaction = new FSTransaction(); // empty
2022 }
2023
2024 if( $transaction === false ) {
2025 // Fail to restore?
2026 wfDebug( __METHOD__.": import to file store failed, aborting\n" );
2027 throw new MWException( "Could not archive and delete file $path" );
2028 return false;
2029 }
2030
2031 $dbw = wfGetDB( DB_MASTER );
2032 $storageMap = array(
2033 'fa_storage_group' => $dbw->addQuotes( $group ),
2034 'fa_storage_key' => $dbw->addQuotes( $key ),
2035
2036 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
2037 'fa_deleted_timestamp' => $dbw->timestamp(),
2038 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
2039 $allFields = array_merge( $storageMap, $fieldMap );
2040
2041 try {
2042 if( $wgSaveDeletedFiles ) {
2043 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
2044 }
2045 $dbw->delete( $table, $where, $fname );
2046 } catch( DBQueryError $e ) {
2047 // Something went horribly wrong!
2048 // Leave the file as it was...
2049 wfDebug( __METHOD__.": database error, rolling back file transaction\n" );
2050 $transaction->rollback();
2051 throw $e;
2052 }
2053
2054 return $transaction;
2055 }
2056
2057 /**
2058 * Restore all or specified deleted revisions to the given file.
2059 * Permissions and logging are left to the caller.
2060 *
2061 * May throw database exceptions on error.
2062 *
2063 * @param $versions set of record ids of deleted items to restore,
2064 * or empty to restore all revisions.
2065 * @return the number of file revisions restored if successful,
2066 * or false on failure
2067 */
2068 function restore( $versions=array() ) {
2069 if( !FileStore::lock() ) {
2070 wfDebug( __METHOD__." could not acquire filestore lock\n" );
2071 return false;
2072 }
2073
2074 $transaction = new FSTransaction();
2075 try {
2076 $dbw = wfGetDB( DB_MASTER );
2077 $dbw->begin();
2078
2079 // Re-confirm whether this image presently exists;
2080 // if no we'll need to create an image record for the
2081 // first item we restore.
2082 $exists = $dbw->selectField( 'image', '1',
2083 array( 'img_name' => $this->name ),
2084 __METHOD__ );
2085
2086 // Fetch all or selected archived revisions for the file,
2087 // sorted from the most recent to the oldest.
2088 $conditions = array( 'fa_name' => $this->name );
2089 if( $versions ) {
2090 $conditions['fa_id'] = $versions;
2091 }
2092
2093 $result = $dbw->select( 'filearchive', '*',
2094 $conditions,
2095 __METHOD__,
2096 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2097
2098 if( $dbw->numRows( $result ) < count( $versions ) ) {
2099 // There's some kind of conflict or confusion;
2100 // we can't restore everything we were asked to.
2101 wfDebug( __METHOD__.": couldn't find requested items\n" );
2102 $dbw->rollback();
2103 FileStore::unlock();
2104 return false;
2105 }
2106
2107 if( $dbw->numRows( $result ) == 0 ) {
2108 // Nothing to do.
2109 wfDebug( __METHOD__.": nothing to do\n" );
2110 $dbw->rollback();
2111 FileStore::unlock();
2112 return true;
2113 }
2114
2115 $revisions = 0;
2116 while( $row = $dbw->fetchObject( $result ) ) {
2117 $revisions++;
2118 $store = FileStore::get( $row->fa_storage_group );
2119 if( !$store ) {
2120 wfDebug( __METHOD__.": skipping row with no file.\n" );
2121 continue;
2122 }
2123
2124 if( $revisions == 1 && !$exists ) {
2125 $destDir = wfImageDir( $row->fa_name );
2126 if ( !is_dir( $destDir ) ) {
2127 wfMkdirParents( $destDir );
2128 }
2129 $destPath = $destDir . DIRECTORY_SEPARATOR . $row->fa_name;
2130
2131 // We may have to fill in data if this was originally
2132 // an archived file revision.
2133 if( is_null( $row->fa_metadata ) ) {
2134 $tempFile = $store->filePath( $row->fa_storage_key );
2135 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2136
2137 $magic = MimeMagic::singleton();
2138 $mime = $magic->guessMimeType( $tempFile, true );
2139 $media_type = $magic->getMediaType( $tempFile, $mime );
2140 list( $major_mime, $minor_mime ) = self::splitMime( $mime );
2141 } else {
2142 $metadata = $row->fa_metadata;
2143 $major_mime = $row->fa_major_mime;
2144 $minor_mime = $row->fa_minor_mime;
2145 $media_type = $row->fa_media_type;
2146 }
2147
2148 $table = 'image';
2149 $fields = array(
2150 'img_name' => $row->fa_name,
2151 'img_size' => $row->fa_size,
2152 'img_width' => $row->fa_width,
2153 'img_height' => $row->fa_height,
2154 'img_metadata' => $metadata,
2155 'img_bits' => $row->fa_bits,
2156 'img_media_type' => $media_type,
2157 'img_major_mime' => $major_mime,
2158 'img_minor_mime' => $minor_mime,
2159 'img_description' => $row->fa_description,
2160 'img_user' => $row->fa_user,
2161 'img_user_text' => $row->fa_user_text,
2162 'img_timestamp' => $row->fa_timestamp );
2163 } else {
2164 $archiveName = $row->fa_archive_name;
2165 if( $archiveName == '' ) {
2166 // This was originally a current version; we
2167 // have to devise a new archive name for it.
2168 // Format is <timestamp of archiving>!<name>
2169 $archiveName =
2170 wfTimestamp( TS_MW, $row->fa_deleted_timestamp ) .
2171 '!' . $row->fa_name;
2172 }
2173 $destDir = wfImageArchiveDir( $row->fa_name );
2174 if ( !is_dir( $destDir ) ) {
2175 wfMkdirParents( $destDir );
2176 }
2177 $destPath = $destDir . DIRECTORY_SEPARATOR . $archiveName;
2178
2179 $table = 'oldimage';
2180 $fields = array(
2181 'oi_name' => $row->fa_name,
2182 'oi_archive_name' => $archiveName,
2183 'oi_size' => $row->fa_size,
2184 'oi_width' => $row->fa_width,
2185 'oi_height' => $row->fa_height,
2186 'oi_bits' => $row->fa_bits,
2187 'oi_description' => $row->fa_description,
2188 'oi_user' => $row->fa_user,
2189 'oi_user_text' => $row->fa_user_text,
2190 'oi_timestamp' => $row->fa_timestamp );
2191 }
2192
2193 $dbw->insert( $table, $fields, __METHOD__ );
2194 /// @fixme this delete is not totally safe, potentially
2195 $dbw->delete( 'filearchive',
2196 array( 'fa_id' => $row->fa_id ),
2197 __METHOD__ );
2198
2199 // Check if any other stored revisions use this file;
2200 // if so, we shouldn't remove the file from the deletion
2201 // archives so they will still work.
2202 $useCount = $dbw->selectField( 'filearchive',
2203 'COUNT(*)',
2204 array(
2205 'fa_storage_group' => $row->fa_storage_group,
2206 'fa_storage_key' => $row->fa_storage_key ),
2207 __METHOD__ );
2208 if( $useCount == 0 ) {
2209 wfDebug( __METHOD__.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2210 $flags = FileStore::DELETE_ORIGINAL;
2211 } else {
2212 $flags = 0;
2213 }
2214
2215 $transaction->add( $store->export( $row->fa_storage_key,
2216 $destPath, $flags ) );
2217 }
2218
2219 $dbw->immediateCommit();
2220 } catch( MWException $e ) {
2221 wfDebug( __METHOD__." caught error, aborting\n" );
2222 $transaction->rollback();
2223 throw $e;
2224 }
2225
2226 $transaction->commit();
2227 FileStore::unlock();
2228
2229 if( $revisions > 0 ) {
2230 if( !$exists ) {
2231 wfDebug( __METHOD__." restored $revisions items, creating a new current\n" );
2232
2233 // Update site_stats
2234 $site_stats = $dbw->tableName( 'site_stats' );
2235 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
2236
2237 $this->purgeEverything();
2238 } else {
2239 wfDebug( __METHOD__." restored $revisions as archived versions\n" );
2240 $this->purgeDescription();
2241 }
2242 }
2243
2244 return $revisions;
2245 }
2246
2247 /**
2248 * Select a page from a multipage document. Determines the page used for
2249 * rendering thumbnails.
2250 *
2251 * @param $page Integer: page number, starting with 1
2252 */
2253 function selectPage( $page ) {
2254 wfDebug( __METHOD__." selecting page $page \n" );
2255 $this->page = $page;
2256 if ( ! $this->dataLoaded ) {
2257 $this->load();
2258 }
2259 if ( ! isset( $this->multiPageXML ) ) {
2260 $this->initializeMultiPageXML();
2261 }
2262 $o = $this->multiPageXML->BODY[0]->OBJECT[$page-1];
2263 $this->height = intval( $o['height'] );
2264 $this->width = intval( $o['width'] );
2265 }
2266
2267 function initializeMultiPageXML() {
2268 #
2269 # Check for files uploaded prior to DJVU support activation
2270 # They have a '0' in their metadata field.
2271 #
2272 if ( $this->metadata == '0' || $this->metadata == '' ) {
2273 $deja = new DjVuImage( $this->imagePath );
2274 $this->metadata = $deja->retrieveMetaData();
2275 $this->purgeMetadataCache();
2276
2277 # Update metadata in the database
2278 $dbw = wfGetDB( DB_MASTER );
2279 $dbw->update( 'image',
2280 array( 'img_metadata' => $this->metadata ),
2281 array( 'img_name' => $this->name ),
2282 __METHOD__
2283 );
2284 }
2285 wfSuppressWarnings();
2286 $this->multiPageXML = new SimpleXMLElement( $this->metadata );
2287 wfRestoreWarnings();
2288 }
2289
2290 /**
2291 * Returns 'true' if this image is a multipage document, e.g. a DJVU
2292 * document.
2293 *
2294 * @return Bool
2295 */
2296 function isMultipage() {
2297 return ( $this->mime == 'image/vnd.djvu' );
2298 }
2299
2300 /**
2301 * Returns the number of pages of a multipage document, or NULL for
2302 * documents which aren't multipage documents
2303 */
2304 function pageCount() {
2305 if ( ! $this->isMultipage() ) {
2306 return null;
2307 }
2308 if ( ! isset( $this->multiPageXML ) ) {
2309 $this->initializeMultiPageXML();
2310 }
2311 return count( $this->multiPageXML->xpath( '//OBJECT' ) );
2312 }
2313
2314 } //class
2315
2316 /**
2317 * Wrapper class for thumbnail images
2318 */
2319 class ThumbnailImage {
2320 /**
2321 * @param string $path Filesystem path to the thumb
2322 * @param string $url URL path to the thumb
2323 * @private
2324 */
2325 function ThumbnailImage( $url, $width, $height, $path = false ) {
2326 $this->url = $url;
2327 $this->width = round( $width );
2328 $this->height = round( $height );
2329 # These should be integers when they get here.
2330 # If not, there's a bug somewhere. But let's at
2331 # least produce valid HTML code regardless.
2332 $this->path = $path;
2333 }
2334
2335 /**
2336 * @return string The thumbnail URL
2337 */
2338 function getUrl() {
2339 return $this->url;
2340 }
2341
2342 /**
2343 * Return HTML <img ... /> tag for the thumbnail, will include
2344 * width and height attributes and a blank alt text (as required).
2345 *
2346 * You can set or override additional attributes by passing an
2347 * associative array of name => data pairs. The data will be escaped
2348 * for HTML output, so should be in plaintext.
2349 *
2350 * @param array $attribs
2351 * @return string
2352 * @public
2353 */
2354 function toHtml( $attribs = array() ) {
2355 $attribs['src'] = $this->url;
2356 $attribs['width'] = $this->width;
2357 $attribs['height'] = $this->height;
2358 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2359
2360 $html = '<img ';
2361 foreach( $attribs as $name => $data ) {
2362 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
2363 }
2364 $html .= '/>';
2365 return $html;
2366 }
2367
2368 }
2369
2370 ?>