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