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