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