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