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