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