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