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