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