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