No current need for an alias to getPath()
[lhc/web/wiklou.git] / includes / filerepo / File.php
1 <?php
2 /**
3 * Base code for files.
4 *
5 * @file
6 * @ingroup FileRepo
7 */
8
9 /**
10 * Implements some public methods and some protected utility functions which
11 * are required by multiple child classes. Contains stub functionality for
12 * unimplemented public methods.
13 *
14 * Stub functions which should be overridden are marked with STUB. Some more
15 * concrete functions are also typically overridden by child classes.
16 *
17 * Note that only the repo object knows what its file class is called. You should
18 * never name a file class explictly outside of the repo class. Instead use the
19 * repo's factory functions to generate file objects, for example:
20 *
21 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
22 *
23 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
24 * in most cases.
25 *
26 * @ingroup FileRepo
27 */
28 abstract class File {
29 const DELETED_FILE = 1;
30 const DELETED_COMMENT = 2;
31 const DELETED_USER = 4;
32 const DELETED_RESTRICTED = 8;
33 const RENDER_NOW = 1;
34
35 const DELETE_SOURCE = 1;
36
37 /**
38 * Some member variables can be lazy-initialised using __get(). The
39 * initialisation function for these variables is always a function named
40 * like getVar(), where Var is the variable name with upper-case first
41 * letter.
42 *
43 * The following variables are initialised in this way in this base class:
44 * name, extension, handler, path, canRender, isSafeFile,
45 * transformScript, hashPath, pageCount, url
46 *
47 * Code within this class should generally use the accessor function
48 * directly, since __get() isn't re-entrant and therefore causes bugs that
49 * depend on initialisation order.
50 */
51
52 /**
53 * The following member variables are not lazy-initialised
54 */
55
56 /**
57 * @var LocalRepo
58 */
59 var $repo;
60
61 /**
62 * @var Title
63 */
64 var $title;
65
66 var $lastError, $redirected, $redirectedTitle;
67
68 /**
69 * @var MediaHandler
70 */
71 protected $handler;
72
73 /**
74 * Call this constructor from child classes
75 */
76 function __construct( $title, $repo ) {
77 $this->title = $title;
78 $this->repo = $repo;
79 }
80
81 function __get( $name ) {
82 $function = array( $this, 'get' . ucfirst( $name ) );
83 if ( !is_callable( $function ) ) {
84 return null;
85 } else {
86 $this->$name = call_user_func( $function );
87 return $this->$name;
88 }
89 }
90
91 /**
92 * Normalize a file extension to the common form, and ensure it's clean.
93 * Extensions with non-alphanumeric characters will be discarded.
94 *
95 * @param $ext string (without the .)
96 * @return string
97 */
98 static function normalizeExtension( $ext ) {
99 $lower = strtolower( $ext );
100 $squish = array(
101 'htm' => 'html',
102 'jpeg' => 'jpg',
103 'mpeg' => 'mpg',
104 'tiff' => 'tif',
105 'ogv' => 'ogg' );
106 if( isset( $squish[$lower] ) ) {
107 return $squish[$lower];
108 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
109 return $lower;
110 } else {
111 return '';
112 }
113 }
114
115 /**
116 * Checks if file extensions are compatible
117 *
118 * @param $old File Old file
119 * @param $new string New name
120 */
121 static function checkExtensionCompatibility( File $old, $new ) {
122 $oldMime = $old->getMimeType();
123 $n = strrpos( $new, '.' );
124 $newExt = self::normalizeExtension(
125 $n ? substr( $new, $n + 1 ) : '' );
126 $mimeMagic = MimeMagic::singleton();
127 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
128 }
129
130 /**
131 * Upgrade the database row if there is one
132 * Called by ImagePage
133 * STUB
134 */
135 function upgradeRow() {}
136
137 /**
138 * Split an internet media type into its two components; if not
139 * a two-part name, set the minor type to 'unknown'.
140 *
141 * @param string $mime "text/html" etc
142 * @return array ("text", "html") etc
143 */
144 public static function splitMime( $mime ) {
145 if( strpos( $mime, '/' ) !== false ) {
146 return explode( '/', $mime, 2 );
147 } else {
148 return array( $mime, 'unknown' );
149 }
150 }
151
152 /**
153 * Return the name of this file
154 */
155 public function getName() {
156 if ( !isset( $this->name ) ) {
157 $this->name = $this->repo->getNameFromTitle( $this->title );
158 }
159 return $this->name;
160 }
161
162 /**
163 * Get the file extension, e.g. "svg"
164 */
165 function getExtension() {
166 if ( !isset( $this->extension ) ) {
167 $n = strrpos( $this->getName(), '.' );
168 $this->extension = self::normalizeExtension(
169 $n ? substr( $this->getName(), $n + 1 ) : '' );
170 }
171 return $this->extension;
172 }
173
174 /**
175 * Return the associated title object
176 * @return Title
177 */
178 public function getTitle() { return $this->title; }
179
180 /**
181 * Return the title used to find this file
182 */
183 public function getOriginalTitle() {
184 if ( $this->redirected )
185 return $this->getRedirectedTitle();
186 return $this->title;
187 }
188
189 /**
190 * Return the URL of the file
191 */
192 public function getUrl() {
193 if ( !isset( $this->url ) ) {
194 $this->url = $this->repo->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
195 }
196 return $this->url;
197 }
198
199 /**
200 * Return a fully-qualified URL to the file.
201 * Upload URL paths _may or may not_ be fully qualified, so
202 * we check. Local paths are assumed to belong on $wgServer.
203 *
204 * @return String
205 */
206 public function getFullUrl() {
207 return wfExpandUrl( $this->getUrl() );
208 }
209
210 function getViewURL() {
211 if( $this->mustRender()) {
212 if( $this->canRender() ) {
213 return $this->createThumb( $this->getWidth() );
214 }
215 else {
216 wfDebug(__METHOD__.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
217 return $this->getURL(); #hm... return NULL?
218 }
219 } else {
220 return $this->getURL();
221 }
222 }
223
224 /**
225 * Return the full filesystem path to the file. Note that this does
226 * not mean that a file actually exists under that location.
227 *
228 * This path depends on whether directory hashing is active or not,
229 * i.e. whether the files are all found in the same directory,
230 * or in hashed paths like /images/3/3c.
231 *
232 * May return false if the file is not locally accessible.
233 */
234 public function getPath() {
235 if ( !isset( $this->path ) ) {
236 $this->path = $this->repo->getZonePath('public') . '/' . $this->getRel();
237 }
238 return $this->path;
239 }
240
241 /**
242 * Alias for getPath()
243 *
244 * @deprecated Use getPath().
245 */
246 public function getFullPath() {
247 wfDeprecated( __METHOD__ );
248 return $this->getPath();
249 }
250
251 /**
252 * Return the width of the image. Returns false if the width is unknown
253 * or undefined.
254 *
255 * STUB
256 * Overridden by LocalFile, UnregisteredLocalFile
257 */
258 public function getWidth( $page = 1 ) { return false; }
259
260 /**
261 * Return the height of the image. Returns false if the height is unknown
262 * or undefined
263 *
264 * STUB
265 * Overridden by LocalFile, UnregisteredLocalFile
266 */
267 public function getHeight( $page = 1 ) { return false; }
268
269 /**
270 * Returns ID or name of user who uploaded the file
271 * STUB
272 *
273 * @param $type string 'text' or 'id'
274 */
275 public function getUser( $type='text' ) { return null; }
276
277 /**
278 * Get the duration of a media file in seconds
279 */
280 public function getLength() {
281 $handler = $this->getHandler();
282 if ( $handler ) {
283 return $handler->getLength( $this );
284 } else {
285 return 0;
286 }
287 }
288
289 /**
290 * Return true if the file is vectorized
291 */
292 public function isVectorized() {
293 $handler = $this->getHandler();
294 if ( $handler ) {
295 return $handler->isVectorized( $this );
296 } else {
297 return false;
298 }
299 }
300
301
302 /**
303 * Get handler-specific metadata
304 * Overridden by LocalFile, UnregisteredLocalFile
305 * STUB
306 */
307 public function getMetadata() { return false; }
308
309 /**
310 * get versioned metadata
311 *
312 * @param $metadata Mixed Array or String of (serialized) metadata
313 * @param $version integer version number.
314 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
315 */
316 public function convertMetadataVersion($metadata, $version) {
317 $handler = $this->getHandler();
318 if ( !is_array( $metadata ) ) {
319 //just to make the return type consistant
320 $metadata = unserialize( $metadata );
321 }
322 if ( $handler ) {
323 return $handler->convertMetadataVersion( $metadata, $version );
324 } else {
325 return $metadata;
326 }
327 }
328
329 /**
330 * Return the bit depth of the file
331 * Overridden by LocalFile
332 * STUB
333 */
334 public function getBitDepth() { return 0; }
335
336 /**
337 * Return the size of the image file, in bytes
338 * Overridden by LocalFile, UnregisteredLocalFile
339 * STUB
340 */
341 public function getSize() { return false; }
342
343 /**
344 * Returns the mime type of the file.
345 * Overridden by LocalFile, UnregisteredLocalFile
346 * STUB
347 */
348 function getMimeType() { return 'unknown/unknown'; }
349
350 /**
351 * Return the type of the media in the file.
352 * Use the value returned by this function with the MEDIATYPE_xxx constants.
353 * Overridden by LocalFile,
354 * STUB
355 */
356 function getMediaType() { return MEDIATYPE_UNKNOWN; }
357
358 /**
359 * Checks if the output of transform() for this file is likely
360 * to be valid. If this is false, various user elements will
361 * display a placeholder instead.
362 *
363 * Currently, this checks if the file is an image format
364 * that can be converted to a format
365 * supported by all browsers (namely GIF, PNG and JPEG),
366 * or if it is an SVG image and SVG conversion is enabled.
367 */
368 function canRender() {
369 if ( !isset( $this->canRender ) ) {
370 $this->canRender = $this->getHandler() && $this->handler->canRender( $this );
371 }
372 return $this->canRender;
373 }
374
375 /**
376 * Accessor for __get()
377 */
378 protected function getCanRender() {
379 return $this->canRender();
380 }
381
382 /**
383 * Return true if the file is of a type that can't be directly
384 * rendered by typical browsers and needs to be re-rasterized.
385 *
386 * This returns true for everything but the bitmap types
387 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
388 * also return true for any non-image formats.
389 *
390 * @return bool
391 */
392 function mustRender() {
393 return $this->getHandler() && $this->handler->mustRender( $this );
394 }
395
396 /**
397 * Alias for canRender()
398 */
399 function allowInlineDisplay() {
400 return $this->canRender();
401 }
402
403 /**
404 * Determines if this media file is in a format that is unlikely to
405 * contain viruses or malicious content. It uses the global
406 * $wgTrustedMediaFormats list to determine if the file is safe.
407 *
408 * This is used to show a warning on the description page of non-safe files.
409 * It may also be used to disallow direct [[media:...]] links to such files.
410 *
411 * Note that this function will always return true if allowInlineDisplay()
412 * or isTrustedFile() is true for this file.
413 */
414 function isSafeFile() {
415 if ( !isset( $this->isSafeFile ) ) {
416 $this->isSafeFile = $this->_getIsSafeFile();
417 }
418 return $this->isSafeFile;
419 }
420
421 /** Accessor for __get() */
422 protected function getIsSafeFile() {
423 return $this->isSafeFile();
424 }
425
426 /** Uncached accessor */
427 protected function _getIsSafeFile() {
428 if ($this->allowInlineDisplay()) return true;
429 if ($this->isTrustedFile()) return true;
430
431 global $wgTrustedMediaFormats;
432
433 $type= $this->getMediaType();
434 $mime= $this->getMimeType();
435 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
436
437 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
438 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
439
440 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
441 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
442
443 return false;
444 }
445
446 /** Returns true if the file is flagged as trusted. Files flagged that way
447 * can be linked to directly, even if that is not allowed for this type of
448 * file normally.
449 *
450 * This is a dummy function right now and always returns false. It could be
451 * implemented to extract a flag from the database. The trusted flag could be
452 * set on upload, if the user has sufficient privileges, to bypass script-
453 * and html-filters. It may even be coupled with cryptographics signatures
454 * or such.
455 */
456 function isTrustedFile() {
457 #this could be implemented to check a flag in the databas,
458 #look for signatures, etc
459 return false;
460 }
461
462 /**
463 * Returns true if file exists in the repository.
464 *
465 * Overridden by LocalFile to avoid unnecessary stat calls.
466 *
467 * @return boolean Whether file exists in the repository.
468 */
469 public function exists() {
470 return $this->getPath() && file_exists( $this->path );
471 }
472
473 /**
474 * Returns true if file exists in the repository and can be included in a page.
475 * It would be unsafe to include private images, making public thumbnails inadvertently
476 *
477 * @return boolean Whether file exists in the repository and is includable.
478 */
479 public function isVisible() {
480 return $this->exists();
481 }
482
483 function getTransformScript() {
484 if ( !isset( $this->transformScript ) ) {
485 $this->transformScript = false;
486 if ( $this->repo ) {
487 $script = $this->repo->getThumbScriptUrl();
488 if ( $script ) {
489 $this->transformScript = "$script?f=" . urlencode( $this->getName() );
490 }
491 }
492 }
493 return $this->transformScript;
494 }
495
496 /**
497 * Get a ThumbnailImage which is the same size as the source
498 */
499 function getUnscaledThumb( $handlerParams = array() ) {
500 $hp =& $handlerParams;
501 $page = isset( $hp['page'] ) ? $hp['page'] : false;
502 $width = $this->getWidth( $page );
503 if ( !$width ) {
504 return $this->iconThumb();
505 }
506 $hp['width'] = $width;
507 return $this->transform( $hp );
508 }
509
510 /**
511 * Return the file name of a thumbnail with the specified parameters
512 *
513 * @param $params Array: handler-specific parameters
514 * @private -ish
515 */
516 function thumbName( $params ) {
517 return $this->generateThumbName( $this->getName(), $params );
518 }
519
520 /**
521 * Generate a thumbnail file name from a name and specified parameters
522 *
523 * @param string $name
524 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
525 */
526 function generateThumbName( $name, $params ) {
527 if ( !$this->getHandler() ) {
528 return null;
529 }
530 $extension = $this->getExtension();
531 list( $thumbExt, $thumbMime ) = $this->handler->getThumbType( $extension, $this->getMimeType(), $params );
532 $thumbName = $this->handler->makeParamString( $params ) . '-' . $name;
533 if ( $thumbExt != $extension ) {
534 $thumbName .= ".$thumbExt";
535 }
536 return $thumbName;
537 }
538
539 /**
540 * Create a thumbnail of the image having the specified width/height.
541 * The thumbnail will not be created if the width is larger than the
542 * image's width. Let the browser do the scaling in this case.
543 * The thumbnail is stored on disk and is only computed if the thumbnail
544 * file does not exist OR if it is older than the image.
545 * Returns the URL.
546 *
547 * Keeps aspect ratio of original image. If both width and height are
548 * specified, the generated image will be no bigger than width x height,
549 * and will also have correct aspect ratio.
550 *
551 * @param $width Integer: maximum width of the generated thumbnail
552 * @param $height Integer: maximum height of the image (optional)
553 */
554 public function createThumb( $width, $height = -1 ) {
555 $params = array( 'width' => $width );
556 if ( $height != -1 ) {
557 $params['height'] = $height;
558 }
559 $thumb = $this->transform( $params );
560 if( is_null( $thumb ) || $thumb->isError() ) return '';
561 return $thumb->getUrl();
562 }
563
564 /**
565 * Transform a media file
566 *
567 * @param $params Array: an associative array of handler-specific parameters.
568 * Typical keys are width, height and page.
569 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
570 * @return MediaTransformOutput | false
571 */
572 function transform( $params, $flags = 0 ) {
573 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
574
575 wfProfileIn( __METHOD__ );
576 do {
577 if ( !$this->canRender() ) {
578 // not a bitmap or renderable image, don't try.
579 $thumb = $this->iconThumb();
580 break;
581 }
582
583 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
584 $descriptionUrl = $this->getDescriptionUrl();
585 if ( $descriptionUrl ) {
586 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
587 }
588
589 $script = $this->getTransformScript();
590 if ( $script && !($flags & self::RENDER_NOW) ) {
591 // Use a script to transform on client request, if possible
592 $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
593 if( $thumb ) {
594 break;
595 }
596 }
597
598 $normalisedParams = $params;
599 $this->handler->normaliseParams( $this, $normalisedParams );
600 $thumbName = $this->thumbName( $normalisedParams );
601 $thumbPath = $this->getThumbPath( $thumbName );
602 $thumbUrl = $this->getThumbUrl( $thumbName );
603
604 if ( $this->repo && $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
605 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
606 break;
607 }
608
609 wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
610 $this->migrateThumbFile( $thumbName );
611 if ( file_exists( $thumbPath )) {
612 $thumbTime = filemtime( $thumbPath );
613 if ( $thumbTime !== FALSE &&
614 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
615
616 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
617 break;
618 }
619 }
620 $thumb = $this->handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
621
622 // Ignore errors if requested
623 if ( !$thumb ) {
624 $thumb = null;
625 } elseif ( $thumb->isError() ) {
626 $this->lastError = $thumb->toText();
627 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
628 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
629 }
630 }
631
632 // Purge. Useful in the event of Core -> Squid connection failure or squid
633 // purge collisions from elsewhere during failure. Don't keep triggering for
634 // "thumbs" which have the main image URL though (bug 13776)
635 if ( $wgUseSquid && ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL()) ) {
636 SquidUpdate::purge( array( $thumbUrl ) );
637 }
638 } while (false);
639
640 wfProfileOut( __METHOD__ );
641 return is_object( $thumb ) ? $thumb : false;
642 }
643
644 /**
645 * Hook into transform() to allow migration of thumbnail files
646 * STUB
647 * Overridden by LocalFile
648 */
649 function migrateThumbFile( $thumbName ) {}
650
651 /**
652 * Get a MediaHandler instance for this file
653 * @return MediaHandler
654 */
655 function getHandler() {
656 if ( !isset( $this->handler ) ) {
657 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
658 }
659 return $this->handler;
660 }
661
662 /**
663 * Get a ThumbnailImage representing a file type icon
664 * @return ThumbnailImage
665 */
666 function iconThumb() {
667 global $wgStylePath, $wgStyleDirectory;
668
669 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
670 foreach( $try as $icon ) {
671 $path = '/common/images/icons/' . $icon;
672 $filepath = $wgStyleDirectory . $path;
673 if( file_exists( $filepath ) ) {
674 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
675 }
676 }
677 return null;
678 }
679
680 /**
681 * Get last thumbnailing error.
682 * Largely obsolete.
683 */
684 function getLastError() {
685 return $this->lastError;
686 }
687
688 /**
689 * Get all thumbnail names previously generated for this file
690 * STUB
691 * Overridden by LocalFile
692 */
693 function getThumbnails() { return array(); }
694
695 /**
696 * Purge shared caches such as thumbnails and DB data caching
697 * STUB
698 * Overridden by LocalFile
699 */
700 function purgeCache() {}
701
702 /**
703 * Purge the file description page, but don't go after
704 * pages using the file. Use when modifying file history
705 * but not the current data.
706 */
707 function purgeDescription() {
708 $title = $this->getTitle();
709 if ( $title ) {
710 $title->invalidateCache();
711 $title->purgeSquid();
712 }
713 }
714
715 /**
716 * Purge metadata and all affected pages when the file is created,
717 * deleted, or majorly updated.
718 */
719 function purgeEverything() {
720 // Delete thumbnails and refresh file metadata cache
721 $this->purgeCache();
722 $this->purgeDescription();
723
724 // Purge cache of all pages using this file
725 $title = $this->getTitle();
726 if ( $title ) {
727 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
728 $update->doUpdate();
729 }
730 }
731
732 /**
733 * Return a fragment of the history of file.
734 *
735 * STUB
736 * @param $limit integer Limit of rows to return
737 * @param $start timestamp Only revisions older than $start will be returned
738 * @param $end timestamp Only revisions newer than $end will be returned
739 * @param $inc bool Include the endpoints of the time range
740 */
741 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
742 return array();
743 }
744
745 /**
746 * Return the history of this file, line by line. Starts with current version,
747 * then old versions. Should return an object similar to an image/oldimage
748 * database row.
749 *
750 * STUB
751 * Overridden in LocalFile
752 */
753 public function nextHistoryLine() {
754 return false;
755 }
756
757 /**
758 * Reset the history pointer to the first element of the history.
759 * Always call this function after using nextHistoryLine() to free db resources
760 * STUB
761 * Overridden in LocalFile.
762 */
763 public function resetHistory() {}
764
765 /**
766 * Get the filename hash component of the directory including trailing slash,
767 * e.g. f/fa/
768 * If the repository is not hashed, returns an empty string.
769 */
770 function getHashPath() {
771 if ( !isset( $this->hashPath ) ) {
772 $this->hashPath = $this->repo->getHashPath( $this->getName() );
773 }
774 return $this->hashPath;
775 }
776
777 /**
778 * Get the path of the file relative to the public zone root
779 */
780 function getRel() {
781 return $this->getHashPath() . $this->getName();
782 }
783
784 /**
785 * Get urlencoded relative path of the file
786 */
787 function getUrlRel() {
788 return $this->getHashPath() . rawurlencode( $this->getName() );
789 }
790
791 /** Get the relative path for an archive file */
792 function getArchiveRel( $suffix = false ) {
793 $path = 'archive/' . $this->getHashPath();
794 if ( $suffix === false ) {
795 $path = substr( $path, 0, -1 );
796 } else {
797 $path .= $suffix;
798 }
799 return $path;
800 }
801
802 /** Get the path of the archive directory, or a particular file if $suffix is specified */
803 function getArchivePath( $suffix = false ) {
804 return $this->repo->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
805 }
806
807 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
808 function getThumbPath( $suffix = false ) {
809 $path = $this->repo->getZonePath('thumb') . '/' . $this->getRel();
810 if ( $suffix !== false ) {
811 $path .= '/' . $suffix;
812 }
813 return $path;
814 }
815
816 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
817 function getArchiveUrl( $suffix = false ) {
818 $path = $this->repo->getZoneUrl('public') . '/archive/' . $this->getHashPath();
819 if ( $suffix === false ) {
820 $path = substr( $path, 0, -1 );
821 } else {
822 $path .= rawurlencode( $suffix );
823 }
824 return $path;
825 }
826
827 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
828 function getThumbUrl( $suffix = false ) {
829 $path = $this->repo->getZoneUrl('thumb') . '/' . $this->getUrlRel();
830 if ( $suffix !== false ) {
831 $path .= '/' . rawurlencode( $suffix );
832 }
833 return $path;
834 }
835
836 /** Get the virtual URL for an archive file or directory */
837 function getArchiveVirtualUrl( $suffix = false ) {
838 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
839 if ( $suffix === false ) {
840 $path = substr( $path, 0, -1 );
841 } else {
842 $path .= rawurlencode( $suffix );
843 }
844 return $path;
845 }
846
847 /** Get the virtual URL for a thumbnail file or directory */
848 function getThumbVirtualUrl( $suffix = false ) {
849 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
850 if ( $suffix !== false ) {
851 $path .= '/' . rawurlencode( $suffix );
852 }
853 return $path;
854 }
855
856 /** Get the virtual URL for the file itself */
857 function getVirtualUrl( $suffix = false ) {
858 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
859 if ( $suffix !== false ) {
860 $path .= '/' . rawurlencode( $suffix );
861 }
862 return $path;
863 }
864
865 /**
866 * @return bool
867 */
868 function isHashed() {
869 return $this->repo->isHashed();
870 }
871
872 function readOnlyError() {
873 throw new MWException( get_class($this) . ': write operations are not supported' );
874 }
875
876 /**
877 * Record a file upload in the upload log and the image table
878 * STUB
879 * Overridden by LocalFile
880 */
881 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
882 $this->readOnlyError();
883 }
884
885 /**
886 * Move or copy a file to its public location. If a file exists at the
887 * destination, move it to an archive. Returns a FileRepoStatus object with
888 * the archive name in the "value" member on success.
889 *
890 * The archive name should be passed through to recordUpload for database
891 * registration.
892 *
893 * @param $srcPath String: local filesystem path to the source image
894 * @param $flags Integer: a bitwise combination of:
895 * File::DELETE_SOURCE Delete the source file, i.e. move
896 * rather than copy
897 * @return FileRepoStatus object. On success, the value member contains the
898 * archive name, or an empty string if it was a new file.
899 *
900 * STUB
901 * Overridden by LocalFile
902 */
903 function publish( $srcPath, $flags = 0 ) {
904 $this->readOnlyError();
905 }
906
907 /**
908 * Get an array of Title objects which are articles which use this file
909 * Also adds their IDs to the link cache
910 *
911 * This is mostly copied from Title::getLinksTo()
912 *
913 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
914 */
915 function getLinksTo( $options = array() ) {
916 wfDeprecated( __METHOD__ );
917 wfProfileIn( __METHOD__ );
918
919 // Note: use local DB not repo DB, we want to know local links
920 if ( count( $options ) > 0 ) {
921 $db = wfGetDB( DB_MASTER );
922 } else {
923 $db = wfGetDB( DB_SLAVE );
924 }
925 $linkCache = LinkCache::singleton();
926
927 $encName = $db->addQuotes( $this->getName() );
928 $res = $db->select( array( 'page', 'imagelinks'),
929 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
930 array( 'page_id=il_from', 'il_to' => $encName ),
931 __METHOD__,
932 $options );
933
934 $retVal = array();
935 if ( $db->numRows( $res ) ) {
936 foreach ( $res as $row ) {
937 $titleObj = Title::newFromRow( $row );
938 if ( $titleObj ) {
939 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
940 $retVal[] = $titleObj;
941 }
942 }
943 }
944 wfProfileOut( __METHOD__ );
945 return $retVal;
946 }
947
948 function formatMetadata() {
949 if ( !$this->getHandler() ) {
950 return false;
951 }
952 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
953 }
954
955 /**
956 * Returns true if the file comes from the local file repository.
957 *
958 * @return bool
959 */
960 function isLocal() {
961 $repo = $this->getRepo();
962 return $repo && $repo->isLocal();
963 }
964
965 /**
966 * Returns the name of the repository.
967 *
968 * @return string
969 */
970 function getRepoName() {
971 return $this->repo ? $this->repo->getName() : 'unknown';
972 }
973 /*
974 * Returns the repository
975 */
976 function getRepo() {
977 return $this->repo;
978 }
979
980 /**
981 * Returns true if the image is an old version
982 * STUB
983 */
984 function isOld() {
985 return false;
986 }
987
988 /**
989 * Is this file a "deleted" file in a private archive?
990 * STUB
991 */
992 function isDeleted( $field ) {
993 return false;
994 }
995
996 /**
997 * Return the deletion bitfield
998 * STUB
999 */
1000 function getVisibility() {
1001 return 0;
1002 }
1003
1004 /**
1005 * Was this file ever deleted from the wiki?
1006 *
1007 * @return bool
1008 */
1009 function wasDeleted() {
1010 $title = $this->getTitle();
1011 return $title && $title->isDeletedQuick();
1012 }
1013
1014 /**
1015 * Move file to the new title
1016 *
1017 * Move current, old version and all thumbnails
1018 * to the new filename. Old file is deleted.
1019 *
1020 * Cache purging is done; checks for validity
1021 * and logging are caller's responsibility
1022 *
1023 * @param $target Title New file name
1024 * @return FileRepoStatus object.
1025 */
1026 function move( $target ) {
1027 $this->readOnlyError();
1028 }
1029
1030 /**
1031 * Delete all versions of the file.
1032 *
1033 * Moves the files into an archive directory (or deletes them)
1034 * and removes the database rows.
1035 *
1036 * Cache purging is done; logging is caller's responsibility.
1037 *
1038 * @param $reason String
1039 * @param $suppress Boolean: hide content from sysops?
1040 * @return true on success, false on some kind of failure
1041 * STUB
1042 * Overridden by LocalFile
1043 */
1044 function delete( $reason, $suppress = false ) {
1045 $this->readOnlyError();
1046 }
1047
1048 /**
1049 * Restore all or specified deleted revisions to the given file.
1050 * Permissions and logging are left to the caller.
1051 *
1052 * May throw database exceptions on error.
1053 *
1054 * @param $versions set of record ids of deleted items to restore,
1055 * or empty to restore all revisions.
1056 * @param $unsuppress remove restrictions on content upon restoration?
1057 * @return the number of file revisions restored if successful,
1058 * or false on failure
1059 * STUB
1060 * Overridden by LocalFile
1061 */
1062 function restore( $versions=array(), $unsuppress=false ) {
1063 $this->readOnlyError();
1064 }
1065
1066 /**
1067 * Returns 'true' if this file is a type which supports multiple pages,
1068 * e.g. DJVU or PDF. Note that this may be true even if the file in
1069 * question only has a single page.
1070 *
1071 * @return Bool
1072 */
1073 function isMultipage() {
1074 return $this->getHandler() && $this->handler->isMultiPage( $this );
1075 }
1076
1077 /**
1078 * Returns the number of pages of a multipage document, or false for
1079 * documents which aren't multipage documents
1080 */
1081 function pageCount() {
1082 if ( !isset( $this->pageCount ) ) {
1083 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1084 $this->pageCount = $this->handler->pageCount( $this );
1085 } else {
1086 $this->pageCount = false;
1087 }
1088 }
1089 return $this->pageCount;
1090 }
1091
1092 /**
1093 * Calculate the height of a thumbnail using the source and destination width
1094 */
1095 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1096 // Exact integer multiply followed by division
1097 if ( $srcWidth == 0 ) {
1098 return 0;
1099 } else {
1100 return round( $srcHeight * $dstWidth / $srcWidth );
1101 }
1102 }
1103
1104 /**
1105 * Get an image size array like that returned by getImageSize(), or false if it
1106 * can't be determined.
1107 *
1108 * @param $fileName String: The filename
1109 * @return Array
1110 */
1111 function getImageSize( $fileName ) {
1112 if ( !$this->getHandler() ) {
1113 return false;
1114 }
1115 return $this->handler->getImageSize( $this, $fileName );
1116 }
1117
1118 /**
1119 * Get the URL of the image description page. May return false if it is
1120 * unknown or not applicable.
1121 */
1122 function getDescriptionUrl() {
1123 return $this->repo->getDescriptionUrl( $this->getName() );
1124 }
1125
1126 /**
1127 * Get the HTML text of the description page, if available
1128 */
1129 function getDescriptionText() {
1130 global $wgMemc, $wgLang;
1131 if ( !$this->repo->fetchDescription ) {
1132 return false;
1133 }
1134 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1135 if ( $renderUrl ) {
1136 if ( $this->repo->descriptionCacheExpiry > 0 ) {
1137 wfDebug("Attempting to get the description from cache...");
1138 $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1139 $this->getName() );
1140 $obj = $wgMemc->get($key);
1141 if ($obj) {
1142 wfDebug("success!\n");
1143 return $obj;
1144 }
1145 wfDebug("miss\n");
1146 }
1147 wfDebug( "Fetching shared description from $renderUrl\n" );
1148 $res = Http::get( $renderUrl );
1149 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
1150 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
1151 }
1152 return $res;
1153 } else {
1154 return false;
1155 }
1156 }
1157
1158 /**
1159 * Get discription of file revision
1160 * STUB
1161 */
1162 function getDescription() {
1163 return null;
1164 }
1165
1166 /**
1167 * Get the 14-character timestamp of the file upload, or false if
1168 * it doesn't exist
1169 */
1170 function getTimestamp() {
1171 $path = $this->getPath();
1172 if ( !file_exists( $path ) ) {
1173 return false;
1174 }
1175 return wfTimestamp( TS_MW, filemtime( $path ) );
1176 }
1177
1178 /**
1179 * Get the SHA-1 base 36 hash of the file
1180 */
1181 function getSha1() {
1182 return self::sha1Base36( $this->getPath() );
1183 }
1184
1185 /**
1186 * Get the deletion archive key, <sha1>.<ext>
1187 */
1188 function getStorageKey() {
1189 $hash = $this->getSha1();
1190 if ( !$hash ) {
1191 return false;
1192 }
1193 $ext = $this->getExtension();
1194 $dotExt = $ext === '' ? '' : ".$ext";
1195 return $hash . $dotExt;
1196 }
1197
1198 /**
1199 * Determine if the current user is allowed to view a particular
1200 * field of this file, if it's marked as deleted.
1201 * STUB
1202 * @param $field Integer
1203 * @return Boolean
1204 */
1205 function userCan( $field ) {
1206 return true;
1207 }
1208
1209 /**
1210 * Get an associative array containing information about a file in the local filesystem.
1211 *
1212 * @param $path String: absolute local filesystem path
1213 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1214 * Set it to false to ignore the extension.
1215 */
1216 static function getPropsFromPath( $path, $ext = true ) {
1217 wfProfileIn( __METHOD__ );
1218 wfDebug( __METHOD__.": Getting file info for $path\n" );
1219 $info = array(
1220 'fileExists' => file_exists( $path ) && !is_dir( $path )
1221 );
1222 $gis = false;
1223 if ( $info['fileExists'] ) {
1224 $magic = MimeMagic::singleton();
1225
1226 if ( $ext === true ) {
1227 $i = strrpos( $path, '.' );
1228 $ext = strtolower( $i ? substr( $path, $i + 1 ) : '' );
1229 }
1230
1231 # mime type according to file contents
1232 $info['file-mime'] = $magic->guessMimeType( $path, false );
1233 # logical mime type
1234 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1235
1236 list( $info['major_mime'], $info['minor_mime'] ) = self::splitMime( $info['mime'] );
1237 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1238
1239 # Get size in bytes
1240 $info['size'] = filesize( $path );
1241
1242 # Height, width and metadata
1243 $handler = MediaHandler::getHandler( $info['mime'] );
1244 if ( $handler ) {
1245 $tempImage = (object)array();
1246 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1247 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1248 } else {
1249 $gis = false;
1250 $info['metadata'] = '';
1251 }
1252 $info['sha1'] = self::sha1Base36( $path );
1253
1254 wfDebug(__METHOD__.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1255 } else {
1256 $info['mime'] = null;
1257 $info['media_type'] = MEDIATYPE_UNKNOWN;
1258 $info['metadata'] = '';
1259 $info['sha1'] = '';
1260 wfDebug(__METHOD__.": $path NOT FOUND!\n");
1261 }
1262 if( $gis ) {
1263 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1264 $info['width'] = $gis[0];
1265 $info['height'] = $gis[1];
1266 if ( isset( $gis['bits'] ) ) {
1267 $info['bits'] = $gis['bits'];
1268 } else {
1269 $info['bits'] = 0;
1270 }
1271 } else {
1272 $info['width'] = 0;
1273 $info['height'] = 0;
1274 $info['bits'] = 0;
1275 }
1276 wfProfileOut( __METHOD__ );
1277 return $info;
1278 }
1279
1280 /**
1281 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1282 * encoding, zero padded to 31 digits.
1283 *
1284 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1285 * fairly neatly.
1286 *
1287 * Returns false on failure
1288 */
1289 static function sha1Base36( $path ) {
1290 wfSuppressWarnings();
1291 $hash = sha1_file( $path );
1292 wfRestoreWarnings();
1293 if ( $hash === false ) {
1294 return false;
1295 } else {
1296 return wfBaseConvert( $hash, 16, 36, 31 );
1297 }
1298 }
1299
1300 function getLongDesc() {
1301 $handler = $this->getHandler();
1302 if ( $handler ) {
1303 return $handler->getLongDesc( $this );
1304 } else {
1305 return MediaHandler::getGeneralLongDesc( $this );
1306 }
1307 }
1308
1309 function getShortDesc() {
1310 $handler = $this->getHandler();
1311 if ( $handler ) {
1312 return $handler->getShortDesc( $this );
1313 } else {
1314 return MediaHandler::getGeneralShortDesc( $this );
1315 }
1316 }
1317
1318 function getDimensionsString() {
1319 $handler = $this->getHandler();
1320 if ( $handler ) {
1321 return $handler->getDimensionsString( $this );
1322 } else {
1323 return '';
1324 }
1325 }
1326
1327 function getRedirected() {
1328 return $this->redirected;
1329 }
1330
1331 function getRedirectedTitle() {
1332 if ( $this->redirected ) {
1333 if ( !$this->redirectTitle ) {
1334 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
1335 }
1336 return $this->redirectTitle;
1337 }
1338 }
1339
1340 function redirectedFrom( $from ) {
1341 $this->redirected = $from;
1342 }
1343
1344 function isMissing() {
1345 return false;
1346 }
1347 }
1348 /**
1349 * Aliases for backwards compatibility with 1.6
1350 */
1351 define( 'MW_IMG_DELETED_FILE', File::DELETED_FILE );
1352 define( 'MW_IMG_DELETED_COMMENT', File::DELETED_COMMENT );
1353 define( 'MW_IMG_DELETED_USER', File::DELETED_USER );
1354 define( 'MW_IMG_DELETED_RESTRICTED', File::DELETED_RESTRICTED );