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