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