(bug 43177) API: Fix regression in case handling for sha1 params
[lhc/web/wiklou.git] / includes / upload / UploadBase.php
1 <?php
2 /**
3 * Base class for the backend of file upload.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Upload
22 */
23
24 /**
25 * @defgroup Upload Upload related
26 */
27
28 /**
29 * @ingroup Upload
30 *
31 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
32 * The frontends are formed by ApiUpload and SpecialUpload.
33 *
34 * See also includes/docs/upload.txt
35 *
36 * @author Brion Vibber
37 * @author Bryan Tong Minh
38 * @author Michael Dale
39 */
40 abstract class UploadBase {
41 protected $mTempPath;
42 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
43 protected $mTitle = false, $mTitleError = 0;
44 protected $mFilteredName, $mFinalExtension;
45 protected $mLocalFile, $mFileSize, $mFileProps;
46 protected $mBlackListedExtensions;
47 protected $mJavaDetected;
48
49 const SUCCESS = 0;
50 const OK = 0;
51 const EMPTY_FILE = 3;
52 const MIN_LENGTH_PARTNAME = 4;
53 const ILLEGAL_FILENAME = 5;
54 const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
55 const FILETYPE_MISSING = 8;
56 const FILETYPE_BADTYPE = 9;
57 const VERIFICATION_ERROR = 10;
58
59 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
60 const UPLOAD_VERIFICATION_ERROR = 11;
61 const HOOK_ABORTED = 11;
62 const FILE_TOO_LARGE = 12;
63 const WINDOWS_NONASCII_FILENAME = 13;
64 const FILENAME_TOO_LONG = 14;
65
66 const SESSION_STATUS_KEY = 'wsUploadStatusData';
67
68 /**
69 * @param $error int
70 * @return string
71 */
72 public function getVerificationErrorCode( $error ) {
73 $code_to_status = array(self::EMPTY_FILE => 'empty-file',
74 self::FILE_TOO_LARGE => 'file-too-large',
75 self::FILETYPE_MISSING => 'filetype-missing',
76 self::FILETYPE_BADTYPE => 'filetype-banned',
77 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
78 self::ILLEGAL_FILENAME => 'illegal-filename',
79 self::OVERWRITE_EXISTING_FILE => 'overwrite',
80 self::VERIFICATION_ERROR => 'verification-error',
81 self::HOOK_ABORTED => 'hookaborted',
82 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
83 self::FILENAME_TOO_LONG => 'filename-toolong',
84 );
85 if( isset( $code_to_status[$error] ) ) {
86 return $code_to_status[$error];
87 }
88
89 return 'unknown-error';
90 }
91
92 /**
93 * Returns true if uploads are enabled.
94 * Can be override by subclasses.
95 * @return bool
96 */
97 public static function isEnabled() {
98 global $wgEnableUploads;
99
100 if ( !$wgEnableUploads ) {
101 return false;
102 }
103
104 # Check php's file_uploads setting
105 return wfIsHipHop() || wfIniGetBool( 'file_uploads' );
106 }
107
108 /**
109 * Returns true if the user can use this upload module or else a string
110 * identifying the missing permission.
111 * Can be overriden by subclasses.
112 *
113 * @param $user User
114 * @return bool
115 */
116 public static function isAllowed( $user ) {
117 foreach ( array( 'upload', 'edit' ) as $permission ) {
118 if ( !$user->isAllowed( $permission ) ) {
119 return $permission;
120 }
121 }
122 return true;
123 }
124
125 // Upload handlers. Should probably just be a global.
126 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
127
128 /**
129 * Create a form of UploadBase depending on wpSourceType and initializes it
130 *
131 * @param $request WebRequest
132 * @param $type
133 * @return null
134 */
135 public static function createFromRequest( &$request, $type = null ) {
136 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
137
138 if( !$type ) {
139 return null;
140 }
141
142 // Get the upload class
143 $type = ucfirst( $type );
144
145 // Give hooks the chance to handle this request
146 $className = null;
147 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
148 if ( is_null( $className ) ) {
149 $className = 'UploadFrom' . $type;
150 wfDebug( __METHOD__ . ": class name: $className\n" );
151 if( !in_array( $type, self::$uploadHandlers ) ) {
152 return null;
153 }
154 }
155
156 // Check whether this upload class is enabled
157 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
158 return null;
159 }
160
161 // Check whether the request is valid
162 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
163 return null;
164 }
165
166 $handler = new $className;
167
168 $handler->initializeFromRequest( $request );
169 return $handler;
170 }
171
172 /**
173 * Check whether a request if valid for this handler
174 * @param $request
175 * @return bool
176 */
177 public static function isValidRequest( $request ) {
178 return false;
179 }
180
181 public function __construct() {}
182
183 /**
184 * Returns the upload type. Should be overridden by child classes
185 *
186 * @since 1.18
187 * @return string
188 */
189 public function getSourceType() { return null; }
190
191 /**
192 * Initialize the path information
193 * @param $name string the desired destination name
194 * @param $tempPath string the temporary path
195 * @param $fileSize int the file size
196 * @param $removeTempFile bool (false) remove the temporary file?
197 * @throws MWException
198 */
199 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
200 $this->mDesiredDestName = $name;
201 if ( FileBackend::isStoragePath( $tempPath ) ) {
202 throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
203 }
204 $this->mTempPath = $tempPath;
205 $this->mFileSize = $fileSize;
206 $this->mRemoveTempFile = $removeTempFile;
207 }
208
209 /**
210 * Initialize from a WebRequest. Override this in a subclass.
211 */
212 public abstract function initializeFromRequest( &$request );
213
214 /**
215 * Fetch the file. Usually a no-op
216 * @return Status
217 */
218 public function fetchFile() {
219 return Status::newGood();
220 }
221
222 /**
223 * Return true if the file is empty
224 * @return bool
225 */
226 public function isEmptyFile() {
227 return empty( $this->mFileSize );
228 }
229
230 /**
231 * Return the file size
232 * @return integer
233 */
234 public function getFileSize() {
235 return $this->mFileSize;
236 }
237
238 /**
239 * @param $srcPath String: the source path
240 * @return string the real path if it was a virtual URL
241 */
242 function getRealPath( $srcPath ) {
243 wfProfileIn( __METHOD__ );
244 $repo = RepoGroup::singleton()->getLocalRepo();
245 if ( $repo->isVirtualUrl( $srcPath ) ) {
246 // @TODO: just make uploads work with storage paths
247 // UploadFromStash loads files via virtuals URLs
248 $tmpFile = $repo->getLocalCopy( $srcPath );
249 $tmpFile->bind( $this ); // keep alive with $this
250 wfProfileOut( __METHOD__ );
251 return $tmpFile->getPath();
252 }
253 wfProfileOut( __METHOD__ );
254 return $srcPath;
255 }
256
257 /**
258 * Verify whether the upload is sane.
259 * @return mixed self::OK or else an array with error information
260 */
261 public function verifyUpload() {
262 wfProfileIn( __METHOD__ );
263
264 /**
265 * If there was no filename or a zero size given, give up quick.
266 */
267 if( $this->isEmptyFile() ) {
268 wfProfileOut( __METHOD__ );
269 return array( 'status' => self::EMPTY_FILE );
270 }
271
272 /**
273 * Honor $wgMaxUploadSize
274 */
275 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
276 if( $this->mFileSize > $maxSize ) {
277 wfProfileOut( __METHOD__ );
278 return array(
279 'status' => self::FILE_TOO_LARGE,
280 'max' => $maxSize,
281 );
282 }
283
284 /**
285 * Look at the contents of the file; if we can recognize the
286 * type but it's corrupt or data of the wrong type, we should
287 * probably not accept it.
288 */
289 $verification = $this->verifyFile();
290 if( $verification !== true ) {
291 wfProfileOut( __METHOD__ );
292 return array(
293 'status' => self::VERIFICATION_ERROR,
294 'details' => $verification
295 );
296 }
297
298 /**
299 * Make sure this file can be created
300 */
301 $result = $this->validateName();
302 if( $result !== true ) {
303 wfProfileOut( __METHOD__ );
304 return $result;
305 }
306
307 $error = '';
308 if( !wfRunHooks( 'UploadVerification',
309 array( $this->mDestName, $this->mTempPath, &$error ) ) )
310 {
311 wfProfileOut( __METHOD__ );
312 return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
313 }
314
315 wfProfileOut( __METHOD__ );
316 return array( 'status' => self::OK );
317 }
318
319 /**
320 * Verify that the name is valid and, if necessary, that we can overwrite
321 *
322 * @return mixed true if valid, otherwise and array with 'status'
323 * and other keys
324 **/
325 protected function validateName() {
326 $nt = $this->getTitle();
327 if( is_null( $nt ) ) {
328 $result = array( 'status' => $this->mTitleError );
329 if( $this->mTitleError == self::ILLEGAL_FILENAME ) {
330 $result['filtered'] = $this->mFilteredName;
331 }
332 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
333 $result['finalExt'] = $this->mFinalExtension;
334 if ( count( $this->mBlackListedExtensions ) ) {
335 $result['blacklistedExt'] = $this->mBlackListedExtensions;
336 }
337 }
338 return $result;
339 }
340 $this->mDestName = $this->getLocalFile()->getName();
341
342 return true;
343 }
344
345 /**
346 * Verify the mime type
347 *
348 * @param $mime string representing the mime
349 * @return mixed true if the file is verified, an array otherwise
350 */
351 protected function verifyMimeType( $mime ) {
352 global $wgVerifyMimeType;
353 wfProfileIn( __METHOD__ );
354 if ( $wgVerifyMimeType ) {
355 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
356 global $wgMimeTypeBlacklist;
357 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
358 wfProfileOut( __METHOD__ );
359 return array( 'filetype-badmime', $mime );
360 }
361
362 # XXX: Missing extension will be caught by validateName() via getTitle()
363 if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
364 wfProfileOut( __METHOD__ );
365 return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
366 }
367
368 # Check IE type
369 $fp = fopen( $this->mTempPath, 'rb' );
370 $chunk = fread( $fp, 256 );
371 fclose( $fp );
372
373 $magic = MimeMagic::singleton();
374 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
375 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
376 foreach ( $ieTypes as $ieType ) {
377 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
378 wfProfileOut( __METHOD__ );
379 return array( 'filetype-bad-ie-mime', $ieType );
380 }
381 }
382 }
383
384 wfProfileOut( __METHOD__ );
385 return true;
386 }
387
388 /**
389 * Verifies that it's ok to include the uploaded file
390 *
391 * @return mixed true of the file is verified, array otherwise.
392 */
393 protected function verifyFile() {
394 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
395 wfProfileIn( __METHOD__ );
396
397 # get the title, even though we are doing nothing with it, because
398 # we need to populate mFinalExtension
399 $this->getTitle();
400
401 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
402
403 # check mime type, if desired
404 $mime = $this->mFileProps[ 'file-mime' ];
405 $status = $this->verifyMimeType( $mime );
406 if ( $status !== true ) {
407 wfProfileOut( __METHOD__ );
408 return $status;
409 }
410
411 # check for htmlish code and javascript
412 if ( !$wgDisableUploadScriptChecks ) {
413 if( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
414 wfProfileOut( __METHOD__ );
415 return array( 'uploadscripted' );
416 }
417 if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
418 if( $this->detectScriptInSvg( $this->mTempPath ) ) {
419 wfProfileOut( __METHOD__ );
420 return array( 'uploadscripted' );
421 }
422 }
423 }
424
425 # Check for Java applets, which if uploaded can bypass cross-site
426 # restrictions.
427 if ( !$wgAllowJavaUploads ) {
428 $this->mJavaDetected = false;
429 $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
430 array( $this, 'zipEntryCallback' ) );
431 if ( !$zipStatus->isOK() ) {
432 $errors = $zipStatus->getErrorsArray();
433 $error = reset( $errors );
434 if ( $error[0] !== 'zip-wrong-format' ) {
435 wfProfileOut( __METHOD__ );
436 return $error;
437 }
438 }
439 if ( $this->mJavaDetected ) {
440 wfProfileOut( __METHOD__ );
441 return array( 'uploadjava' );
442 }
443 }
444
445 # Scan the uploaded file for viruses
446 $virus = $this->detectVirus( $this->mTempPath );
447 if ( $virus ) {
448 wfProfileOut( __METHOD__ );
449 return array( 'uploadvirus', $virus );
450 }
451
452 $handler = MediaHandler::getHandler( $mime );
453 if ( $handler ) {
454 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
455 if ( !$handlerStatus->isOK() ) {
456 $errors = $handlerStatus->getErrorsArray();
457 wfProfileOut( __METHOD__ );
458 return reset( $errors );
459 }
460 }
461
462 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
463 if ( $status !== true ) {
464 wfProfileOut( __METHOD__ );
465 return $status;
466 }
467
468 wfDebug( __METHOD__ . ": all clear; passing.\n" );
469 wfProfileOut( __METHOD__ );
470 return true;
471 }
472
473 /**
474 * Callback for ZipDirectoryReader to detect Java class files.
475 */
476 function zipEntryCallback( $entry ) {
477 $names = array( $entry['name'] );
478
479 // If there is a null character, cut off the name at it, because JDK's
480 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
481 // were constructed which had ".class\0" followed by a string chosen to
482 // make the hash collide with the truncated name, that file could be
483 // returned in response to a request for the .class file.
484 $nullPos = strpos( $entry['name'], "\000" );
485 if ( $nullPos !== false ) {
486 $names[] = substr( $entry['name'], 0, $nullPos );
487 }
488
489 // If there is a trailing slash in the file name, we have to strip it,
490 // because that's what ZIP_GetEntry() does.
491 if ( preg_grep( '!\.class/?$!', $names ) ) {
492 $this->mJavaDetected = true;
493 }
494 }
495
496 /**
497 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
498 * but that suggests it's checking the user, when it's really checking the title + user combination.
499 * @param $user User object to verify the permissions against
500 * @return mixed An array as returned by getUserPermissionsErrors or true
501 * in case the user has proper permissions.
502 */
503 public function verifyPermissions( $user ) {
504 return $this->verifyTitlePermissions( $user );
505 }
506
507 /**
508 * Check whether the user can edit, upload and create the image. This
509 * checks only against the current title; if it returns errors, it may
510 * very well be that another title will not give errors. Therefore
511 * isAllowed() should be called as well for generic is-user-blocked or
512 * can-user-upload checking.
513 *
514 * @param $user User object to verify the permissions against
515 * @return mixed An array as returned by getUserPermissionsErrors or true
516 * in case the user has proper permissions.
517 */
518 public function verifyTitlePermissions( $user ) {
519 /**
520 * If the image is protected, non-sysop users won't be able
521 * to modify it by uploading a new revision.
522 */
523 $nt = $this->getTitle();
524 if( is_null( $nt ) ) {
525 return true;
526 }
527 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
528 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
529 if ( !$nt->exists() ) {
530 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
531 } else {
532 $permErrorsCreate = array();
533 }
534 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
535 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
536 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
537 return $permErrors;
538 }
539
540 $overwriteError = $this->checkOverwrite( $user );
541 if ( $overwriteError !== true ) {
542 return array( $overwriteError );
543 }
544
545 return true;
546 }
547
548 /**
549 * Check for non fatal problems with the file
550 *
551 * @return Array of warnings
552 */
553 public function checkWarnings() {
554 global $wgLang;
555 wfProfileIn( __METHOD__ );
556
557 $warnings = array();
558
559 $localFile = $this->getLocalFile();
560 $filename = $localFile->getName();
561
562 /**
563 * Check whether the resulting filename is different from the desired one,
564 * but ignore things like ucfirst() and spaces/underscore things
565 */
566 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
567 $comparableName = Title::capitalize( $comparableName, NS_FILE );
568
569 if( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
570 $warnings['badfilename'] = $filename;
571 }
572
573 // Check whether the file extension is on the unwanted list
574 global $wgCheckFileExtensions, $wgFileExtensions;
575 if ( $wgCheckFileExtensions ) {
576 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) {
577 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension,
578 $wgLang->commaList( $wgFileExtensions ), count( $wgFileExtensions ) );
579 }
580 }
581
582 global $wgUploadSizeWarning;
583 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
584 $warnings['large-file'] = $wgUploadSizeWarning;
585 }
586
587 if ( $this->mFileSize == 0 ) {
588 $warnings['emptyfile'] = true;
589 }
590
591 $exists = self::getExistsWarning( $localFile );
592 if( $exists !== false ) {
593 $warnings['exists'] = $exists;
594 }
595
596 // Check dupes against existing files
597 $hash = FSFile::getSha1Base36FromPath( $this->mTempPath );
598 $dupes = RepoGroup::singleton()->findBySha1( $hash );
599 $title = $this->getTitle();
600 // Remove all matches against self
601 foreach ( $dupes as $key => $dupe ) {
602 if( $title->equals( $dupe->getTitle() ) ) {
603 unset( $dupes[$key] );
604 }
605 }
606 if( $dupes ) {
607 $warnings['duplicate'] = $dupes;
608 }
609
610 // Check dupes against archives
611 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
612 if ( $archivedImage->getID() > 0 ) {
613 $warnings['duplicate-archive'] = $archivedImage->getName();
614 }
615
616 wfProfileOut( __METHOD__ );
617 return $warnings;
618 }
619
620 /**
621 * Really perform the upload. Stores the file in the local repo, watches
622 * if necessary and runs the UploadComplete hook.
623 *
624 * @param $comment
625 * @param $pageText
626 * @param $watch
627 * @param $user User
628 *
629 * @return Status indicating the whether the upload succeeded.
630 */
631 public function performUpload( $comment, $pageText, $watch, $user ) {
632 wfProfileIn( __METHOD__ );
633
634 $status = $this->getLocalFile()->upload(
635 $this->mTempPath,
636 $comment,
637 $pageText,
638 File::DELETE_SOURCE,
639 $this->mFileProps,
640 false,
641 $user
642 );
643
644 if( $status->isGood() ) {
645 if ( $watch ) {
646 $user->addWatch( $this->getLocalFile()->getTitle() );
647 }
648 wfRunHooks( 'UploadComplete', array( &$this ) );
649 }
650
651 wfProfileOut( __METHOD__ );
652 return $status;
653 }
654
655 /**
656 * Returns the title of the file to be uploaded. Sets mTitleError in case
657 * the name was illegal.
658 *
659 * @return Title The title of the file or null in case the name was illegal
660 */
661 public function getTitle() {
662 if ( $this->mTitle !== false ) {
663 return $this->mTitle;
664 }
665
666 /* Assume that if a user specified File:Something.jpg, this is an error
667 * and that the namespace prefix needs to be stripped of.
668 */
669 $title = Title::newFromText( $this->mDesiredDestName );
670 if ( $title && $title->getNamespace() == NS_FILE ) {
671 $this->mFilteredName = $title->getDBkey();
672 } else {
673 $this->mFilteredName = $this->mDesiredDestName;
674 }
675
676 # oi_archive_name is max 255 bytes, which include a timestamp and an
677 # exclamation mark, so restrict file name to 240 bytes.
678 if ( strlen( $this->mFilteredName ) > 240 ) {
679 $this->mTitleError = self::FILENAME_TOO_LONG;
680 return $this->mTitle = null;
681 }
682
683 /**
684 * Chop off any directories in the given filename. Then
685 * filter out illegal characters, and try to make a legible name
686 * out of it. We'll strip some silently that Title would die on.
687 */
688 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
689 /* Normalize to title form before we do any further processing */
690 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
691 if( is_null( $nt ) ) {
692 $this->mTitleError = self::ILLEGAL_FILENAME;
693 return $this->mTitle = null;
694 }
695 $this->mFilteredName = $nt->getDBkey();
696
697
698
699 /**
700 * We'll want to blacklist against *any* 'extension', and use
701 * only the final one for the whitelist.
702 */
703 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
704
705 if( count( $ext ) ) {
706 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
707 } else {
708 $this->mFinalExtension = '';
709
710 # No extension, try guessing one
711 $magic = MimeMagic::singleton();
712 $mime = $magic->guessMimeType( $this->mTempPath );
713 if ( $mime !== 'unknown/unknown' ) {
714 # Get a space separated list of extensions
715 $extList = $magic->getExtensionsForType( $mime );
716 if ( $extList ) {
717 # Set the extension to the canonical extension
718 $this->mFinalExtension = strtok( $extList, ' ' );
719
720 # Fix up the other variables
721 $this->mFilteredName .= ".{$this->mFinalExtension}";
722 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
723 $ext = array( $this->mFinalExtension );
724 }
725 }
726
727 }
728
729 /* Don't allow users to override the blacklist (check file extension) */
730 global $wgCheckFileExtensions, $wgStrictFileExtensions;
731 global $wgFileExtensions, $wgFileBlacklist;
732
733 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
734
735 if ( $this->mFinalExtension == '' ) {
736 $this->mTitleError = self::FILETYPE_MISSING;
737 return $this->mTitle = null;
738 } elseif ( $blackListedExtensions ||
739 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
740 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
741 $this->mBlackListedExtensions = $blackListedExtensions;
742 $this->mTitleError = self::FILETYPE_BADTYPE;
743 return $this->mTitle = null;
744 }
745
746 // Windows may be broken with special characters, see bug XXX
747 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
748 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
749 return $this->mTitle = null;
750 }
751
752 # If there was more than one "extension", reassemble the base
753 # filename to prevent bogus complaints about length
754 if( count( $ext ) > 1 ) {
755 for( $i = 0; $i < count( $ext ) - 1; $i++ ) {
756 $partname .= '.' . $ext[$i];
757 }
758 }
759
760 if( strlen( $partname ) < 1 ) {
761 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
762 return $this->mTitle = null;
763 }
764
765 return $this->mTitle = $nt;
766 }
767
768 /**
769 * Return the local file and initializes if necessary.
770 *
771 * @return LocalFile|null
772 */
773 public function getLocalFile() {
774 if( is_null( $this->mLocalFile ) ) {
775 $nt = $this->getTitle();
776 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
777 }
778 return $this->mLocalFile;
779 }
780
781 /**
782 * If the user does not supply all necessary information in the first upload form submission (either by accident or
783 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
784 *
785 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
786 * into the database.
787 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
788 * API request to find this stashed file again.
789 *
790 * @param $user User
791 * @return UploadStashFile stashed file
792 */
793 public function stashFile( User $user = null ) {
794 // was stashSessionFile
795 wfProfileIn( __METHOD__ );
796
797 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user );
798 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
799 $this->mLocalFile = $file;
800
801 wfProfileOut( __METHOD__ );
802 return $file;
803 }
804
805 /**
806 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
807 *
808 * @return String: file key
809 */
810 public function stashFileGetKey() {
811 return $this->stashFile()->getFileKey();
812 }
813
814 /**
815 * alias for stashFileGetKey, for backwards compatibility
816 *
817 * @return String: file key
818 */
819 public function stashSession() {
820 return $this->stashFileGetKey();
821 }
822
823 /**
824 * If we've modified the upload file we need to manually remove it
825 * on exit to clean up.
826 */
827 public function cleanupTempFile() {
828 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
829 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
830 unlink( $this->mTempPath );
831 }
832 }
833
834 public function getTempPath() {
835 return $this->mTempPath;
836 }
837
838 /**
839 * Split a file into a base name and all dot-delimited 'extensions'
840 * on the end. Some web server configurations will fall back to
841 * earlier pseudo-'extensions' to determine type and execute
842 * scripts, so the blacklist needs to check them all.
843 *
844 * @param $filename string
845 * @return array
846 */
847 public static function splitExtensions( $filename ) {
848 $bits = explode( '.', $filename );
849 $basename = array_shift( $bits );
850 return array( $basename, $bits );
851 }
852
853 /**
854 * Perform case-insensitive match against a list of file extensions.
855 * Returns true if the extension is in the list.
856 *
857 * @param $ext String
858 * @param $list Array
859 * @return Boolean
860 */
861 public static function checkFileExtension( $ext, $list ) {
862 return in_array( strtolower( $ext ), $list );
863 }
864
865 /**
866 * Perform case-insensitive match against a list of file extensions.
867 * Returns an array of matching extensions.
868 *
869 * @param $ext Array
870 * @param $list Array
871 * @return Boolean
872 */
873 public static function checkFileExtensionList( $ext, $list ) {
874 return array_intersect( array_map( 'strtolower', $ext ), $list );
875 }
876
877 /**
878 * Checks if the mime type of the uploaded file matches the file extension.
879 *
880 * @param $mime String: the mime type of the uploaded file
881 * @param $extension String: the filename extension that the file is to be served with
882 * @return Boolean
883 */
884 public static function verifyExtension( $mime, $extension ) {
885 $magic = MimeMagic::singleton();
886
887 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
888 if ( !$magic->isRecognizableExtension( $extension ) ) {
889 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
890 "unrecognized extension '$extension', can't verify\n" );
891 return true;
892 } else {
893 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
894 "recognized extension '$extension', so probably invalid file\n" );
895 return false;
896 }
897
898 $match = $magic->isMatchingExtension( $extension, $mime );
899
900 if ( $match === null ) {
901 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
902 return true;
903 } elseif( $match === true ) {
904 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
905
906 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
907 return true;
908
909 } else {
910 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
911 return false;
912 }
913 }
914
915 /**
916 * Heuristic for detecting files that *could* contain JavaScript instructions or
917 * things that may look like HTML to a browser and are thus
918 * potentially harmful. The present implementation will produce false
919 * positives in some situations.
920 *
921 * @param $file String: pathname to the temporary upload file
922 * @param $mime String: the mime type of the file
923 * @param $extension String: the extension of the file
924 * @return Boolean: true if the file contains something looking like embedded scripts
925 */
926 public static function detectScript( $file, $mime, $extension ) {
927 global $wgAllowTitlesInSVG;
928 wfProfileIn( __METHOD__ );
929
930 # ugly hack: for text files, always look at the entire file.
931 # For binary field, just check the first K.
932
933 if( strpos( $mime,'text/' ) === 0 ) {
934 $chunk = file_get_contents( $file );
935 } else {
936 $fp = fopen( $file, 'rb' );
937 $chunk = fread( $fp, 1024 );
938 fclose( $fp );
939 }
940
941 $chunk = strtolower( $chunk );
942
943 if( !$chunk ) {
944 wfProfileOut( __METHOD__ );
945 return false;
946 }
947
948 # decode from UTF-16 if needed (could be used for obfuscation).
949 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
950 $enc = 'UTF-16BE';
951 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
952 $enc = 'UTF-16LE';
953 } else {
954 $enc = null;
955 }
956
957 if( $enc ) {
958 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
959 }
960
961 $chunk = trim( $chunk );
962
963 # @todo FIXME: Convert from UTF-16 if necessarry!
964 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
965
966 # check for HTML doctype
967 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
968 wfProfileOut( __METHOD__ );
969 return true;
970 }
971
972 /**
973 * Internet Explorer for Windows performs some really stupid file type
974 * autodetection which can cause it to interpret valid image files as HTML
975 * and potentially execute JavaScript, creating a cross-site scripting
976 * attack vectors.
977 *
978 * Apple's Safari browser also performs some unsafe file type autodetection
979 * which can cause legitimate files to be interpreted as HTML if the
980 * web server is not correctly configured to send the right content-type
981 * (or if you're really uploading plain text and octet streams!)
982 *
983 * Returns true if IE is likely to mistake the given file for HTML.
984 * Also returns true if Safari would mistake the given file for HTML
985 * when served with a generic content-type.
986 */
987 $tags = array(
988 '<a href',
989 '<body',
990 '<head',
991 '<html', #also in safari
992 '<img',
993 '<pre',
994 '<script', #also in safari
995 '<table'
996 );
997
998 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
999 $tags[] = '<title';
1000 }
1001
1002 foreach( $tags as $tag ) {
1003 if( false !== strpos( $chunk, $tag ) ) {
1004 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
1005 wfProfileOut( __METHOD__ );
1006 return true;
1007 }
1008 }
1009
1010 /*
1011 * look for JavaScript
1012 */
1013
1014 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1015 $chunk = Sanitizer::decodeCharReferences( $chunk );
1016
1017 # look for script-types
1018 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1019 wfDebug( __METHOD__ . ": found script types\n" );
1020 wfProfileOut( __METHOD__ );
1021 return true;
1022 }
1023
1024 # look for html-style script-urls
1025 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1026 wfDebug( __METHOD__ . ": found html-style script urls\n" );
1027 wfProfileOut( __METHOD__ );
1028 return true;
1029 }
1030
1031 # look for css-style script-urls
1032 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1033 wfDebug( __METHOD__ . ": found css-style script urls\n" );
1034 wfProfileOut( __METHOD__ );
1035 return true;
1036 }
1037
1038 wfDebug( __METHOD__ . ": no scripts found\n" );
1039 wfProfileOut( __METHOD__ );
1040 return false;
1041 }
1042
1043 /**
1044 * @param $filename string
1045 * @return bool
1046 */
1047 protected function detectScriptInSvg( $filename ) {
1048 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1049 return $check->filterMatch;
1050 }
1051
1052 /**
1053 * @todo Replace this with a whitelist filter!
1054 * @param $element string
1055 * @param $attribs array
1056 * @return bool
1057 */
1058 public function checkSvgScriptCallback( $element, $attribs ) {
1059 $strippedElement = $this->stripXmlNamespace( $element );
1060
1061 /*
1062 * check for elements that can contain javascript
1063 */
1064 if( $strippedElement == 'script' ) {
1065 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1066 return true;
1067 }
1068
1069 # e.g., <svg xmlns="http://www.w3.org/2000/svg"> <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1070 if( $strippedElement == 'handler' ) {
1071 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1072 return true;
1073 }
1074
1075 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1076 if( $strippedElement == 'stylesheet' ) {
1077 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1078 return true;
1079 }
1080
1081 foreach( $attribs as $attrib => $value ) {
1082 $stripped = $this->stripXmlNamespace( $attrib );
1083 $value = strtolower($value);
1084
1085 if( substr( $stripped, 0, 2 ) == 'on' ) {
1086 wfDebug( __METHOD__ . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1087 return true;
1088 }
1089
1090 # href with javascript target
1091 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1092 wfDebug( __METHOD__ . ": Found script in href attribute '$attrib'='$value' in uploaded file.\n" );
1093 return true;
1094 }
1095
1096 # href with embeded svg as target
1097 if( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1098 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1099 return true;
1100 }
1101
1102 # href with embeded (text/xml) svg as target
1103 if( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1104 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1105 return true;
1106 }
1107
1108 # use set/animate to add event-handler attribute to parent
1109 if( ( $strippedElement == 'set' || $strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
1110 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1111 return true;
1112 }
1113
1114 # use set to add href attribute to parent element
1115 if( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
1116 wfDebug( __METHOD__ . ": Found svg setting href attibute '$value' in uploaded file.\n" );
1117 return true;
1118 }
1119
1120 # use set to add a remote / data / script target to an element
1121 if( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1122 wfDebug( __METHOD__ . ": Found svg setting attibute to '$value' in uploaded file.\n" );
1123 return true;
1124 }
1125
1126
1127 # use handler attribute with remote / data / script
1128 if( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1129 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1130 return true;
1131 }
1132
1133 # use CSS styles to bring in remote code
1134 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1135 if( $stripped == 'style' && preg_match_all( '!((?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*["\']?\s*[^#]+.*?\))!sim', $value, $matches ) ) {
1136 foreach ($matches[1] as $match) {
1137 if (!preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1138 wfDebug( __METHOD__ . ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
1139 return true;
1140 }
1141 }
1142 }
1143
1144 # image filters can pull in url, which could be svg that executes scripts
1145 if( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1146 wfDebug( __METHOD__ . ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1147 return true;
1148 }
1149
1150 }
1151
1152 return false; //No scripts detected
1153 }
1154
1155 /**
1156 * @param $name string
1157 * @return string
1158 */
1159 private function stripXmlNamespace( $name ) {
1160 // 'http://www.w3.org/2000/svg:script' -> 'script'
1161 $parts = explode( ':', strtolower( $name ) );
1162 return array_pop( $parts );
1163 }
1164
1165 /**
1166 * Generic wrapper function for a virus scanner program.
1167 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1168 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1169 *
1170 * @param $file String: pathname to the temporary upload file
1171 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1172 * or a string containing feedback from the virus scanner if a virus was found.
1173 * If textual feedback is missing but a virus was found, this function returns true.
1174 */
1175 public static function detectVirus( $file ) {
1176 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1177 wfProfileIn( __METHOD__ );
1178
1179 if ( !$wgAntivirus ) {
1180 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1181 wfProfileOut( __METHOD__ );
1182 return null;
1183 }
1184
1185 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1186 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1187 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1188 array( 'virus-badscanner', $wgAntivirus ) );
1189 wfProfileOut( __METHOD__ );
1190 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1191 }
1192
1193 # look up scanner configuration
1194 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1195 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1196 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1197 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1198
1199 if ( strpos( $command, "%f" ) === false ) {
1200 # simple pattern: append file to scan
1201 $command .= " " . wfEscapeShellArg( $file );
1202 } else {
1203 # complex pattern: replace "%f" with file to scan
1204 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1205 }
1206
1207 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1208
1209 # execute virus scanner
1210 $exitCode = false;
1211
1212 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1213 # that does not seem to be worth the pain.
1214 # Ask me (Duesentrieb) about it if it's ever needed.
1215 $output = wfShellExec( "$command 2>&1", $exitCode );
1216
1217 # map exit code to AV_xxx constants.
1218 $mappedCode = $exitCode;
1219 if ( $exitCodeMap ) {
1220 if ( isset( $exitCodeMap[$exitCode] ) ) {
1221 $mappedCode = $exitCodeMap[$exitCode];
1222 } elseif ( isset( $exitCodeMap["*"] ) ) {
1223 $mappedCode = $exitCodeMap["*"];
1224 }
1225 }
1226
1227 if ( $mappedCode === AV_SCAN_FAILED ) {
1228 # scan failed (code was mapped to false by $exitCodeMap)
1229 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1230
1231 if ( $wgAntivirusRequired ) {
1232 wfProfileOut( __METHOD__ );
1233 return wfMessage( 'virus-scanfailed', array( $exitCode ) )->text();
1234 } else {
1235 wfProfileOut( __METHOD__ );
1236 return null;
1237 }
1238 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1239 # scan failed because filetype is unknown (probably imune)
1240 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1241 wfProfileOut( __METHOD__ );
1242 return null;
1243 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1244 # no virus found
1245 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1246 wfProfileOut( __METHOD__ );
1247 return false;
1248 } else {
1249 $output = trim( $output );
1250
1251 if ( !$output ) {
1252 $output = true; #if there's no output, return true
1253 } elseif ( $msgPattern ) {
1254 $groups = array();
1255 if ( preg_match( $msgPattern, $output, $groups ) ) {
1256 if ( $groups[1] ) {
1257 $output = $groups[1];
1258 }
1259 }
1260 }
1261
1262 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1263 wfProfileOut( __METHOD__ );
1264 return $output;
1265 }
1266 }
1267
1268 /**
1269 * Check if there's an overwrite conflict and, if so, if restrictions
1270 * forbid this user from performing the upload.
1271 *
1272 * @param $user User
1273 *
1274 * @return mixed true on success, array on failure
1275 */
1276 private function checkOverwrite( $user ) {
1277 // First check whether the local file can be overwritten
1278 $file = $this->getLocalFile();
1279 if( $file->exists() ) {
1280 if( !self::userCanReUpload( $user, $file ) ) {
1281 return array( 'fileexists-forbidden', $file->getName() );
1282 } else {
1283 return true;
1284 }
1285 }
1286
1287 /* Check shared conflicts: if the local file does not exist, but
1288 * wfFindFile finds a file, it exists in a shared repository.
1289 */
1290 $file = wfFindFile( $this->getTitle() );
1291 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1292 return array( 'fileexists-shared-forbidden', $file->getName() );
1293 }
1294
1295 return true;
1296 }
1297
1298 /**
1299 * Check if a user is the last uploader
1300 *
1301 * @param $user User object
1302 * @param $img String: image name
1303 * @return Boolean
1304 */
1305 public static function userCanReUpload( User $user, $img ) {
1306 if( $user->isAllowed( 'reupload' ) ) {
1307 return true; // non-conditional
1308 }
1309 if( !$user->isAllowed( 'reupload-own' ) ) {
1310 return false;
1311 }
1312 if( is_string( $img ) ) {
1313 $img = wfLocalFile( $img );
1314 }
1315 if ( !( $img instanceof LocalFile ) ) {
1316 return false;
1317 }
1318
1319 return $user->getId() == $img->getUser( 'id' );
1320 }
1321
1322 /**
1323 * Helper function that does various existence checks for a file.
1324 * The following checks are performed:
1325 * - The file exists
1326 * - Article with the same name as the file exists
1327 * - File exists with normalized extension
1328 * - The file looks like a thumbnail and the original exists
1329 *
1330 * @param $file File The File object to check
1331 * @return mixed False if the file does not exists, else an array
1332 */
1333 public static function getExistsWarning( $file ) {
1334 if( $file->exists() ) {
1335 return array( 'warning' => 'exists', 'file' => $file );
1336 }
1337
1338 if( $file->getTitle()->getArticleID() ) {
1339 return array( 'warning' => 'page-exists', 'file' => $file );
1340 }
1341
1342 if ( $file->wasDeleted() && !$file->exists() ) {
1343 return array( 'warning' => 'was-deleted', 'file' => $file );
1344 }
1345
1346 if( strpos( $file->getName(), '.' ) == false ) {
1347 $partname = $file->getName();
1348 $extension = '';
1349 } else {
1350 $n = strrpos( $file->getName(), '.' );
1351 $extension = substr( $file->getName(), $n + 1 );
1352 $partname = substr( $file->getName(), 0, $n );
1353 }
1354 $normalizedExtension = File::normalizeExtension( $extension );
1355
1356 if ( $normalizedExtension != $extension ) {
1357 // We're not using the normalized form of the extension.
1358 // Normal form is lowercase, using most common of alternate
1359 // extensions (eg 'jpg' rather than 'JPEG').
1360 //
1361 // Check for another file using the normalized form...
1362 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1363 $file_lc = wfLocalFile( $nt_lc );
1364
1365 if( $file_lc->exists() ) {
1366 return array(
1367 'warning' => 'exists-normalized',
1368 'file' => $file,
1369 'normalizedFile' => $file_lc
1370 );
1371 }
1372 }
1373
1374 if ( self::isThumbName( $file->getName() ) ) {
1375 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1376 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
1377 $file_thb = wfLocalFile( $nt_thb );
1378 if( $file_thb->exists() ) {
1379 return array(
1380 'warning' => 'thumb',
1381 'file' => $file,
1382 'thumbFile' => $file_thb
1383 );
1384 } else {
1385 // File does not exist, but we just don't like the name
1386 return array(
1387 'warning' => 'thumb-name',
1388 'file' => $file,
1389 'thumbFile' => $file_thb
1390 );
1391 }
1392 }
1393
1394
1395 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
1396 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1397 return array(
1398 'warning' => 'bad-prefix',
1399 'file' => $file,
1400 'prefix' => $prefix
1401 );
1402 }
1403 }
1404
1405 return false;
1406 }
1407
1408 /**
1409 * Helper function that checks whether the filename looks like a thumbnail
1410 * @param $filename string
1411 * @return bool
1412 */
1413 public static function isThumbName( $filename ) {
1414 $n = strrpos( $filename, '.' );
1415 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1416 return (
1417 substr( $partname , 3, 3 ) == 'px-' ||
1418 substr( $partname , 2, 3 ) == 'px-'
1419 ) &&
1420 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1421 }
1422
1423 /**
1424 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1425 *
1426 * @return array list of prefixes
1427 */
1428 public static function getFilenamePrefixBlacklist() {
1429 $blacklist = array();
1430 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1431 if( !$message->isDisabled() ) {
1432 $lines = explode( "\n", $message->plain() );
1433 foreach( $lines as $line ) {
1434 // Remove comment lines
1435 $comment = substr( trim( $line ), 0, 1 );
1436 if ( $comment == '#' || $comment == '' ) {
1437 continue;
1438 }
1439 // Remove additional comments after a prefix
1440 $comment = strpos( $line, '#' );
1441 if ( $comment > 0 ) {
1442 $line = substr( $line, 0, $comment-1 );
1443 }
1444 $blacklist[] = trim( $line );
1445 }
1446 }
1447 return $blacklist;
1448 }
1449
1450 /**
1451 * Gets image info about the file just uploaded.
1452 *
1453 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1454 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1455 * with the appropriate format, presumably.
1456 *
1457 * @param $result ApiResult:
1458 * @return Array: image info
1459 */
1460 public function getImageInfo( $result ) {
1461 $file = $this->getLocalFile();
1462 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1463 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1464 if ( $file instanceof UploadStashFile ) {
1465 $imParam = ApiQueryStashImageInfo::getPropertyNames();
1466 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1467 } else {
1468 $imParam = ApiQueryImageInfo::getPropertyNames();
1469 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1470 }
1471 return $info;
1472 }
1473
1474 /**
1475 * @param $error array
1476 * @return Status
1477 */
1478 public function convertVerifyErrorToStatus( $error ) {
1479 $code = $error['status'];
1480 unset( $code['status'] );
1481 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1482 }
1483
1484 /**
1485 * @param $forType null|string
1486 * @return int
1487 */
1488 public static function getMaxUploadSize( $forType = null ) {
1489 global $wgMaxUploadSize;
1490
1491 if ( is_array( $wgMaxUploadSize ) ) {
1492 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1493 return $wgMaxUploadSize[$forType];
1494 } else {
1495 return $wgMaxUploadSize['*'];
1496 }
1497 } else {
1498 return intval( $wgMaxUploadSize );
1499 }
1500 }
1501
1502 /**
1503 * Get the current status of a chunked upload (used for polling).
1504 * The status will be read from the *current* user session.
1505 * @param $statusKey string
1506 * @return Array|bool
1507 */
1508 public static function getSessionStatus( $statusKey ) {
1509 return isset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] )
1510 ? $_SESSION[self::SESSION_STATUS_KEY][$statusKey]
1511 : false;
1512 }
1513
1514 /**
1515 * Set the current status of a chunked upload (used for polling).
1516 * The status will be stored in the *current* user session.
1517 * @param $statusKey string
1518 * @param $value array|false
1519 * @return void
1520 */
1521 public static function setSessionStatus( $statusKey, $value ) {
1522 if ( $value === false ) {
1523 unset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] );
1524 } else {
1525 $_SESSION[self::SESSION_STATUS_KEY][$statusKey] = $value;
1526 }
1527 }
1528 }