PHP4 doesn't like null references, so splitting function
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 * @package MediaWiki
4 */
5
6 # NOTE FOR WINDOWS USERS:
7 # To enable EXIF functions, add the folloing lines to the
8 # "Windows extensions" section of php.ini:
9 #
10 # extension=extensions/php_mbstring.dll
11 # extension=extensions/php_exif.dll
12
13 if ($wgShowEXIF)
14 require_once('Exif.php');
15
16
17 /**
18 * Class to represent an image
19 *
20 * Provides methods to retrieve paths (physical, logical, URL),
21 * to generate thumbnails or for uploading.
22 * @package MediaWiki
23 */
24 class Image
25 {
26 /**#@+
27 * @access private
28 */
29 var $name, # name of the image (constructor)
30 $imagePath, # Path of the image (loadFromXxx)
31 $url, # Image URL (accessor)
32 $title, # Title object for this image (constructor)
33 $fileExists, # does the image file exist on disk? (loadFromXxx)
34 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
35 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
36 $historyRes, # result of the query for the image's history (nextHistoryLine)
37 $width, # \
38 $height, # |
39 $bits, # --- returned by getimagesize (loadFromXxx)
40 $attr, # /
41 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
42 $mime, # MIME type, determined by MimeMagic::guessMimeType
43 $size, # Size in bytes (loadFromXxx)
44 $metadata, # Metadata
45 $exif, # The Exif class
46 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
47
48
49 /**#@-*/
50
51 /**
52 * Create an Image object from an image name
53 *
54 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
55 * @access public
56 */
57 function newFromName( $name ) {
58 $title = Title::makeTitleSafe( NS_IMAGE, $name );
59 return new Image( $title );
60 }
61
62 /**
63 * Obsolete factory function, use constructor
64 */
65 function newFromTitle( $title ) {
66 return new Image( $title );
67 }
68
69 function Image( $title ) {
70 global $wgShowEXIF;
71
72 $this->title =& $title;
73 $this->name = $title->getDBkey();
74 $this->metadata = serialize ( array() ) ;
75
76 $n = strrpos( $this->name, '.' );
77 $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
78 $this->historyLine = 0;
79
80 $this->dataLoaded = false;
81
82 if ($wgShowEXIF)
83 $this->exif = new Exif;
84 }
85
86 /**
87 * Get the memcached keys
88 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
89 */
90 function getCacheKeys( $shared = false ) {
91 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
92
93 $foundCached = false;
94 $hashedName = md5($this->name);
95 $keys = array( "$wgDBname:Image:$hashedName" );
96 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
97 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
98 }
99 return $keys;
100 }
101
102 /**
103 * Try to load image metadata from memcached. Returns true on success.
104 */
105 function loadFromCache() {
106 global $wgUseSharedUploads, $wgMemc;
107 $fname = 'Image::loadFromMemcached';
108 wfProfileIn( $fname );
109 $this->dataLoaded = false;
110 $keys = $this->getCacheKeys();
111 $cachedValues = $wgMemc->get( $keys[0] );
112
113 // Check if the key existed and belongs to this version of MediaWiki
114 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width'])
115 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
116 {
117 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
118 # if this is shared file, we need to check if image
119 # in shared repository has not changed
120 if ( isset( $keys[1] ) ) {
121 $commonsCachedValues = $wgMemc->get( $keys[1] );
122 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
123 $this->name = $commonsCachedValues['name'];
124 $this->imagePath = $commonsCachedValues['imagePath'];
125 $this->fileExists = $commonsCachedValues['fileExists'];
126 $this->width = $commonsCachedValues['width'];
127 $this->height = $commonsCachedValues['height'];
128 $this->bits = $commonsCachedValues['bits'];
129 $this->type = $commonsCachedValues['type'];
130 $this->mime = $commonsCachedValues['mime'];
131 $this->metadata = $commonsCachedValues['metadata'];
132 $this->size = $commonsCachedValues['size'];
133 $this->fromSharedDirectory = true;
134 $this->dataLoaded = true;
135 $this->imagePath = $this->getFullPath(true);
136 }
137 }
138 }
139 else {
140 $this->name = $cachedValues['name'];
141 $this->imagePath = $cachedValues['imagePath'];
142 $this->fileExists = $cachedValues['fileExists'];
143 $this->width = $cachedValues['width'];
144 $this->height = $cachedValues['height'];
145 $this->bits = $cachedValues['bits'];
146 $this->type = $cachedValues['type'];
147 $this->mime = $cachedValues['mime'];
148 $this->metadata = $cachedValues['metadata'];
149 $this->size = $cachedValues['size'];
150 $this->fromSharedDirectory = false;
151 $this->dataLoaded = true;
152 $this->imagePath = $this->getFullPath();
153 }
154 }
155
156 wfProfileOut( $fname );
157 return $this->dataLoaded;
158 }
159
160 /**
161 * Save the image metadata to memcached
162 */
163 function saveToCache() {
164 global $wgMemc;
165 $this->load();
166 // We can't cache metadata for non-existent files, because if the file later appears
167 // in commons, the local keys won't be purged.
168 if ( $this->fileExists ) {
169 $keys = $this->getCacheKeys();
170
171 $cachedValues = array('name' => $this->name,
172 'imagePath' => $this->imagePath,
173 'fileExists' => $this->fileExists,
174 'fromShared' => $this->fromSharedDirectory,
175 'width' => $this->width,
176 'height' => $this->height,
177 'bits' => $this->bits,
178 'type' => $this->type,
179 'mime' => $this->mime,
180 'metadata' => $this->metadata,
181 'size' => $this->size);
182
183 $wgMemc->set( $keys[0], $cachedValues );
184 }
185 }
186
187 /**
188 * Load metadata from the file itself
189 */
190 function loadFromFile() {
191 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang,
192 $wgShowEXIF;
193 $fname = 'Image::loadFromFile';
194 wfProfileIn( $fname );
195 $this->imagePath = $this->getFullPath();
196 $this->fileExists = file_exists( $this->imagePath );
197 $this->fromSharedDirectory = false;
198 $gis = array();
199
200 if (!$this->fileExists) wfDebug("$fname: ".$this->imagePath." not found locally!\n");
201
202 # If the file is not found, and a shared upload directory is used, look for it there.
203 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
204 # In case we're on a wgCapitalLinks=false wiki, we
205 # capitalize the first letter of the filename before
206 # looking it up in the shared repository.
207 $sharedImage = Image::newFromName( $wgLang->ucfirst($this->name) );
208 $this->fileExists = file_exists( $sharedImage->getFullPath(true) );
209 if ( $this->fileExists ) {
210 $this->name = $sharedImage->name;
211 $this->imagePath = $this->getFullPath(true);
212 $this->fromSharedDirectory = true;
213 }
214 }
215
216
217 if ( $this->fileExists ) {
218 $magic=& wfGetMimeMagic();
219
220 $this->mime = $magic->guessMimeType($this->imagePath,true);
221 $this->type = $magic->getMediaType($this->imagePath,$this->mime);
222
223 # Get size in bytes
224 $this->size = filesize( $this->imagePath );
225
226 $magic=& wfGetMimeMagic();
227
228 # Height and width
229 if( $this->mime == 'image/svg' ) {
230 wfSuppressWarnings();
231 $gis = wfGetSVGsize( $this->imagePath );
232 wfRestoreWarnings();
233 }
234 elseif ( !$magic->isPHPImageType( $this->mime ) ) {
235 # Don't try to get the width and height of sound and video files, that's bad for performance
236 $gis[0]= 0; //width
237 $gis[1]= 0; //height
238 $gis[2]= 0; //unknown
239 $gis[3]= ""; //width height string
240 }
241 else {
242 wfSuppressWarnings();
243 $gis = getimagesize( $this->imagePath );
244 wfRestoreWarnings();
245 }
246
247 wfDebug("$fname: ".$this->imagePath." loaded, ".$this->size." bytes, ".$this->mime.".\n");
248 }
249 else {
250 $gis[0]= 0; //width
251 $gis[1]= 0; //height
252 $gis[2]= 0; //unknown
253 $gis[3]= ""; //width height string
254
255 $this->mime = NULL;
256 $this->type = MEDIATYPE_UNKNOWN;
257 wfDebug("$fname: ".$this->imagePath." NOT FOUND!\n");
258 }
259
260 $this->width = $gis[0];
261 $this->height = $gis[1];
262
263 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
264
265 #NOTE: we have to set this flag early to avoid load() to be called
266 # be some of the functions below. This may lead to recursion or other bad things!
267 # as ther's only one thread of execution, this should be safe anyway.
268 $this->dataLoaded = true;
269
270
271 if ($this->fileExists && $wgShowEXIF) $this->metadata = serialize ( $this->retrieveExifData() ) ;
272 else $this->metadata = serialize ( array() ) ;
273
274 if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
275 else $this->bits = 0;
276
277 wfProfileOut( $fname );
278 }
279
280 /**
281 * Load image metadata from the DB
282 */
283 function loadFromDB() {
284 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
285 $fname = 'Image::loadFromDB';
286 wfProfileIn( $fname );
287
288 $dbr =& wfGetDB( DB_SLAVE );
289
290 $this->checkDBSchema($dbr);
291
292 $row = $dbr->selectRow( 'image',
293 array( 'img_size', 'img_width', 'img_height', 'img_bits',
294 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
295 array( 'img_name' => $this->name ), $fname );
296 if ( $row ) {
297 $this->fromSharedDirectory = false;
298 $this->fileExists = true;
299 $this->loadFromRow( $row );
300 $this->imagePath = $this->getFullPath();
301 // Check for rows from a previous schema, quietly upgrade them
302 if ( is_null($this->type) ) {
303 $this->upgradeRow();
304 }
305 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
306 # In case we're on a wgCapitalLinks=false wiki, we
307 # capitalize the first letter of the filename before
308 # looking it up in the shared repository.
309 $name = $wgLang->ucfirst($this->name);
310
311 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
312 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_media_type', 'img_major_mime', 'img_minor_mime' ),
313 array( 'img_name' => $name ), $fname );
314 if ( $row ) {
315 $this->fromSharedDirectory = true;
316 $this->fileExists = true;
317 $this->imagePath = $this->getFullPath(true);
318 $this->name = $name;
319 $this->loadFromRow( $row );
320
321 // Check for rows from a previous schema, quietly upgrade them
322 if ( is_null($this->type) ) {
323 $this->upgradeRow();
324 }
325 }
326 }
327
328 if ( !$row ) {
329 $this->size = 0;
330 $this->width = 0;
331 $this->height = 0;
332 $this->bits = 0;
333 $this->type = 0;
334 $this->fileExists = false;
335 $this->fromSharedDirectory = false;
336 $this->metadata = serialize ( array() ) ;
337 }
338
339 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
340 $this->dataLoaded = true;
341 }
342
343 /*
344 * Load image metadata from a DB result row
345 */
346 function loadFromRow( &$row ) {
347 $this->size = $row->img_size;
348 $this->width = $row->img_width;
349 $this->height = $row->img_height;
350 $this->bits = $row->img_bits;
351 $this->type = $row->img_media_type;
352
353 $major= $row->img_major_mime;
354 $minor= $row->img_minor_mime;
355
356 if (!$major) $this->mime = "unknown/unknown";
357 else {
358 if (!$minor) $minor= "unknown";
359 $this->mime = $major.'/'.$minor;
360 }
361
362 $this->metadata = $row->img_metadata;
363 if ( $this->metadata == "" ) $this->metadata = serialize ( array() ) ;
364
365 $this->dataLoaded = true;
366 }
367
368 /**
369 * Load image metadata from cache or DB, unless already loaded
370 */
371 function load() {
372 global $wgSharedUploadDBname, $wgUseSharedUploads;
373 if ( !$this->dataLoaded ) {
374 if ( !$this->loadFromCache() ) {
375 $this->loadFromDB();
376 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
377 $this->loadFromFile();
378 } elseif ( $this->fileExists ) {
379 $this->saveToCache();
380 }
381 }
382 $this->dataLoaded = true;
383 }
384 }
385
386 /**
387 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
388 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
389 */
390 function upgradeRow() {
391 global $wgDBname, $wgSharedUploadDBname;
392 $fname = 'Image::upgradeRow';
393 $this->loadFromFile();
394 $dbw =& wfGetDB( DB_MASTER );
395
396 if ( $this->fromSharedDirectory ) {
397 if ( !$wgSharedUploadDBname ) {
398 return;
399 }
400
401 // Write to the other DB using selectDB, not database selectors
402 // This avoids breaking replication in MySQL
403 $dbw->selectDB( $wgSharedUploadDBname );
404 }
405
406 $this->checkDBSchema($dbw);
407
408 if (strpos($this->mime,'/')!==false) {
409 list($major,$minor)= explode('/',$this->mime,2);
410 }
411 else {
412 $major= $this->mime;
413 $minor= "unknown";
414 }
415
416 wfDebug("$fname: upgrading ".$this->name." to 1.5 schema\n");
417
418 $dbw->update( 'image',
419 array(
420 'img_width' => $this->width,
421 'img_height' => $this->height,
422 'img_bits' => $this->bits,
423 'img_media_type' => $this->type,
424 'img_major_mime' => $major,
425 'img_minor_mime' => $minor,
426 'img_metadata' => $this->metadata,
427 ), array( 'img_name' => $this->name ), $fname
428 );
429 if ( $this->fromSharedDirectory ) {
430 $dbw->selectDB( $wgDBname );
431 }
432 }
433
434 /**
435 * Return the name of this image
436 * @access public
437 */
438 function getName() {
439 return $this->name;
440 }
441
442 /**
443 * Return the associated title object
444 * @access public
445 */
446 function getTitle() {
447 return $this->title;
448 }
449
450 /**
451 * Return the URL of the image file
452 * @access public
453 */
454 function getURL() {
455 if ( !$this->url ) {
456 $this->load();
457 if($this->fileExists) {
458 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
459 } else {
460 $this->url = '';
461 }
462 }
463 return $this->url;
464 }
465
466 function getViewURL() {
467 if( $this->mustRender()) {
468 if( $this->canRender() ) {
469 return $this->createThumb( $this->getWidth() );
470 }
471 else {
472 wfDebug('Image::getViewURL(): supposed to render '.$this->name.' ('.$this->mime."), but can't!\n");
473 return $this->getURL(); #hm... return NULL?
474 }
475 } else {
476 return $this->getURL();
477 }
478 }
479
480 /**
481 * Return the image path of the image in the
482 * local file system as an absolute path
483 * @access public
484 */
485 function getImagePath() {
486 $this->load();
487 return $this->imagePath;
488 }
489
490 /**
491 * Return the width of the image
492 *
493 * Returns -1 if the file specified is not a known image type
494 * @access public
495 */
496 function getWidth() {
497 $this->load();
498 return $this->width;
499 }
500
501 /**
502 * Return the height of the image
503 *
504 * Returns -1 if the file specified is not a known image type
505 * @access public
506 */
507 function getHeight() {
508 $this->load();
509 return $this->height;
510 }
511
512 /**
513 * Return the size of the image file, in bytes
514 * @access public
515 */
516 function getSize() {
517 $this->load();
518 return $this->size;
519 }
520
521 /**
522 * Returns the mime type of the file.
523 */
524 function getMimeType() {
525 $this->load();
526 return $this->mime;
527 }
528
529 /**
530 * Return the type of the media in the file.
531 * Use the value returned by this function with the MEDIATYPE_xxx constants.
532 */
533 function getMediaType() {
534 $this->load();
535 return $this->type;
536 }
537
538 /**
539 * Checks if the file can be presented to the browser as a bitmap.
540 *
541 * Currently, this checks if the file is an image format
542 * that can be converted to a format
543 * supported by all browsers (namely GIF, PNG and JPEG),
544 * or if it is an SVG image and SVG conversion is enabled.
545 *
546 * @todo remember the result of this check.
547 */
548 function canRender() {
549 global $wgUseImageMagick;
550
551 if( $this->getWidth()<=0 || $this->getHeight()<=0 ) return false;
552
553 $mime= $this->getMimeType();
554
555 if (!$mime || $mime==='unknown' || $mime==='unknown/unknown') return false;
556
557 #if it's SVG, check if ther's a converter enabled
558 if ($mime === 'image/svg') {
559 global $wgSVGConverters, $wgSVGConverter;
560
561 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
562 return true;
563 }
564 }
565
566 #image formats available on ALL browsers
567 if ( $mime === 'image/gif'
568 || $mime === 'image/png'
569 || $mime === 'image/jpeg' ) return true;
570
571 #image formats that can be converted to the above formats
572 if ($wgUseImageMagick) {
573 #convertable by ImageMagick (there are more...)
574 if ( $mime === 'image/vnd.wap.wbmp'
575 || $mime === 'image/x-xbitmap'
576 || $mime === 'image/x-xpixmap'
577 #|| $mime === 'image/x-icon' #file may be split into multiple parts
578 || $mime === 'image/x-portable-anymap'
579 || $mime === 'image/x-portable-bitmap'
580 || $mime === 'image/x-portable-graymap'
581 || $mime === 'image/x-portable-pixmap'
582 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
583 || $mime === 'image/x-rgb'
584 || $mime === 'image/x-bmp'
585 || $mime === 'image/tiff' ) return true;
586 }
587 else {
588 #convertable by the PHP GD image lib
589 if ( $mime === 'image/vnd.wap.wbmp'
590 || $mime === 'image/x-xbitmap' ) return true;
591 }
592
593 return false;
594 }
595
596
597 /**
598 * Return true if the file is of a type that can't be directly
599 * rendered by typical browsers and needs to be re-rasterized.
600 *
601 * This returns true for everything but the bitmap types
602 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
603 * also return true for any non-image formats.
604 *
605 * @return bool
606 */
607 function mustRender() {
608 $mime= $this->getMimeType();
609
610 if ( $mime === "image/gif"
611 || $mime === "image/png"
612 || $mime === "image/jpeg" ) return false;
613
614 return true;
615 }
616
617 /**
618 * Determines if this media file may be shown inline on a page.
619 *
620 * This is currently synonymous to canRender(), but this could be
621 * extended to also allow inline display of other media,
622 * like flash animations or videos. If you do so, please keep in mind that
623 * that could be a scurity risc.
624 */
625 function allowInlineDisplay() {
626 return $this->canRender();
627 }
628
629 /**
630 * Determines if this media file is in a format that is unlikely to contain viruses
631 * or malicious content. It uses the global $wgTrustedMediaFormats list to determine
632 * if the file is safe.
633 *
634 * This is used to show a warning on the description page of non-safe files.
635 * It may also be used to disallow direct [[media:...]] links to such files.
636 *
637 * Note that this function will always return ture if allowInlineDisplay()
638 * or isTrustedFile() is true for this file.
639 */
640 function isSafeFile() {
641 if ($this->allowInlineDisplay()) return true;
642 if ($this->isTrustedFile()) return true;
643
644 global $wgTrustedMediaFormats;
645
646 $type= $this->getMediaType();
647 $mime= $this->getMimeType();
648 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
649
650 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
651 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
652
653 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
654 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
655
656 return false;
657 }
658
659 /** Returns true if the file is flagegd as trusted. Files flagged that way can be
660 * linked to directly, even if that is not allowed for this type of file normally.
661 *
662 * This is a dummy function right now and always returns false. It could be implemented
663 * to extract a flag from the database. The trusted flag could be set on upload, if the
664 * user has sufficient privileges, to bypass script- and html-filters. It may even be
665 * coupeled with cryptographics signatures or such.
666 */
667 function isTrustedFile() {
668 #this could be implemented to check a flag in the databas,
669 #look for signatures, etc
670 return false;
671 }
672
673 /**
674 * Return the escapeLocalURL of this image
675 * @access public
676 */
677 function getEscapeLocalURL() {
678 $this->getTitle();
679 return $this->title->escapeLocalURL();
680 }
681
682 /**
683 * Return the escapeFullURL of this image
684 * @access public
685 */
686 function getEscapeFullURL() {
687 $this->getTitle();
688 return $this->title->escapeFullURL();
689 }
690
691 /**
692 * Return the URL of an image, provided its name.
693 *
694 * @param string $name Name of the image, without the leading "Image:"
695 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
696 * @access public
697 * @static
698 */
699 function imageUrl( $name, $fromSharedDirectory = false ) {
700 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
701 if($fromSharedDirectory) {
702 $base = '';
703 $path = $wgSharedUploadPath;
704 } else {
705 $base = $wgUploadBaseUrl;
706 $path = $wgUploadPath;
707 }
708 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
709 return wfUrlencode( $url );
710 }
711
712 /**
713 * Returns true if the image file exists on disk.
714 *
715 * @access public
716 */
717 function exists() {
718 $this->load();
719 return $this->fileExists;
720 }
721
722 /**
723 *
724 * @access private
725 */
726 function thumbUrl( $width, $subdir='thumb') {
727 global $wgUploadPath, $wgUploadBaseUrl,
728 $wgSharedUploadPath,$wgSharedUploadDirectory,
729 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
730
731 // Generate thumb.php URL if possible
732 $script = false;
733 $url = false;
734
735 if ( $this->fromSharedDirectory ) {
736 if ( $wgSharedThumbnailScriptPath ) {
737 $script = $wgSharedThumbnailScriptPath;
738 }
739 } else {
740 if ( $wgThumbnailScriptPath ) {
741 $script = $wgThumbnailScriptPath;
742 }
743 }
744 if ( $script ) {
745 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
746 if( $this->mustRender() ) {
747 $url.= '&r=1';
748 }
749 } else {
750 $name = $this->thumbName( $width );
751 if($this->fromSharedDirectory) {
752 $base = '';
753 $path = $wgSharedUploadPath;
754 } else {
755 $base = $wgUploadBaseUrl;
756 $path = $wgUploadPath;
757 }
758 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
759 $url = "{$base}{$path}/{$subdir}" .
760 wfGetHashPath($this->name, $this->fromSharedDirectory)
761 . $this->name.'/'.$name;
762 $url = wfUrlencode( $url );
763 } else {
764 $url = "{$base}{$path}/{$subdir}/{$name}";
765 }
766 }
767 return array( $script !== false, $url );
768 }
769
770 /**
771 * Return the file name of a thumbnail of the specified width
772 *
773 * @param integer $width Width of the thumbnail image
774 * @param boolean $shared Does the thumbnail come from the shared repository?
775 * @access private
776 */
777 function thumbName( $width ) {
778 $thumb = $width."px-".$this->name;
779
780 if( $this->mustRender() ) {
781 if( $this->canRender() ) {
782 # Rasterize to PNG (for SVG vector images, etc)
783 $thumb .= '.png';
784 }
785 else {
786 #should we use iconThumb here to get a symbolic thumbnail?
787 #or should we fail with an internal error?
788 return NULL; //can't make bitmap
789 }
790 }
791 return $thumb;
792 }
793
794 /**
795 * Create a thumbnail of the image having the specified width/height.
796 * The thumbnail will not be created if the width is larger than the
797 * image's width. Let the browser do the scaling in this case.
798 * The thumbnail is stored on disk and is only computed if the thumbnail
799 * file does not exist OR if it is older than the image.
800 * Returns the URL.
801 *
802 * Keeps aspect ratio of original image. If both width and height are
803 * specified, the generated image will be no bigger than width x height,
804 * and will also have correct aspect ratio.
805 *
806 * @param integer $width maximum width of the generated thumbnail
807 * @param integer $height maximum height of the image (optional)
808 * @access public
809 */
810 function createThumb( $width, $height=-1 ) {
811 $thumb = $this->getThumbnail( $width, $height );
812 if( is_null( $thumb ) ) return '';
813 return $thumb->getUrl();
814 }
815
816 /**
817 * As createThumb, but returns a ThumbnailImage object. This can
818 * provide access to the actual file, the real size of the thumb,
819 * and can produce a convenient <img> tag for you.
820 *
821 * @param integer $width maximum width of the generated thumbnail
822 * @param integer $height maximum height of the image (optional)
823 * @return ThumbnailImage
824 * @access public
825 */
826 function &getThumbnail( $width, $height=-1 ) {
827 if ( $height == -1 ) {
828 return $this->renderThumb( $width );
829 }
830 $this->load();
831
832 if ($this->canRender()) {
833 if ( $width < $this->width ) {
834 $thumbheight = $this->height * $width / $this->width;
835 $thumbwidth = $width;
836 } else {
837 $thumbheight = $this->height;
838 $thumbwidth = $this->width;
839 }
840 if ( $thumbheight > $height ) {
841 $thumbwidth = $thumbwidth * $height / $thumbheight;
842 $thumbheight = $height;
843 }
844
845 $thumb = $this->renderThumb( $thumbwidth );
846 }
847 else $thumb= NULL; #not a bitmap or renderable image, don't try.
848
849 if( is_null( $thumb ) ) {
850 $thumb = $this->iconThumb();
851 }
852 return $thumb;
853 }
854
855 /**
856 * @return ThumbnailImage
857 */
858 function iconThumb() {
859 global $wgStylePath, $wgStyleDirectory;
860
861 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
862 foreach( $try as $icon ) {
863 $path = '/common/images/icons/' . $icon;
864 $filepath = $wgStyleDirectory . $path;
865 if( file_exists( $filepath ) ) {
866 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
867 }
868 }
869 return null;
870 }
871
872 /**
873 * Create a thumbnail of the image having the specified width.
874 * The thumbnail will not be created if the width is larger than the
875 * image's width. Let the browser do the scaling in this case.
876 * The thumbnail is stored on disk and is only computed if the thumbnail
877 * file does not exist OR if it is older than the image.
878 * Returns an object which can return the pathname, URL, and physical
879 * pixel size of the thumbnail -- or null on failure.
880 *
881 * @return ThumbnailImage
882 * @access private
883 */
884 function renderThumb( $width, $useScript = true ) {
885 global $wgUseSquid, $wgInternalServer;
886 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
887
888 $width = IntVal( $width );
889
890 $this->load();
891 if ( ! $this->exists() )
892 {
893 # If there is no image, there will be no thumbnail
894 return null;
895 }
896
897 # Sanity check $width
898 if( $width <= 0 || $this->width <= 0) {
899 # BZZZT
900 return null;
901 }
902
903 if( $width > $this->width && !$this->mustRender() ) {
904 # Don't make an image bigger than the source
905 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
906 }
907
908 $height = floor( $this->height * ( $width/$this->width ) );
909
910 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
911 if ( $isScriptUrl && $useScript ) {
912 // Use thumb.php to render the image
913 return new ThumbnailImage( $url, $width, $height );
914 }
915
916 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
917 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
918
919 if ( !file_exists( $thumbPath ) ) {
920 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
921 '/'.$thumbName;
922 $done = false;
923 if ( file_exists( $oldThumbPath ) ) {
924 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
925 rename( $oldThumbPath, $thumbPath );
926 $done = true;
927 } else {
928 unlink( $oldThumbPath );
929 }
930 }
931 if ( !$done ) {
932 $this->reallyRenderThumb( $thumbPath, $width, $height );
933
934 # Purge squid
935 # This has to be done after the image is updated and present for all machines on NFS,
936 # or else the old version might be stored into the squid again
937 if ( $wgUseSquid ) {
938 if ( substr( $url, 0, 4 ) == 'http' ) {
939 $urlArr = array( $url );
940 } else {
941 $urlArr = array( $wgInternalServer.$url );
942 }
943 wfPurgeSquidServers($urlArr);
944 }
945 }
946 }
947
948 return new ThumbnailImage( $url, $width, $height, $thumbPath );
949 } // END OF function renderThumb
950
951 /**
952 * Really render a thumbnail
953 * Call this only for images for which canRender() returns true.
954 *
955 * @access private
956 */
957 function reallyRenderThumb( $thumbPath, $width, $height ) {
958 global $wgSVGConverters, $wgSVGConverter,
959 $wgUseImageMagick, $wgImageMagickConvertCommand;
960
961 $this->load();
962
963 if( $this->mime === "image/svg" ) {
964 #Right now we have only SVG
965
966 global $wgSVGConverters, $wgSVGConverter;
967 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
968 global $wgSVGConverterPath;
969 $cmd = str_replace(
970 array( '$path/', '$width', '$input', '$output' ),
971 array( $wgSVGConverterPath,
972 $width,
973 wfEscapeShellArg( $this->imagePath ),
974 wfEscapeShellArg( $thumbPath ) ),
975 $wgSVGConverters[$wgSVGConverter] );
976 $conv = shell_exec( $cmd );
977 } else {
978 $conv = false;
979 }
980 } elseif ( $wgUseImageMagick ) {
981 # use ImageMagick
982 # Specify white background color, will be used for transparent images
983 # in Internet Explorer/Windows instead of default black.
984 $cmd = $wgImageMagickConvertCommand .
985 " -quality 85 -background white -geometry {$width} ".
986 wfEscapeShellArg($this->imagePath) . " " .
987 wfEscapeShellArg($thumbPath);
988 wfDebug("reallyRenderThumb: running ImageMagick: $cmd");
989 $conv = shell_exec( $cmd );
990 } else {
991 # Use PHP's builtin GD library functions.
992 #
993 # First find out what kind of file this is, and select the correct
994 # input routine for this.
995
996 $truecolor = false;
997
998 switch( $this->type ) {
999 case 1: # GIF
1000 $src_image = imagecreatefromgif( $this->imagePath );
1001 break;
1002 case 2: # JPG
1003 $src_image = imagecreatefromjpeg( $this->imagePath );
1004 $truecolor = true;
1005 break;
1006 case 3: # PNG
1007 $src_image = imagecreatefrompng( $this->imagePath );
1008 $truecolor = ( $this->bits > 8 );
1009 break;
1010 case 15: # WBMP for WML
1011 $src_image = imagecreatefromwbmp( $this->imagePath );
1012 break;
1013 case 16: # XBM
1014 $src_image = imagecreatefromxbm( $this->imagePath );
1015 break;
1016 default:
1017 return 'Image type not supported';
1018 break;
1019 }
1020 if ( $truecolor ) {
1021 $dst_image = imagecreatetruecolor( $width, $height );
1022 } else {
1023 $dst_image = imagecreate( $width, $height );
1024 }
1025 imagecopyresampled( $dst_image, $src_image,
1026 0,0,0,0,
1027 $width, $height, $this->width, $this->height );
1028 switch( $this->type ) {
1029 case 1: # GIF
1030 case 3: # PNG
1031 case 15: # WBMP
1032 case 16: # XBM
1033 imagepng( $dst_image, $thumbPath );
1034 break;
1035 case 2: # JPEG
1036 imageinterlace( $dst_image );
1037 imagejpeg( $dst_image, $thumbPath, 95 );
1038 break;
1039 default:
1040 break;
1041 }
1042 imagedestroy( $dst_image );
1043 imagedestroy( $src_image );
1044 }
1045
1046 #
1047 # Check for zero-sized thumbnails. Those can be generated when
1048 # no disk space is available or some other error occurs
1049 #
1050 if( file_exists( $thumbPath ) ) {
1051 $thumbstat = stat( $thumbPath );
1052 if( $thumbstat['size'] == 0 ) {
1053 unlink( $thumbPath );
1054 }
1055 }
1056 }
1057
1058 /**
1059 * Get all thumbnail names previously generated for this image
1060 */
1061 function getThumbnails( $shared = false ) {
1062 if ( Image::isHashed( $shared ) ) {
1063 $this->load();
1064 $files = array();
1065 $dir = wfImageThumbDir( $this->name, $shared );
1066
1067 // This generates an error on failure, hence the @
1068 $handle = @opendir( $dir );
1069
1070 if ( $handle ) {
1071 while ( false !== ( $file = readdir($handle) ) ) {
1072 if ( $file{0} != '.' ) {
1073 $files[] = $file;
1074 }
1075 }
1076 closedir( $handle );
1077 }
1078 } else {
1079 $files = array();
1080 }
1081
1082 return $files;
1083 }
1084
1085 /**
1086 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1087 */
1088 function purgeCache( $archiveFiles = array(), $shared = false ) {
1089 global $wgInternalServer, $wgUseSquid;
1090
1091 // Refresh metadata cache
1092 clearstatcache();
1093 $this->loadFromFile();
1094 $this->saveToCache();
1095
1096 // Delete thumbnails
1097 $files = $this->getThumbnails( $shared );
1098 $dir = wfImageThumbDir( $this->name, $shared );
1099 $urls = array();
1100 foreach ( $files as $file ) {
1101 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1102 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
1103 @unlink( "$dir/$file" );
1104 }
1105 }
1106
1107 // Purge the squid
1108 if ( $wgUseSquid ) {
1109 $urls[] = $wgInternalServer . $this->getViewURL();
1110 foreach ( $archiveFiles as $file ) {
1111 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1112 }
1113 wfPurgeSquidServers( $urls );
1114 }
1115 }
1116
1117 function checkDBSchema(&$db) {
1118 # img_name must be unique
1119 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1120 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1121 }
1122
1123 #new fields must exist
1124 if ( !$db->fieldExists( 'image', 'img_media_type' )
1125 || !$db->fieldExists( 'image', 'img_metadata' )
1126 || !$db->fieldExists( 'image', 'img_width' ) ) {
1127
1128 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/updater.php' );
1129 }
1130 }
1131
1132 /**
1133 * Return the image history of this image, line by line.
1134 * starts with current version, then old versions.
1135 * uses $this->historyLine to check which line to return:
1136 * 0 return line for current version
1137 * 1 query for old versions, return first one
1138 * 2, ... return next old version from above query
1139 *
1140 * @access public
1141 */
1142 function nextHistoryLine() {
1143 $fname = 'Image::nextHistoryLine()';
1144 $dbr =& wfGetDB( DB_SLAVE );
1145
1146 $this->checkDBSchema($dbr);
1147
1148 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1149 $this->historyRes = $dbr->select( 'image',
1150 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
1151 array( 'img_name' => $this->title->getDBkey() ),
1152 $fname
1153 );
1154 if ( 0 == wfNumRows( $this->historyRes ) ) {
1155 return FALSE;
1156 }
1157 } else if ( $this->historyLine == 1 ) {
1158 $this->historyRes = $dbr->select( 'oldimage',
1159 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
1160 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
1161 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
1162 );
1163 }
1164 $this->historyLine ++;
1165
1166 return $dbr->fetchObject( $this->historyRes );
1167 }
1168
1169 /**
1170 * Reset the history pointer to the first element of the history
1171 * @access public
1172 */
1173 function resetHistory() {
1174 $this->historyLine = 0;
1175 }
1176
1177 /**
1178 * Return the full filesystem path to the file. Note that this does
1179 * not mean that a file actually exists under that location.
1180 *
1181 * This path depends on whether directory hashing is active or not,
1182 * i.e. whether the images are all found in the same directory,
1183 * or in hashed paths like /images/3/3c.
1184 *
1185 * @access public
1186 * @param boolean $fromSharedDirectory Return the path to the file
1187 * in a shared repository (see $wgUseSharedRepository and related
1188 * options in DefaultSettings.php) instead of a local one.
1189 *
1190 */
1191 function getFullPath( $fromSharedRepository = false ) {
1192 global $wgUploadDirectory, $wgSharedUploadDirectory;
1193 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1194
1195 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1196 $wgUploadDirectory;
1197
1198 // $wgSharedUploadDirectory may be false, if thumb.php is used
1199 if ( $dir ) {
1200 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1201 } else {
1202 $fullpath = false;
1203 }
1204
1205 return $fullpath;
1206 }
1207
1208 /**
1209 * @return bool
1210 * @static
1211 */
1212 function isHashed( $shared ) {
1213 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1214 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1215 }
1216
1217 /**
1218 * Record an image upload in the upload log and the image table
1219 */
1220 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
1221 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
1222 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1223
1224 $fname = 'Image::recordUpload';
1225 $dbw =& wfGetDB( DB_MASTER );
1226
1227 $this->checkDBSchema($dbw);
1228
1229 // Delete thumbnails and refresh the metadata cache
1230 $this->purgeCache();
1231
1232 // Fail now if the image isn't there
1233 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1234 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1235 return false;
1236 }
1237
1238 if ( $wgUseCopyrightUpload ) {
1239 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1240 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1241 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1242 } else {
1243 $textdesc = $desc;
1244 }
1245
1246 $now = $dbw->timestamp();
1247
1248 #split mime type
1249 if (strpos($this->mime,'/')!==false) {
1250 list($major,$minor)= explode('/',$this->mime,2);
1251 }
1252 else {
1253 $major= $this->mime;
1254 $minor= "unknown";
1255 }
1256
1257 # Test to see if the row exists using INSERT IGNORE
1258 # This avoids race conditions by locking the row until the commit, and also
1259 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1260 $dbw->insert( 'image',
1261 array(
1262 'img_name' => $this->name,
1263 'img_size'=> $this->size,
1264 'img_width' => $this->width,
1265 'img_height' => $this->height,
1266 'img_bits' => $this->bits,
1267 'img_media_type' => $this->type,
1268 'img_major_mime' => $major,
1269 'img_minor_mime' => $minor,
1270 'img_timestamp' => $now,
1271 'img_description' => $desc,
1272 'img_user' => $wgUser->getID(),
1273 'img_user_text' => $wgUser->getName(),
1274 'img_metadata' => $this->metadata,
1275 ), $fname, 'IGNORE'
1276 );
1277 $descTitle = $this->getTitle();
1278 $purgeURLs = array();
1279
1280 if ( $dbw->affectedRows() ) {
1281 # Successfully inserted, this is a new image
1282 $id = $descTitle->getArticleID();
1283
1284 if ( $id == 0 ) {
1285 $article = new Article( $descTitle );
1286 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1287 }
1288 } else {
1289 # Collision, this is an update of an image
1290 # Insert previous contents into oldimage
1291 $dbw->insertSelect( 'oldimage', 'image',
1292 array(
1293 'oi_name' => 'img_name',
1294 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1295 'oi_size' => 'img_size',
1296 'oi_width' => 'img_width',
1297 'oi_height' => 'img_height',
1298 'oi_bits' => 'img_bits',
1299 'oi_timestamp' => 'img_timestamp',
1300 'oi_description' => 'img_description',
1301 'oi_user' => 'img_user',
1302 'oi_user_text' => 'img_user_text',
1303 ), array( 'img_name' => $this->name ), $fname
1304 );
1305
1306 # Update the current image row
1307 $dbw->update( 'image',
1308 array( /* SET */
1309 'img_size' => $this->size,
1310 'img_width' => $this->width,
1311 'img_height' => $this->height,
1312 'img_bits' => $this->bits,
1313 'img_media_type' => $this->type,
1314 'img_major_mime' => $major,
1315 'img_minor_mime' => $minor,
1316 'img_timestamp' => $now,
1317 'img_description' => $desc,
1318 'img_user' => $wgUser->getID(),
1319 'img_user_text' => $wgUser->getName(),
1320 'img_metadata' => $this->metadata,
1321 ), array( /* WHERE */
1322 'img_name' => $this->name
1323 ), $fname
1324 );
1325
1326 # Invalidate the cache for the description page
1327 $descTitle->invalidateCache();
1328 $purgeURLs[] = $descTitle->getInternalURL();
1329 }
1330
1331 # Invalidate cache for all pages using this image
1332 $linksTo = $this->getLinksTo();
1333
1334 if ( $wgUseSquid ) {
1335 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1336 array_push( $wgPostCommitUpdateList, $u );
1337 }
1338 Title::touchArray( $linksTo );
1339
1340 $log = new LogPage( 'upload' );
1341 $log->addEntry( 'upload', $descTitle, $desc );
1342
1343 return true;
1344 }
1345
1346 /**
1347 * Get an array of Title objects which are articles which use this image
1348 * Also adds their IDs to the link cache
1349 *
1350 * This is mostly copied from Title::getLinksTo()
1351 */
1352 function getLinksTo( $options = '' ) {
1353 global $wgLinkCache;
1354 $fname = 'Image::getLinksTo';
1355 wfProfileIn( $fname );
1356
1357 if ( $options ) {
1358 $db =& wfGetDB( DB_MASTER );
1359 } else {
1360 $db =& wfGetDB( DB_SLAVE );
1361 }
1362
1363 extract( $db->tableNames( 'page', 'imagelinks' ) );
1364 $encName = $db->addQuotes( $this->name );
1365 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1366 $res = $db->query( $sql, $fname );
1367
1368 $retVal = array();
1369 if ( $db->numRows( $res ) ) {
1370 while ( $row = $db->fetchObject( $res ) ) {
1371 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1372 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1373 $retVal[] = $titleObj;
1374 }
1375 }
1376 }
1377 $db->freeResult( $res );
1378 return $retVal;
1379 }
1380 /**
1381 * Retrive Exif data from the database
1382 *
1383 * Retrive Exif data from the database and prune unrecognized tags
1384 * and/or tags with invalid contents
1385 *
1386 * @return array
1387 */
1388 function retrieveExifData () {
1389 if ( $this->getMimeType() !== "image/jpeg" ) return array ();
1390
1391 $exif = exif_read_data( $this->imagePath );
1392 foreach($exif as $k => $v) {
1393 if ( !in_array($k, array_keys($this->exif->mFlatExif)) ) {
1394 wfDebug( "Image::retrieveExifData: '$k' is not a valid Exif tag (type: '" . gettype($v) . "'; data: '$v')\n");
1395 unset($exif[$k]);
1396 }
1397 }
1398
1399 foreach($exif as $k => $v) {
1400 if ( !$this->exif->validate($k, $v) ) {
1401 wfDebug( "Image::retrieveExifData: '$k' contained invalid data (type: '" . gettype($v) . "'; data: '$v')\n");
1402 unset($exif[$k]);
1403 }
1404 }
1405 return $exif;
1406 }
1407
1408 function getExifData () {
1409 global $wgRequest;
1410 if ( $this->metadata === '0' )
1411 return array();
1412
1413 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1414 $ret = unserialize ( $this->metadata );
1415
1416 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1417 $newver = $this->exif->version();
1418
1419 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1420 $this->updateExifData( $newver );
1421 }
1422 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1423 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1424
1425 foreach($ret as $k => $v) {
1426 $ret[$k] = $this->exif->format($k, $v);
1427 }
1428
1429 return $ret;
1430 }
1431
1432 function updateExifData( $version ) {
1433 $fname = 'Image:updateExifData';
1434
1435 if ( $this->getImagePath() === false ) # Not a local image
1436 return;
1437
1438 # Get EXIF data from image
1439 $exif = $this->retrieveExifData();
1440 if ( count( $exif ) ) {
1441 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1442 $this->metadata = serialize( $exif );
1443 } else {
1444 $this->metadata = '0';
1445 }
1446
1447 # Update EXIF data in database
1448 $dbw =& wfGetDB( DB_MASTER );
1449
1450 $this->checkDBSchema($dbw);
1451
1452 $dbw->update( 'image',
1453 array( 'img_metadata' => $this->metadata ),
1454 array( 'img_name' => $this->name ),
1455 $fname
1456 );
1457 }
1458
1459 } //class
1460
1461
1462 /**
1463 * Returns the image directory of an image
1464 * If the directory does not exist, it is created.
1465 * The result is an absolute path.
1466 *
1467 * This function is called from thumb.php before Setup.php is included
1468 *
1469 * @param string $fname file name of the image file
1470 * @access public
1471 */
1472 function wfImageDir( $fname ) {
1473 global $wgUploadDirectory, $wgHashedUploadDirectory;
1474
1475 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1476
1477 $hash = md5( $fname );
1478 $oldumask = umask(0);
1479 $dest = $wgUploadDirectory . '/' . $hash{0};
1480 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1481 $dest .= '/' . substr( $hash, 0, 2 );
1482 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1483
1484 umask( $oldumask );
1485 return $dest;
1486 }
1487
1488 /**
1489 * Returns the image directory of an image's thubnail
1490 * If the directory does not exist, it is created.
1491 * The result is an absolute path.
1492 *
1493 * This function is called from thumb.php before Setup.php is included
1494 *
1495 * @param string $fname file name of the original image file
1496 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1497 * @param boolean $shared (optional) use the shared upload directory
1498 * @access public
1499 */
1500 function wfImageThumbDir( $fname, $shared = false ) {
1501 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1502 if ( Image::isHashed( $shared ) ) {
1503 $dir = "$base/$fname";
1504
1505 if ( !is_dir( $base ) ) {
1506 $oldumask = umask(0);
1507 @mkdir( $base, 0777 );
1508 umask( $oldumask );
1509 }
1510
1511 if ( ! is_dir( $dir ) ) {
1512 $oldumask = umask(0);
1513 @mkdir( $dir, 0777 );
1514 umask( $oldumask );
1515 }
1516 } else {
1517 $dir = $base;
1518 }
1519
1520 return $dir;
1521 }
1522
1523 /**
1524 * Old thumbnail directory, kept for conversion
1525 */
1526 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1527 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1528 }
1529
1530 /**
1531 * Returns the image directory of an image's old version
1532 * If the directory does not exist, it is created.
1533 * The result is an absolute path.
1534 *
1535 * This function is called from thumb.php before Setup.php is included
1536 *
1537 * @param string $fname file name of the thumbnail file, including file size prefix
1538 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1539 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1540 * @access public
1541 */
1542 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1543 global $wgUploadDirectory, $wgHashedUploadDirectory,
1544 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1545 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1546 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1547 if (!$hashdir) { return $dir.'/'.$subdir; }
1548 $hash = md5( $fname );
1549 $oldumask = umask(0);
1550
1551 # Suppress warning messages here; if the file itself can't
1552 # be written we'll worry about it then.
1553 wfSuppressWarnings();
1554
1555 $archive = $dir.'/'.$subdir;
1556 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1557 $archive .= '/' . $hash{0};
1558 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1559 $archive .= '/' . substr( $hash, 0, 2 );
1560 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1561
1562 wfRestoreWarnings();
1563 umask( $oldumask );
1564 return $archive;
1565 }
1566
1567
1568 /*
1569 * Return the hash path component of an image path (URL or filesystem),
1570 * e.g. "/3/3c/", or just "/" if hashing is not used.
1571 *
1572 * @param $dbkey The filesystem / database name of the file
1573 * @param $fromSharedDirectory Use the shared file repository? It may
1574 * use different hash settings from the local one.
1575 */
1576 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1577 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1578 global $wgHashedUploadDirectory;
1579
1580 if( Image::isHashed( $fromSharedDirectory ) ) {
1581 $hash = md5($dbkey);
1582 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1583 } else {
1584 return '/';
1585 }
1586 }
1587
1588 /**
1589 * Returns the image URL of an image's old version
1590 *
1591 * @param string $fname file name of the image file
1592 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1593 * @access public
1594 */
1595 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1596 global $wgUploadPath, $wgHashedUploadDirectory;
1597
1598 if ($wgHashedUploadDirectory) {
1599 $hash = md5( substr( $name, 15) );
1600 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1601 substr( $hash, 0, 2 ) . '/'.$name;
1602 } else {
1603 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1604 }
1605 return wfUrlencode($url);
1606 }
1607
1608 /**
1609 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1610 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1611 *
1612 * @param string $length
1613 * @return int Length in pixels
1614 */
1615 function wfScaleSVGUnit( $length ) {
1616 static $unitLength = array(
1617 'px' => 1.0,
1618 'pt' => 1.25,
1619 'pc' => 15.0,
1620 'mm' => 3.543307,
1621 'cm' => 35.43307,
1622 'in' => 90.0,
1623 '' => 1.0, // "User units" pixels by default
1624 '%' => 2.0, // Fake it!
1625 );
1626 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1627 $length = FloatVal( $matches[1] );
1628 $unit = $matches[2];
1629 return round( $length * $unitLength[$unit] );
1630 } else {
1631 // Assume pixels
1632 return round( FloatVal( $length ) );
1633 }
1634 }
1635
1636 /**
1637 * Compatible with PHP getimagesize()
1638 * @todo support gzipped SVGZ
1639 * @todo check XML more carefully
1640 * @todo sensible defaults
1641 *
1642 * @param string $filename
1643 * @return array
1644 */
1645 function wfGetSVGsize( $filename ) {
1646 $width = 256;
1647 $height = 256;
1648
1649 // Read a chunk of the file
1650 $f = fopen( $filename, "rt" );
1651 if( !$f ) return false;
1652 $chunk = fread( $f, 4096 );
1653 fclose( $f );
1654
1655 // Uber-crappy hack! Run through a real XML parser.
1656 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1657 return false;
1658 }
1659 $tag = $matches[1];
1660 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1661 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1662 }
1663 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1664 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1665 }
1666
1667 return array( $width, $height, 'SVG',
1668 "width=\"$width\" height=\"$height\"" );
1669 }
1670
1671 /**
1672 * Determine if an image exists on the 'bad image list'
1673 *
1674 * @param string $name The image to check
1675 * @return bool
1676 */
1677 function wfIsBadImage( $name ) {
1678 global $wgContLang;
1679 static $titleList = false;
1680 if ( $titleList === false ) {
1681 $titleList = array();
1682
1683 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1684 foreach ( $lines as $line ) {
1685 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE ) . ':.*?)\]{2}/', $line, $m ) ) {
1686 $t = Title::newFromText( $m[1] );
1687 $titleList[$t->getDBkey()] = 1;
1688 }
1689 }
1690 }
1691
1692 return array_key_exists( $name, $titleList );
1693 }
1694
1695
1696
1697 /**
1698 * Wrapper class for thumbnail images
1699 * @package MediaWiki
1700 */
1701 class ThumbnailImage {
1702 /**
1703 * @param string $path Filesystem path to the thumb
1704 * @param string $url URL path to the thumb
1705 * @access private
1706 */
1707 function ThumbnailImage( $url, $width, $height, $path = false ) {
1708 $this->url = $url;
1709 $this->width = $width;
1710 $this->height = $height;
1711 $this->path = $path;
1712 }
1713
1714 /**
1715 * @return string The thumbnail URL
1716 */
1717 function getUrl() {
1718 return $this->url;
1719 }
1720
1721 /**
1722 * Return HTML <img ... /> tag for the thumbnail, will include
1723 * width and height attributes and a blank alt text (as required).
1724 *
1725 * You can set or override additional attributes by passing an
1726 * associative array of name => data pairs. The data will be escaped
1727 * for HTML output, so should be in plaintext.
1728 *
1729 * @param array $attribs
1730 * @return string
1731 * @access public
1732 */
1733 function toHtml( $attribs = array() ) {
1734 $attribs['src'] = $this->url;
1735 $attribs['width'] = $this->width;
1736 $attribs['height'] = $this->height;
1737 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1738
1739 $html = '<img ';
1740 foreach( $attribs as $name => $data ) {
1741 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1742 }
1743 $html .= '/>';
1744 return $html;
1745 }
1746
1747 }
1748 ?>