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