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