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