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