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