* Add redirect and size fields to title. Add accessors.
[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 /**
382 * Returns true if file exists in the repository and can be included in a page.
383 * It would be unsafe to include private images, making public thumbnails inadvertently
384 *
385 * @return boolean Whether file exists in the repository and is includable.
386 * @public
387 */
388 function isVisible() {
389 return $this->exists();
390 }
391
392 function getTransformScript() {
393 if ( !isset( $this->transformScript ) ) {
394 $this->transformScript = false;
395 if ( $this->repo ) {
396 $script = $this->repo->getThumbScriptUrl();
397 if ( $script ) {
398 $this->transformScript = "$script?f=" . urlencode( $this->getName() );
399 }
400 }
401 }
402 return $this->transformScript;
403 }
404
405 /**
406 * Get a ThumbnailImage which is the same size as the source
407 */
408 function getUnscaledThumb( $page = false ) {
409 $width = $this->getWidth( $page );
410 if ( !$width ) {
411 return $this->iconThumb();
412 }
413 if ( $page ) {
414 $params = array(
415 'page' => $page,
416 'width' => $this->getWidth( $page )
417 );
418 } else {
419 $params = array( 'width' => $this->getWidth() );
420 }
421 return $this->transform( $params );
422 }
423
424 /**
425 * Return the file name of a thumbnail with the specified parameters
426 *
427 * @param array $params Handler-specific parameters
428 * @private -ish
429 */
430 function thumbName( $params ) {
431 if ( !$this->getHandler() ) {
432 return null;
433 }
434 $extension = $this->getExtension();
435 list( $thumbExt, $thumbMime ) = $this->handler->getThumbType( $extension, $this->getMimeType() );
436 $thumbName = $this->handler->makeParamString( $params ) . '-' . $this->getName();
437 if ( $thumbExt != $extension ) {
438 $thumbName .= ".$thumbExt";
439 }
440 return $thumbName;
441 }
442
443 /**
444 * Create a thumbnail of the image having the specified width/height.
445 * The thumbnail will not be created if the width is larger than the
446 * image's width. Let the browser do the scaling in this case.
447 * The thumbnail is stored on disk and is only computed if the thumbnail
448 * file does not exist OR if it is older than the image.
449 * Returns the URL.
450 *
451 * Keeps aspect ratio of original image. If both width and height are
452 * specified, the generated image will be no bigger than width x height,
453 * and will also have correct aspect ratio.
454 *
455 * @param integer $width maximum width of the generated thumbnail
456 * @param integer $height maximum height of the image (optional)
457 */
458 public function createThumb( $width, $height = -1 ) {
459 $params = array( 'width' => $width );
460 if ( $height != -1 ) {
461 $params['height'] = $height;
462 }
463 $thumb = $this->transform( $params );
464 if( is_null( $thumb ) || $thumb->isError() ) return '';
465 return $thumb->getUrl();
466 }
467
468 /**
469 * As createThumb, but returns a ThumbnailImage object. This can
470 * provide access to the actual file, the real size of the thumb,
471 * and can produce a convenient <img> tag for you.
472 *
473 * For non-image formats, this may return a filetype-specific icon.
474 *
475 * @param integer $width maximum width of the generated thumbnail
476 * @param integer $height maximum height of the image (optional)
477 * @param boolean $render True to render the thumbnail if it doesn't exist,
478 * false to just return the URL
479 *
480 * @return ThumbnailImage or null on failure
481 *
482 * @deprecated use transform()
483 */
484 public function getThumbnail( $width, $height=-1, $render = true ) {
485 $params = array( 'width' => $width );
486 if ( $height != -1 ) {
487 $params['height'] = $height;
488 }
489 $flags = $render ? self::RENDER_NOW : 0;
490 return $this->transform( $params, $flags );
491 }
492
493 /**
494 * Transform a media file
495 *
496 * @param array $params An associative array of handler-specific parameters. Typical
497 * keys are width, height and page.
498 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
499 * @return MediaTransformOutput
500 */
501 function transform( $params, $flags = 0 ) {
502 global $wgUseSquid, $wgIgnoreImageErrors;
503
504 wfProfileIn( __METHOD__ );
505 do {
506 if ( !$this->canRender() ) {
507 // not a bitmap or renderable image, don't try.
508 $thumb = $this->iconThumb();
509 break;
510 }
511
512 $script = $this->getTransformScript();
513 if ( $script && !($flags & self::RENDER_NOW) ) {
514 // Use a script to transform on client request, if possible
515 $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
516 if( $thumb ) {
517 break;
518 }
519 }
520
521 $normalisedParams = $params;
522 $this->handler->normaliseParams( $this, $normalisedParams );
523 $thumbName = $this->thumbName( $normalisedParams );
524 $thumbPath = $this->getThumbPath( $thumbName );
525 $thumbUrl = $this->getThumbUrl( $thumbName );
526
527 if ( $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
528 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
529 break;
530 }
531
532 wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
533 $this->migrateThumbFile( $thumbName );
534 if ( file_exists( $thumbPath ) ) {
535 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
536 break;
537 }
538 $thumb = $this->handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
539
540 // Ignore errors if requested
541 if ( !$thumb ) {
542 $thumb = null;
543 } elseif ( $thumb->isError() ) {
544 $this->lastError = $thumb->toText();
545 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
546 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
547 }
548 }
549
550 if ( $wgUseSquid ) {
551 SquidUpdate::purge( array( $thumbUrl ) );
552 }
553 } while (false);
554
555 wfProfileOut( __METHOD__ );
556 return $thumb;
557 }
558
559 /**
560 * Hook into transform() to allow migration of thumbnail files
561 * STUB
562 * Overridden by LocalFile
563 */
564 function migrateThumbFile( $thumbName ) {}
565
566 /**
567 * Get a MediaHandler instance for this file
568 */
569 function getHandler() {
570 if ( !isset( $this->handler ) ) {
571 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
572 }
573 return $this->handler;
574 }
575
576 /**
577 * Get a ThumbnailImage representing a file type icon
578 * @return ThumbnailImage
579 */
580 function iconThumb() {
581 global $wgStylePath, $wgStyleDirectory;
582
583 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
584 foreach( $try as $icon ) {
585 $path = '/common/images/icons/' . $icon;
586 $filepath = $wgStyleDirectory . $path;
587 if( file_exists( $filepath ) ) {
588 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
589 }
590 }
591 return null;
592 }
593
594 /**
595 * Get last thumbnailing error.
596 * Largely obsolete.
597 */
598 function getLastError() {
599 return $this->lastError;
600 }
601
602 /**
603 * Get all thumbnail names previously generated for this file
604 * STUB
605 * Overridden by LocalFile
606 */
607 function getThumbnails() { return array(); }
608
609 /**
610 * Purge shared caches such as thumbnails and DB data caching
611 * STUB
612 * Overridden by LocalFile
613 */
614 function purgeCache() {}
615
616 /**
617 * Purge the file description page, but don't go after
618 * pages using the file. Use when modifying file history
619 * but not the current data.
620 */
621 function purgeDescription() {
622 $title = $this->getTitle();
623 if ( $title ) {
624 $title->invalidateCache();
625 $title->purgeSquid();
626 }
627 }
628
629 /**
630 * Purge metadata and all affected pages when the file is created,
631 * deleted, or majorly updated.
632 */
633 function purgeEverything() {
634 // Delete thumbnails and refresh file metadata cache
635 $this->purgeCache();
636 $this->purgeDescription();
637
638 // Purge cache of all pages using this file
639 $title = $this->getTitle();
640 if ( $title ) {
641 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
642 $update->doUpdate();
643 }
644 }
645
646 /**
647 * Return a fragment of the history of file.
648 *
649 * STUB
650 * @param $limit integer Limit of rows to return
651 * @param $start timestamp Only revisions older than $start will be returned
652 * @param $end timestamp Only revisions newer than $end will be returned
653 */
654 function getHistory($limit = null, $start = null, $end = null) {
655 return false;
656 }
657
658 /**
659 * Return the history of this file, line by line. Starts with current version,
660 * then old versions. Should return an object similar to an image/oldimage
661 * database row.
662 *
663 * STUB
664 * Overridden in LocalFile
665 */
666 public function nextHistoryLine() {
667 return false;
668 }
669
670 /**
671 * Reset the history pointer to the first element of the history.
672 * Always call this function after using nextHistoryLine() to free db resources
673 * STUB
674 * Overridden in LocalFile.
675 */
676 public function resetHistory() {}
677
678 /**
679 * Get the filename hash component of the directory including trailing slash,
680 * e.g. f/fa/
681 * If the repository is not hashed, returns an empty string.
682 */
683 function getHashPath() {
684 if ( !isset( $this->hashPath ) ) {
685 $this->hashPath = $this->repo->getHashPath( $this->getName() );
686 }
687 return $this->hashPath;
688 }
689
690 /**
691 * Get the path of the file relative to the public zone root
692 */
693 function getRel() {
694 return $this->getHashPath() . $this->getName();
695 }
696
697 /**
698 * Get urlencoded relative path of the file
699 */
700 function getUrlRel() {
701 return $this->getHashPath() . rawurlencode( $this->getName() );
702 }
703
704 /** Get the relative path for an archive file */
705 function getArchiveRel( $suffix = false ) {
706 $path = 'archive/' . $this->getHashPath();
707 if ( $suffix === false ) {
708 $path = substr( $path, 0, -1 );
709 } else {
710 $path .= $suffix;
711 }
712 return $path;
713 }
714
715 /** Get relative path for a thumbnail file */
716 function getThumbRel( $suffix = false ) {
717 $path = 'thumb/' . $this->getRel();
718 if ( $suffix !== false ) {
719 $path .= '/' . $suffix;
720 }
721 return $path;
722 }
723
724 /** Get the path of the archive directory, or a particular file if $suffix is specified */
725 function getArchivePath( $suffix = false ) {
726 return $this->repo->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
727 }
728
729 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
730 function getThumbPath( $suffix = false ) {
731 return $this->repo->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
732 }
733
734 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
735 function getArchiveUrl( $suffix = false ) {
736 $path = $this->repo->getZoneUrl('public') . '/archive/' . $this->getHashPath();
737 if ( $suffix === false ) {
738 $path = substr( $path, 0, -1 );
739 } else {
740 $path .= rawurlencode( $suffix );
741 }
742 return $path;
743 }
744
745 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
746 function getThumbUrl( $suffix = false ) {
747 $path = $this->repo->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
748 if ( $suffix !== false ) {
749 $path .= '/' . rawurlencode( $suffix );
750 }
751 return $path;
752 }
753
754 /** Get the virtual URL for an archive file or directory */
755 function getArchiveVirtualUrl( $suffix = false ) {
756 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
757 if ( $suffix === false ) {
758 $path = substr( $path, 0, -1 );
759 } else {
760 $path .= rawurlencode( $suffix );
761 }
762 return $path;
763 }
764
765 /** Get the virtual URL for a thumbnail file or directory */
766 function getThumbVirtualUrl( $suffix = false ) {
767 $path = $this->repo->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
768 if ( $suffix !== false ) {
769 $path .= '/' . rawurlencode( $suffix );
770 }
771 return $path;
772 }
773
774 /** Get the virtual URL for the file itself */
775 function getVirtualUrl( $suffix = false ) {
776 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
777 if ( $suffix !== false ) {
778 $path .= '/' . rawurlencode( $suffix );
779 }
780 return $path;
781 }
782
783 /**
784 * @return bool
785 */
786 function isHashed() {
787 return $this->repo->isHashed();
788 }
789
790 function readOnlyError() {
791 throw new MWException( get_class($this) . ': write operations are not supported' );
792 }
793
794 /**
795 * Record a file upload in the upload log and the image table
796 * STUB
797 * Overridden by LocalFile
798 */
799 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
800 $this->readOnlyError();
801 }
802
803 /**
804 * Move or copy a file to its public location. If a file exists at the
805 * destination, move it to an archive. Returns the archive name on success
806 * or an empty string if it was a new file, and a wikitext-formatted
807 * WikiError object on failure.
808 *
809 * The archive name should be passed through to recordUpload for database
810 * registration.
811 *
812 * @param string $sourcePath Local filesystem path to the source image
813 * @param integer $flags A bitwise combination of:
814 * File::DELETE_SOURCE Delete the source file, i.e. move
815 * rather than copy
816 * @return The archive name on success or an empty string if it was a new
817 * file, and a wikitext-formatted WikiError object on failure.
818 *
819 * STUB
820 * Overridden by LocalFile
821 */
822 function publish( $srcPath, $flags = 0 ) {
823 $this->readOnlyError();
824 }
825
826 /**
827 * Get an array of Title objects which are articles which use this file
828 * Also adds their IDs to the link cache
829 *
830 * This is mostly copied from Title::getLinksTo()
831 *
832 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
833 */
834 function getLinksTo( $options = '' ) {
835 wfProfileIn( __METHOD__ );
836
837 // Note: use local DB not repo DB, we want to know local links
838 if ( $options ) {
839 $db = wfGetDB( DB_MASTER );
840 } else {
841 $db = wfGetDB( DB_SLAVE );
842 }
843 $linkCache =& LinkCache::singleton();
844
845 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
846 $encName = $db->addQuotes( $this->getName() );
847 $sql = "SELECT page_namespace,page_title,page_id,page_len,page_is_redirect,
848 FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
849 $res = $db->query( $sql, __METHOD__ );
850
851 $retVal = array();
852 if ( $db->numRows( $res ) ) {
853 while ( $row = $db->fetchObject( $res ) ) {
854 if ( $titleObj = Title::newFromRow( $row ) ) {
855 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
856 $retVal[] = $titleObj;
857 }
858 }
859 }
860 $db->freeResult( $res );
861 wfProfileOut( __METHOD__ );
862 return $retVal;
863 }
864
865 function formatMetadata() {
866 if ( !$this->getHandler() ) {
867 return false;
868 }
869 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
870 }
871
872 /**
873 * Returns true if the file comes from the local file repository.
874 *
875 * @return bool
876 */
877 function isLocal() {
878 return $this->getRepoName() == 'local';
879 }
880
881 /**
882 * Returns the name of the repository.
883 *
884 * @return string
885 */
886 function getRepoName() {
887 return $this->repo ? $this->repo->getName() : 'unknown';
888 }
889
890 /**
891 * Returns true if the image is an old version
892 * STUB
893 */
894 function isOld() {
895 return false;
896 }
897
898 /**
899 * Is this file a "deleted" file in a private archive?
900 * STUB
901 */
902 function isDeleted( $field ) {
903 return false;
904 }
905
906 /**
907 * Was this file ever deleted from the wiki?
908 *
909 * @return bool
910 */
911 function wasDeleted() {
912 $title = $this->getTitle();
913 return $title && $title->isDeleted() > 0;
914 }
915
916 /**
917 * Delete all versions of the file.
918 *
919 * Moves the files into an archive directory (or deletes them)
920 * and removes the database rows.
921 *
922 * Cache purging is done; logging is caller's responsibility.
923 *
924 * @param $reason
925 * @param $suppress, hide content from sysops?
926 * @return true on success, false on some kind of failure
927 * STUB
928 * Overridden by LocalFile
929 */
930 function delete( $reason, $suppress = false ) {
931 $this->readOnlyError();
932 }
933
934 /**
935 * Restore all or specified deleted revisions to the given file.
936 * Permissions and logging are left to the caller.
937 *
938 * May throw database exceptions on error.
939 *
940 * @param $versions set of record ids of deleted items to restore,
941 * or empty to restore all revisions.
942 * @param $unsuppress, remove restrictions on content upon restoration?
943 * @return the number of file revisions restored if successful,
944 * or false on failure
945 * STUB
946 * Overridden by LocalFile
947 */
948 function restore( $versions=array(), $unsuppress=false ) {
949 $this->readOnlyError();
950 }
951
952 /**
953 * Returns 'true' if this image is a multipage document, e.g. a DJVU
954 * document.
955 *
956 * @return Bool
957 */
958 function isMultipage() {
959 return $this->getHandler() && $this->handler->isMultiPage( $this );
960 }
961
962 /**
963 * Returns the number of pages of a multipage document, or NULL for
964 * documents which aren't multipage documents
965 */
966 function pageCount() {
967 if ( !isset( $this->pageCount ) ) {
968 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
969 $this->pageCount = $this->handler->pageCount( $this );
970 } else {
971 $this->pageCount = false;
972 }
973 }
974 return $this->pageCount;
975 }
976
977 /**
978 * Calculate the height of a thumbnail using the source and destination width
979 */
980 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
981 // Exact integer multiply followed by division
982 if ( $srcWidth == 0 ) {
983 return 0;
984 } else {
985 return round( $srcHeight * $dstWidth / $srcWidth );
986 }
987 }
988
989 /**
990 * Get an image size array like that returned by getimagesize(), or false if it
991 * can't be determined.
992 *
993 * @param string $fileName The filename
994 * @return array
995 */
996 function getImageSize( $fileName ) {
997 if ( !$this->getHandler() ) {
998 return false;
999 }
1000 return $this->handler->getImageSize( $this, $fileName );
1001 }
1002
1003 /**
1004 * Get the URL of the image description page. May return false if it is
1005 * unknown or not applicable.
1006 */
1007 function getDescriptionUrl() {
1008 return $this->repo->getDescriptionUrl( $this->getName() );
1009 }
1010
1011 /**
1012 * Get the HTML text of the description page, if available
1013 */
1014 function getDescriptionText() {
1015 if ( !$this->repo->fetchDescription ) {
1016 return false;
1017 }
1018 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName() );
1019 if ( $renderUrl ) {
1020 wfDebug( "Fetching shared description from $renderUrl\n" );
1021 return Http::get( $renderUrl );
1022 } else {
1023 return false;
1024 }
1025 }
1026
1027 /**
1028 * Get discription of file revision
1029 * STUB
1030 */
1031 function getDescription() {
1032 return null;
1033 }
1034
1035 /**
1036 * Get the 14-character timestamp of the file upload, or false if
1037 * it doesn't exist
1038 */
1039 function getTimestamp() {
1040 $path = $this->getPath();
1041 if ( !file_exists( $path ) ) {
1042 return false;
1043 }
1044 return wfTimestamp( TS_MW, filemtime( $path ) );
1045 }
1046
1047 /**
1048 * Get the SHA-1 base 36 hash of the file
1049 */
1050 function getSha1() {
1051 return self::sha1Base36( $this->getPath() );
1052 }
1053
1054 /**
1055 * Determine if the current user is allowed to view a particular
1056 * field of this file, if it's marked as deleted.
1057 * STUB
1058 * @param int $field
1059 * @return bool
1060 */
1061 function userCan( $field ) {
1062 return true;
1063 }
1064
1065 /**
1066 * Get an associative array containing information about a file in the local filesystem.
1067 *
1068 * @param string $path Absolute local filesystem path
1069 * @param mixed $ext The file extension, or true to extract it from the filename.
1070 * Set it to false to ignore the extension.
1071 */
1072 static function getPropsFromPath( $path, $ext = true ) {
1073 wfProfileIn( __METHOD__ );
1074 wfDebug( __METHOD__.": Getting file info for $path\n" );
1075 $info = array(
1076 'fileExists' => file_exists( $path ) && !is_dir( $path )
1077 );
1078 $gis = false;
1079 if ( $info['fileExists'] ) {
1080 $magic = MimeMagic::singleton();
1081
1082 $info['mime'] = $magic->guessMimeType( $path, $ext );
1083 list( $info['major_mime'], $info['minor_mime'] ) = self::splitMime( $info['mime'] );
1084 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1085
1086 # Get size in bytes
1087 $info['size'] = filesize( $path );
1088
1089 # Height, width and metadata
1090 $handler = MediaHandler::getHandler( $info['mime'] );
1091 if ( $handler ) {
1092 $tempImage = (object)array();
1093 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1094 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1095 } else {
1096 $gis = false;
1097 $info['metadata'] = '';
1098 }
1099 $info['sha1'] = self::sha1Base36( $path );
1100
1101 wfDebug(__METHOD__.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1102 } else {
1103 $info['mime'] = NULL;
1104 $info['media_type'] = MEDIATYPE_UNKNOWN;
1105 $info['metadata'] = '';
1106 $info['sha1'] = '';
1107 wfDebug(__METHOD__.": $path NOT FOUND!\n");
1108 }
1109 if( $gis ) {
1110 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1111 $info['width'] = $gis[0];
1112 $info['height'] = $gis[1];
1113 if ( isset( $gis['bits'] ) ) {
1114 $info['bits'] = $gis['bits'];
1115 } else {
1116 $info['bits'] = 0;
1117 }
1118 } else {
1119 $info['width'] = 0;
1120 $info['height'] = 0;
1121 $info['bits'] = 0;
1122 }
1123 wfProfileOut( __METHOD__ );
1124 return $info;
1125 }
1126
1127 /**
1128 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1129 * encoding, zero padded to 31 digits.
1130 *
1131 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1132 * fairly neatly.
1133 *
1134 * Returns false on failure
1135 */
1136 static function sha1Base36( $path ) {
1137 wfSuppressWarnings();
1138 $hash = sha1_file( $path );
1139 wfRestoreWarnings();
1140 if ( $hash === false ) {
1141 return false;
1142 } else {
1143 return wfBaseConvert( $hash, 16, 36, 31 );
1144 }
1145 }
1146
1147 function getLongDesc() {
1148 $handler = $this->getHandler();
1149 if ( $handler ) {
1150 return $handler->getLongDesc( $this );
1151 } else {
1152 return MediaHandler::getLongDesc( $this );
1153 }
1154 }
1155
1156 function getShortDesc() {
1157 $handler = $this->getHandler();
1158 if ( $handler ) {
1159 return $handler->getShortDesc( $this );
1160 } else {
1161 return MediaHandler::getShortDesc( $this );
1162 }
1163 }
1164
1165 function getDimensionsString() {
1166 $handler = $this->getHandler();
1167 if ( $handler ) {
1168 return $handler->getDimensionsString( $this );
1169 } else {
1170 return '';
1171 }
1172 }
1173
1174 function getRedirected() {
1175 return $this->redirected;
1176 }
1177
1178 function redirectedFrom( $from ) {
1179 $this->redirected = $from;
1180 }
1181 }
1182 /**
1183 * Aliases for backwards compatibility with 1.6
1184 */
1185 define( 'MW_IMG_DELETED_FILE', File::DELETED_FILE );
1186 define( 'MW_IMG_DELETED_COMMENT', File::DELETED_COMMENT );
1187 define( 'MW_IMG_DELETED_USER', File::DELETED_USER );
1188 define( 'MW_IMG_DELETED_RESTRICTED', File::DELETED_RESTRICTED );
1189
1190