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