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