b617e3e4352fe8642281c3fe822dfe188df721f5
[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 FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
848 $res = $db->query( $sql, __METHOD__ );
849
850 $retVal = array();
851 if ( $db->numRows( $res ) ) {
852 while ( $row = $db->fetchObject( $res ) ) {
853 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
854 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
855 $retVal[] = $titleObj;
856 }
857 }
858 }
859 $db->freeResult( $res );
860 wfProfileOut( __METHOD__ );
861 return $retVal;
862 }
863
864 function formatMetadata() {
865 if ( !$this->getHandler() ) {
866 return false;
867 }
868 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
869 }
870
871 /**
872 * Returns true if the file comes from the local file repository.
873 *
874 * @return bool
875 */
876 function isLocal() {
877 return $this->getRepoName() == 'local';
878 }
879
880 /**
881 * Returns the name of the repository.
882 *
883 * @return string
884 */
885 function getRepoName() {
886 return $this->repo ? $this->repo->getName() : 'unknown';
887 }
888
889 /**
890 * Returns true if the image is an old version
891 * STUB
892 */
893 function isOld() {
894 return false;
895 }
896
897 /**
898 * Is this file a "deleted" file in a private archive?
899 * STUB
900 */
901 function isDeleted( $field ) {
902 return false;
903 }
904
905 /**
906 * Was this file ever deleted from the wiki?
907 *
908 * @return bool
909 */
910 function wasDeleted() {
911 $title = $this->getTitle();
912 return $title && $title->isDeleted() > 0;
913 }
914
915 /**
916 * Delete all versions of the file.
917 *
918 * Moves the files into an archive directory (or deletes them)
919 * and removes the database rows.
920 *
921 * Cache purging is done; logging is caller's responsibility.
922 *
923 * @param $reason
924 * @param $suppress, hide content from sysops?
925 * @return true on success, false on some kind of failure
926 * STUB
927 * Overridden by LocalFile
928 */
929 function delete( $reason, $suppress = false ) {
930 $this->readOnlyError();
931 }
932
933 /**
934 * Restore all or specified deleted revisions to the given file.
935 * Permissions and logging are left to the caller.
936 *
937 * May throw database exceptions on error.
938 *
939 * @param $versions set of record ids of deleted items to restore,
940 * or empty to restore all revisions.
941 * @param $unsuppress, remove restrictions on content upon restoration?
942 * @return the number of file revisions restored if successful,
943 * or false on failure
944 * STUB
945 * Overridden by LocalFile
946 */
947 function restore( $versions=array(), $unsuppress=false ) {
948 $this->readOnlyError();
949 }
950
951 /**
952 * Returns 'true' if this image is a multipage document, e.g. a DJVU
953 * document.
954 *
955 * @return Bool
956 */
957 function isMultipage() {
958 return $this->getHandler() && $this->handler->isMultiPage( $this );
959 }
960
961 /**
962 * Returns the number of pages of a multipage document, or NULL for
963 * documents which aren't multipage documents
964 */
965 function pageCount() {
966 if ( !isset( $this->pageCount ) ) {
967 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
968 $this->pageCount = $this->handler->pageCount( $this );
969 } else {
970 $this->pageCount = false;
971 }
972 }
973 return $this->pageCount;
974 }
975
976 /**
977 * Calculate the height of a thumbnail using the source and destination width
978 */
979 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
980 // Exact integer multiply followed by division
981 if ( $srcWidth == 0 ) {
982 return 0;
983 } else {
984 return round( $srcHeight * $dstWidth / $srcWidth );
985 }
986 }
987
988 /**
989 * Get an image size array like that returned by getimagesize(), or false if it
990 * can't be determined.
991 *
992 * @param string $fileName The filename
993 * @return array
994 */
995 function getImageSize( $fileName ) {
996 if ( !$this->getHandler() ) {
997 return false;
998 }
999 return $this->handler->getImageSize( $this, $fileName );
1000 }
1001
1002 /**
1003 * Get the URL of the image description page. May return false if it is
1004 * unknown or not applicable.
1005 */
1006 function getDescriptionUrl() {
1007 return $this->repo->getDescriptionUrl( $this->getName() );
1008 }
1009
1010 /**
1011 * Get the HTML text of the description page, if available
1012 */
1013 function getDescriptionText() {
1014 if ( !$this->repo->fetchDescription ) {
1015 return false;
1016 }
1017 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName() );
1018 if ( $renderUrl ) {
1019 wfDebug( "Fetching shared description from $renderUrl\n" );
1020 return Http::get( $renderUrl );
1021 } else {
1022 return false;
1023 }
1024 }
1025
1026 /**
1027 * Get discription of file revision
1028 * STUB
1029 */
1030 function getDescription() {
1031 return null;
1032 }
1033
1034 /**
1035 * Get the 14-character timestamp of the file upload, or false if
1036 * it doesn't exist
1037 */
1038 function getTimestamp() {
1039 $path = $this->getPath();
1040 if ( !file_exists( $path ) ) {
1041 return false;
1042 }
1043 return wfTimestamp( TS_MW, filemtime( $path ) );
1044 }
1045
1046 /**
1047 * Get the SHA-1 base 36 hash of the file
1048 */
1049 function getSha1() {
1050 return self::sha1Base36( $this->getPath() );
1051 }
1052
1053 /**
1054 * Determine if the current user is allowed to view a particular
1055 * field of this file, if it's marked as deleted.
1056 * STUB
1057 * @param int $field
1058 * @return bool
1059 */
1060 function userCan( $field ) {
1061 return true;
1062 }
1063
1064 /**
1065 * Get an associative array containing information about a file in the local filesystem.
1066 *
1067 * @param string $path Absolute local filesystem path
1068 * @param mixed $ext The file extension, or true to extract it from the filename.
1069 * Set it to false to ignore the extension.
1070 */
1071 static function getPropsFromPath( $path, $ext = true ) {
1072 wfProfileIn( __METHOD__ );
1073 wfDebug( __METHOD__.": Getting file info for $path\n" );
1074 $info = array(
1075 'fileExists' => file_exists( $path ) && !is_dir( $path )
1076 );
1077 $gis = false;
1078 if ( $info['fileExists'] ) {
1079 $magic = MimeMagic::singleton();
1080
1081 $info['mime'] = $magic->guessMimeType( $path, $ext );
1082 list( $info['major_mime'], $info['minor_mime'] ) = self::splitMime( $info['mime'] );
1083 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1084
1085 # Get size in bytes
1086 $info['size'] = filesize( $path );
1087
1088 # Height, width and metadata
1089 $handler = MediaHandler::getHandler( $info['mime'] );
1090 if ( $handler ) {
1091 $tempImage = (object)array();
1092 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1093 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1094 } else {
1095 $gis = false;
1096 $info['metadata'] = '';
1097 }
1098 $info['sha1'] = self::sha1Base36( $path );
1099
1100 wfDebug(__METHOD__.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1101 } else {
1102 $info['mime'] = NULL;
1103 $info['media_type'] = MEDIATYPE_UNKNOWN;
1104 $info['metadata'] = '';
1105 $info['sha1'] = '';
1106 wfDebug(__METHOD__.": $path NOT FOUND!\n");
1107 }
1108 if( $gis ) {
1109 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1110 $info['width'] = $gis[0];
1111 $info['height'] = $gis[1];
1112 if ( isset( $gis['bits'] ) ) {
1113 $info['bits'] = $gis['bits'];
1114 } else {
1115 $info['bits'] = 0;
1116 }
1117 } else {
1118 $info['width'] = 0;
1119 $info['height'] = 0;
1120 $info['bits'] = 0;
1121 }
1122 wfProfileOut( __METHOD__ );
1123 return $info;
1124 }
1125
1126 /**
1127 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1128 * encoding, zero padded to 31 digits.
1129 *
1130 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1131 * fairly neatly.
1132 *
1133 * Returns false on failure
1134 */
1135 static function sha1Base36( $path ) {
1136 wfSuppressWarnings();
1137 $hash = sha1_file( $path );
1138 wfRestoreWarnings();
1139 if ( $hash === false ) {
1140 return false;
1141 } else {
1142 return wfBaseConvert( $hash, 16, 36, 31 );
1143 }
1144 }
1145
1146 function getLongDesc() {
1147 $handler = $this->getHandler();
1148 if ( $handler ) {
1149 return $handler->getLongDesc( $this );
1150 } else {
1151 return MediaHandler::getLongDesc( $this );
1152 }
1153 }
1154
1155 function getShortDesc() {
1156 $handler = $this->getHandler();
1157 if ( $handler ) {
1158 return $handler->getShortDesc( $this );
1159 } else {
1160 return MediaHandler::getShortDesc( $this );
1161 }
1162 }
1163
1164 function getDimensionsString() {
1165 $handler = $this->getHandler();
1166 if ( $handler ) {
1167 return $handler->getDimensionsString( $this );
1168 } else {
1169 return '';
1170 }
1171 }
1172
1173 function getRedirected() {
1174 return $this->redirected;
1175 }
1176
1177 function redirectedFrom( $from ) {
1178 $this->redirected = $from;
1179 }
1180 }
1181 /**
1182 * Aliases for backwards compatibility with 1.6
1183 */
1184 define( 'MW_IMG_DELETED_FILE', File::DELETED_FILE );
1185 define( 'MW_IMG_DELETED_COMMENT', File::DELETED_COMMENT );
1186 define( 'MW_IMG_DELETED_USER', File::DELETED_USER );
1187 define( 'MW_IMG_DELETED_RESTRICTED', File::DELETED_RESTRICTED );
1188
1189