Merge "Special:EditWatchlist/raw now make use of GenderCache"
[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
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 $user User
618 *
619 * @return Status indicating the whether the upload succeeded.
620 */
621 public function performUpload( $comment, $pageText, $watch, $user ) {
622 wfProfileIn( __METHOD__ );
623
624 $status = $this->getLocalFile()->upload(
625 $this->mTempPath,
626 $comment,
627 $pageText,
628 File::DELETE_SOURCE,
629 $this->mFileProps,
630 false,
631 $user
632 );
633
634 if( $status->isGood() ) {
635 if ( $watch ) {
636 $user->addWatch( $this->getLocalFile()->getTitle() );
637 }
638 wfRunHooks( 'UploadComplete', array( &$this ) );
639 }
640
641 wfProfileOut( __METHOD__ );
642 return $status;
643 }
644
645 /**
646 * Returns the title of the file to be uploaded. Sets mTitleError in case
647 * the name was illegal.
648 *
649 * @return Title The title of the file or null in case the name was illegal
650 */
651 public function getTitle() {
652 if ( $this->mTitle !== false ) {
653 return $this->mTitle;
654 }
655
656 /* Assume that if a user specified File:Something.jpg, this is an error
657 * and that the namespace prefix needs to be stripped of.
658 */
659 $title = Title::newFromText( $this->mDesiredDestName );
660 if ( $title && $title->getNamespace() == NS_FILE ) {
661 $this->mFilteredName = $title->getDBkey();
662 } else {
663 $this->mFilteredName = $this->mDesiredDestName;
664 }
665
666 # oi_archive_name is max 255 bytes, which include a timestamp and an
667 # exclamation mark, so restrict file name to 240 bytes.
668 if ( strlen( $this->mFilteredName ) > 240 ) {
669 $this->mTitleError = self::FILENAME_TOO_LONG;
670 return $this->mTitle = null;
671 }
672
673 /**
674 * Chop off any directories in the given filename. Then
675 * filter out illegal characters, and try to make a legible name
676 * out of it. We'll strip some silently that Title would die on.
677 */
678 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
679 /* Normalize to title form before we do any further processing */
680 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
681 if( is_null( $nt ) ) {
682 $this->mTitleError = self::ILLEGAL_FILENAME;
683 return $this->mTitle = null;
684 }
685 $this->mFilteredName = $nt->getDBkey();
686
687
688
689 /**
690 * We'll want to blacklist against *any* 'extension', and use
691 * only the final one for the whitelist.
692 */
693 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
694
695 if( count( $ext ) ) {
696 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
697 } else {
698 $this->mFinalExtension = '';
699
700 # No extension, try guessing one
701 $magic = MimeMagic::singleton();
702 $mime = $magic->guessMimeType( $this->mTempPath );
703 if ( $mime !== 'unknown/unknown' ) {
704 # Get a space separated list of extensions
705 $extList = $magic->getExtensionsForType( $mime );
706 if ( $extList ) {
707 # Set the extension to the canonical extension
708 $this->mFinalExtension = strtok( $extList, ' ' );
709
710 # Fix up the other variables
711 $this->mFilteredName .= ".{$this->mFinalExtension}";
712 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
713 $ext = array( $this->mFinalExtension );
714 }
715 }
716
717 }
718
719 /* Don't allow users to override the blacklist (check file extension) */
720 global $wgCheckFileExtensions, $wgStrictFileExtensions;
721 global $wgFileExtensions, $wgFileBlacklist;
722
723 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
724
725 if ( $this->mFinalExtension == '' ) {
726 $this->mTitleError = self::FILETYPE_MISSING;
727 return $this->mTitle = null;
728 } elseif ( $blackListedExtensions ||
729 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
730 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
731 $this->mBlackListedExtensions = $blackListedExtensions;
732 $this->mTitleError = self::FILETYPE_BADTYPE;
733 return $this->mTitle = null;
734 }
735
736 // Windows may be broken with special characters, see bug XXX
737 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
738 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
739 return $this->mTitle = null;
740 }
741
742 # If there was more than one "extension", reassemble the base
743 # filename to prevent bogus complaints about length
744 if( count( $ext ) > 1 ) {
745 for( $i = 0; $i < count( $ext ) - 1; $i++ ) {
746 $partname .= '.' . $ext[$i];
747 }
748 }
749
750 if( strlen( $partname ) < 1 ) {
751 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
752 return $this->mTitle = null;
753 }
754
755 return $this->mTitle = $nt;
756 }
757
758 /**
759 * Return the local file and initializes if necessary.
760 *
761 * @return LocalFile
762 */
763 public function getLocalFile() {
764 if( is_null( $this->mLocalFile ) ) {
765 $nt = $this->getTitle();
766 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
767 }
768 return $this->mLocalFile;
769 }
770
771 /**
772 * If the user does not supply all necessary information in the first upload form submission (either by accident or
773 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
774 *
775 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
776 * into the database.
777 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
778 * API request to find this stashed file again.
779 *
780 * @return UploadStashFile stashed file
781 */
782 public function stashFile() {
783 // was stashSessionFile
784 wfProfileIn( __METHOD__ );
785
786 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
787 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
788 $this->mLocalFile = $file;
789
790 wfProfileOut( __METHOD__ );
791 return $file;
792 }
793
794 /**
795 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
796 *
797 * @return String: file key
798 */
799 public function stashFileGetKey() {
800 return $this->stashFile()->getFileKey();
801 }
802
803 /**
804 * alias for stashFileGetKey, for backwards compatibility
805 *
806 * @return String: file key
807 */
808 public function stashSession() {
809 return $this->stashFileGetKey();
810 }
811
812 /**
813 * If we've modified the upload file we need to manually remove it
814 * on exit to clean up.
815 */
816 public function cleanupTempFile() {
817 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
818 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
819 unlink( $this->mTempPath );
820 }
821 }
822
823 public function getTempPath() {
824 return $this->mTempPath;
825 }
826
827 /**
828 * Split a file into a base name and all dot-delimited 'extensions'
829 * on the end. Some web server configurations will fall back to
830 * earlier pseudo-'extensions' to determine type and execute
831 * scripts, so the blacklist needs to check them all.
832 *
833 * @return array
834 */
835 public static function splitExtensions( $filename ) {
836 $bits = explode( '.', $filename );
837 $basename = array_shift( $bits );
838 return array( $basename, $bits );
839 }
840
841 /**
842 * Perform case-insensitive match against a list of file extensions.
843 * Returns true if the extension is in the list.
844 *
845 * @param $ext String
846 * @param $list Array
847 * @return Boolean
848 */
849 public static function checkFileExtension( $ext, $list ) {
850 return in_array( strtolower( $ext ), $list );
851 }
852
853 /**
854 * Perform case-insensitive match against a list of file extensions.
855 * Returns an array of matching extensions.
856 *
857 * @param $ext Array
858 * @param $list Array
859 * @return Boolean
860 */
861 public static function checkFileExtensionList( $ext, $list ) {
862 return array_intersect( array_map( 'strtolower', $ext ), $list );
863 }
864
865 /**
866 * Checks if the mime type of the uploaded file matches the file extension.
867 *
868 * @param $mime String: the mime type of the uploaded file
869 * @param $extension String: the filename extension that the file is to be served with
870 * @return Boolean
871 */
872 public static function verifyExtension( $mime, $extension ) {
873 $magic = MimeMagic::singleton();
874
875 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
876 if ( !$magic->isRecognizableExtension( $extension ) ) {
877 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
878 "unrecognized extension '$extension', can't verify\n" );
879 return true;
880 } else {
881 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
882 "recognized extension '$extension', so probably invalid file\n" );
883 return false;
884 }
885
886 $match = $magic->isMatchingExtension( $extension, $mime );
887
888 if ( $match === null ) {
889 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
890 return true;
891 } elseif( $match === true ) {
892 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
893
894 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
895 return true;
896
897 } else {
898 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
899 return false;
900 }
901 }
902
903 /**
904 * Heuristic for detecting files that *could* contain JavaScript instructions or
905 * things that may look like HTML to a browser and are thus
906 * potentially harmful. The present implementation will produce false
907 * positives in some situations.
908 *
909 * @param $file String: pathname to the temporary upload file
910 * @param $mime String: the mime type of the file
911 * @param $extension String: the extension of the file
912 * @return Boolean: true if the file contains something looking like embedded scripts
913 */
914 public static function detectScript( $file, $mime, $extension ) {
915 global $wgAllowTitlesInSVG;
916 wfProfileIn( __METHOD__ );
917
918 # ugly hack: for text files, always look at the entire file.
919 # For binary field, just check the first K.
920
921 if( strpos( $mime,'text/' ) === 0 ) {
922 $chunk = file_get_contents( $file );
923 } else {
924 $fp = fopen( $file, 'rb' );
925 $chunk = fread( $fp, 1024 );
926 fclose( $fp );
927 }
928
929 $chunk = strtolower( $chunk );
930
931 if( !$chunk ) {
932 wfProfileOut( __METHOD__ );
933 return false;
934 }
935
936 # decode from UTF-16 if needed (could be used for obfuscation).
937 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
938 $enc = 'UTF-16BE';
939 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
940 $enc = 'UTF-16LE';
941 } else {
942 $enc = null;
943 }
944
945 if( $enc ) {
946 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
947 }
948
949 $chunk = trim( $chunk );
950
951 # @todo FIXME: Convert from UTF-16 if necessarry!
952 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
953
954 # check for HTML doctype
955 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
956 wfProfileOut( __METHOD__ );
957 return true;
958 }
959
960 /**
961 * Internet Explorer for Windows performs some really stupid file type
962 * autodetection which can cause it to interpret valid image files as HTML
963 * and potentially execute JavaScript, creating a cross-site scripting
964 * attack vectors.
965 *
966 * Apple's Safari browser also performs some unsafe file type autodetection
967 * which can cause legitimate files to be interpreted as HTML if the
968 * web server is not correctly configured to send the right content-type
969 * (or if you're really uploading plain text and octet streams!)
970 *
971 * Returns true if IE is likely to mistake the given file for HTML.
972 * Also returns true if Safari would mistake the given file for HTML
973 * when served with a generic content-type.
974 */
975 $tags = array(
976 '<a href',
977 '<body',
978 '<head',
979 '<html', #also in safari
980 '<img',
981 '<pre',
982 '<script', #also in safari
983 '<table'
984 );
985
986 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
987 $tags[] = '<title';
988 }
989
990 foreach( $tags as $tag ) {
991 if( false !== strpos( $chunk, $tag ) ) {
992 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
993 wfProfileOut( __METHOD__ );
994 return true;
995 }
996 }
997
998 /*
999 * look for JavaScript
1000 */
1001
1002 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1003 $chunk = Sanitizer::decodeCharReferences( $chunk );
1004
1005 # look for script-types
1006 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1007 wfDebug( __METHOD__ . ": found script types\n" );
1008 wfProfileOut( __METHOD__ );
1009 return true;
1010 }
1011
1012 # look for html-style script-urls
1013 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1014 wfDebug( __METHOD__ . ": found html-style script urls\n" );
1015 wfProfileOut( __METHOD__ );
1016 return true;
1017 }
1018
1019 # look for css-style script-urls
1020 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1021 wfDebug( __METHOD__ . ": found css-style script urls\n" );
1022 wfProfileOut( __METHOD__ );
1023 return true;
1024 }
1025
1026 wfDebug( __METHOD__ . ": no scripts found\n" );
1027 wfProfileOut( __METHOD__ );
1028 return false;
1029 }
1030
1031 protected function detectScriptInSvg( $filename ) {
1032 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1033 return $check->filterMatch;
1034 }
1035
1036 /**
1037 * @todo Replace this with a whitelist filter!
1038 * @return bool
1039 */
1040 public function checkSvgScriptCallback( $element, $attribs ) {
1041 $strippedElement = $this->stripXmlNamespace( $element );
1042
1043 /*
1044 * check for elements that can contain javascript
1045 */
1046 if( $strippedElement == 'script' ) {
1047 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1048 return true;
1049 }
1050
1051 # 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>
1052 if( $strippedElement == 'handler' ) {
1053 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1054 return true;
1055 }
1056
1057 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1058 if( $strippedElement == 'stylesheet' ) {
1059 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1060 return true;
1061 }
1062
1063 foreach( $attribs as $attrib => $value ) {
1064 $stripped = $this->stripXmlNamespace( $attrib );
1065 $value = strtolower($value);
1066
1067 if( substr( $stripped, 0, 2 ) == 'on' ) {
1068 wfDebug( __METHOD__ . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1069 return true;
1070 }
1071
1072 # href with javascript target
1073 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1074 wfDebug( __METHOD__ . ": Found script in href attribute '$attrib'='$value' in uploaded file.\n" );
1075 return true;
1076 }
1077
1078 # href with embeded svg as target
1079 if( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1080 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1081 return true;
1082 }
1083
1084 # href with embeded (text/xml) svg as target
1085 if( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1086 wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1087 return true;
1088 }
1089
1090 # use set/animate to add event-handler attribute to parent
1091 if( ( $strippedElement == 'set' || $strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
1092 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1093 return true;
1094 }
1095
1096 # use set to add href attribute to parent element
1097 if( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
1098 wfDebug( __METHOD__ . ": Found svg setting href attibute '$value' in uploaded file.\n" );
1099 return true;
1100 }
1101
1102 # use set to add a remote / data / script target to an element
1103 if( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1104 wfDebug( __METHOD__ . ": Found svg setting attibute to '$value' in uploaded file.\n" );
1105 return true;
1106 }
1107
1108
1109 # use handler attribute with remote / data / script
1110 if( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1111 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1112 return true;
1113 }
1114
1115 # use CSS styles to bring in remote code
1116 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1117 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 ) ) {
1118 foreach ($matches[1] as $match) {
1119 if (!preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1120 wfDebug( __METHOD__ . ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
1121 return true;
1122 }
1123 }
1124 }
1125
1126 # image filters can pull in url, which could be svg that executes scripts
1127 if( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1128 wfDebug( __METHOD__ . ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1129 return true;
1130 }
1131
1132 }
1133
1134 return false; //No scripts detected
1135 }
1136
1137 private function stripXmlNamespace( $name ) {
1138 // 'http://www.w3.org/2000/svg:script' -> 'script'
1139 $parts = explode( ':', strtolower( $name ) );
1140 return array_pop( $parts );
1141 }
1142
1143 /**
1144 * Generic wrapper function for a virus scanner program.
1145 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1146 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1147 *
1148 * @param $file String: pathname to the temporary upload file
1149 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1150 * or a string containing feedback from the virus scanner if a virus was found.
1151 * If textual feedback is missing but a virus was found, this function returns true.
1152 */
1153 public static function detectVirus( $file ) {
1154 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1155 wfProfileIn( __METHOD__ );
1156
1157 if ( !$wgAntivirus ) {
1158 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1159 wfProfileOut( __METHOD__ );
1160 return null;
1161 }
1162
1163 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1164 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1165 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1166 array( 'virus-badscanner', $wgAntivirus ) );
1167 wfProfileOut( __METHOD__ );
1168 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1169 }
1170
1171 # look up scanner configuration
1172 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1173 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1174 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1175 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1176
1177 if ( strpos( $command, "%f" ) === false ) {
1178 # simple pattern: append file to scan
1179 $command .= " " . wfEscapeShellArg( $file );
1180 } else {
1181 # complex pattern: replace "%f" with file to scan
1182 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1183 }
1184
1185 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1186
1187 # execute virus scanner
1188 $exitCode = false;
1189
1190 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1191 # that does not seem to be worth the pain.
1192 # Ask me (Duesentrieb) about it if it's ever needed.
1193 $output = wfShellExec( "$command 2>&1", $exitCode );
1194
1195 # map exit code to AV_xxx constants.
1196 $mappedCode = $exitCode;
1197 if ( $exitCodeMap ) {
1198 if ( isset( $exitCodeMap[$exitCode] ) ) {
1199 $mappedCode = $exitCodeMap[$exitCode];
1200 } elseif ( isset( $exitCodeMap["*"] ) ) {
1201 $mappedCode = $exitCodeMap["*"];
1202 }
1203 }
1204
1205 if ( $mappedCode === AV_SCAN_FAILED ) {
1206 # scan failed (code was mapped to false by $exitCodeMap)
1207 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1208
1209 if ( $wgAntivirusRequired ) {
1210 wfProfileOut( __METHOD__ );
1211 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1212 } else {
1213 wfProfileOut( __METHOD__ );
1214 return null;
1215 }
1216 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1217 # scan failed because filetype is unknown (probably imune)
1218 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1219 wfProfileOut( __METHOD__ );
1220 return null;
1221 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1222 # no virus found
1223 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1224 wfProfileOut( __METHOD__ );
1225 return false;
1226 } else {
1227 $output = trim( $output );
1228
1229 if ( !$output ) {
1230 $output = true; #if there's no output, return true
1231 } elseif ( $msgPattern ) {
1232 $groups = array();
1233 if ( preg_match( $msgPattern, $output, $groups ) ) {
1234 if ( $groups[1] ) {
1235 $output = $groups[1];
1236 }
1237 }
1238 }
1239
1240 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1241 wfProfileOut( __METHOD__ );
1242 return $output;
1243 }
1244 }
1245
1246 /**
1247 * Check if there's an overwrite conflict and, if so, if restrictions
1248 * forbid this user from performing the upload.
1249 *
1250 * @param $user User
1251 *
1252 * @return mixed true on success, array on failure
1253 */
1254 private function checkOverwrite( $user ) {
1255 // First check whether the local file can be overwritten
1256 $file = $this->getLocalFile();
1257 if( $file->exists() ) {
1258 if( !self::userCanReUpload( $user, $file ) ) {
1259 return array( 'fileexists-forbidden', $file->getName() );
1260 } else {
1261 return true;
1262 }
1263 }
1264
1265 /* Check shared conflicts: if the local file does not exist, but
1266 * wfFindFile finds a file, it exists in a shared repository.
1267 */
1268 $file = wfFindFile( $this->getTitle() );
1269 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1270 return array( 'fileexists-shared-forbidden', $file->getName() );
1271 }
1272
1273 return true;
1274 }
1275
1276 /**
1277 * Check if a user is the last uploader
1278 *
1279 * @param $user User object
1280 * @param $img String: image name
1281 * @return Boolean
1282 */
1283 public static function userCanReUpload( User $user, $img ) {
1284 if( $user->isAllowed( 'reupload' ) ) {
1285 return true; // non-conditional
1286 }
1287 if( !$user->isAllowed( 'reupload-own' ) ) {
1288 return false;
1289 }
1290 if( is_string( $img ) ) {
1291 $img = wfLocalFile( $img );
1292 }
1293 if ( !( $img instanceof LocalFile ) ) {
1294 return false;
1295 }
1296
1297 return $user->getId() == $img->getUser( 'id' );
1298 }
1299
1300 /**
1301 * Helper function that does various existence checks for a file.
1302 * The following checks are performed:
1303 * - The file exists
1304 * - Article with the same name as the file exists
1305 * - File exists with normalized extension
1306 * - The file looks like a thumbnail and the original exists
1307 *
1308 * @param $file File The File object to check
1309 * @return mixed False if the file does not exists, else an array
1310 */
1311 public static function getExistsWarning( $file ) {
1312 if( $file->exists() ) {
1313 return array( 'warning' => 'exists', 'file' => $file );
1314 }
1315
1316 if( $file->getTitle()->getArticleID() ) {
1317 return array( 'warning' => 'page-exists', 'file' => $file );
1318 }
1319
1320 if ( $file->wasDeleted() && !$file->exists() ) {
1321 return array( 'warning' => 'was-deleted', 'file' => $file );
1322 }
1323
1324 if( strpos( $file->getName(), '.' ) == false ) {
1325 $partname = $file->getName();
1326 $extension = '';
1327 } else {
1328 $n = strrpos( $file->getName(), '.' );
1329 $extension = substr( $file->getName(), $n + 1 );
1330 $partname = substr( $file->getName(), 0, $n );
1331 }
1332 $normalizedExtension = File::normalizeExtension( $extension );
1333
1334 if ( $normalizedExtension != $extension ) {
1335 // We're not using the normalized form of the extension.
1336 // Normal form is lowercase, using most common of alternate
1337 // extensions (eg 'jpg' rather than 'JPEG').
1338 //
1339 // Check for another file using the normalized form...
1340 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1341 $file_lc = wfLocalFile( $nt_lc );
1342
1343 if( $file_lc->exists() ) {
1344 return array(
1345 'warning' => 'exists-normalized',
1346 'file' => $file,
1347 'normalizedFile' => $file_lc
1348 );
1349 }
1350 }
1351
1352 if ( self::isThumbName( $file->getName() ) ) {
1353 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1354 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
1355 $file_thb = wfLocalFile( $nt_thb );
1356 if( $file_thb->exists() ) {
1357 return array(
1358 'warning' => 'thumb',
1359 'file' => $file,
1360 'thumbFile' => $file_thb
1361 );
1362 } else {
1363 // File does not exist, but we just don't like the name
1364 return array(
1365 'warning' => 'thumb-name',
1366 'file' => $file,
1367 'thumbFile' => $file_thb
1368 );
1369 }
1370 }
1371
1372
1373 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
1374 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1375 return array(
1376 'warning' => 'bad-prefix',
1377 'file' => $file,
1378 'prefix' => $prefix
1379 );
1380 }
1381 }
1382
1383 return false;
1384 }
1385
1386 /**
1387 * Helper function that checks whether the filename looks like a thumbnail
1388 * @return bool
1389 */
1390 public static function isThumbName( $filename ) {
1391 $n = strrpos( $filename, '.' );
1392 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1393 return (
1394 substr( $partname , 3, 3 ) == 'px-' ||
1395 substr( $partname , 2, 3 ) == 'px-'
1396 ) &&
1397 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1398 }
1399
1400 /**
1401 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1402 *
1403 * @return array list of prefixes
1404 */
1405 public static function getFilenamePrefixBlacklist() {
1406 $blacklist = array();
1407 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1408 if( !$message->isDisabled() ) {
1409 $lines = explode( "\n", $message->plain() );
1410 foreach( $lines as $line ) {
1411 // Remove comment lines
1412 $comment = substr( trim( $line ), 0, 1 );
1413 if ( $comment == '#' || $comment == '' ) {
1414 continue;
1415 }
1416 // Remove additional comments after a prefix
1417 $comment = strpos( $line, '#' );
1418 if ( $comment > 0 ) {
1419 $line = substr( $line, 0, $comment-1 );
1420 }
1421 $blacklist[] = trim( $line );
1422 }
1423 }
1424 return $blacklist;
1425 }
1426
1427 /**
1428 * Gets image info about the file just uploaded.
1429 *
1430 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1431 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1432 * with the appropriate format, presumably.
1433 *
1434 * @param $result ApiResult:
1435 * @return Array: image info
1436 */
1437 public function getImageInfo( $result ) {
1438 $file = $this->getLocalFile();
1439 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1440 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1441 if ( $file instanceof UploadStashFile ) {
1442 $imParam = ApiQueryStashImageInfo::getPropertyNames();
1443 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1444 } else {
1445 $imParam = ApiQueryImageInfo::getPropertyNames();
1446 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1447 }
1448 return $info;
1449 }
1450
1451
1452 public function convertVerifyErrorToStatus( $error ) {
1453 $code = $error['status'];
1454 unset( $code['status'] );
1455 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1456 }
1457
1458 public static function getMaxUploadSize( $forType = null ) {
1459 global $wgMaxUploadSize;
1460
1461 if ( is_array( $wgMaxUploadSize ) ) {
1462 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1463 return $wgMaxUploadSize[$forType];
1464 } else {
1465 return $wgMaxUploadSize['*'];
1466 }
1467 } else {
1468 return intval( $wgMaxUploadSize );
1469 }
1470
1471 }
1472 }