Make UploadBase::getTempFileSha1Base36 public
[lhc/web/wiklou.git] / includes / upload / UploadBase.php
1 <?php
2 /**
3 * Base class for the backend of file upload.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Upload
22 */
23
24 /**
25 * @defgroup Upload Upload related
26 */
27
28 /**
29 * @ingroup Upload
30 *
31 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
32 * The frontends are formed by ApiUpload and SpecialUpload.
33 *
34 * See also includes/docs/upload.txt
35 *
36 * @author Brion Vibber
37 * @author Bryan Tong Minh
38 * @author Michael Dale
39 */
40 abstract class UploadBase {
41 protected $mTempPath;
42 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
43 protected $mTitle = false, $mTitleError = 0;
44 protected $mFilteredName, $mFinalExtension;
45 protected $mLocalFile, $mFileSize, $mFileProps;
46 protected $mBlackListedExtensions;
47 protected $mJavaDetected;
48
49 const SUCCESS = 0;
50 const OK = 0;
51 const EMPTY_FILE = 3;
52 const MIN_LENGTH_PARTNAME = 4;
53 const ILLEGAL_FILENAME = 5;
54 const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
55 const FILETYPE_MISSING = 8;
56 const FILETYPE_BADTYPE = 9;
57 const VERIFICATION_ERROR = 10;
58
59 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
60 const UPLOAD_VERIFICATION_ERROR = 11;
61 const HOOK_ABORTED = 11;
62 const FILE_TOO_LARGE = 12;
63 const WINDOWS_NONASCII_FILENAME = 13;
64 const FILENAME_TOO_LONG = 14;
65
66 const SESSION_STATUS_KEY = 'wsUploadStatusData';
67
68 /**
69 * @param $error int
70 * @return string
71 */
72 public function getVerificationErrorCode( $error ) {
73 $code_to_status = array(self::EMPTY_FILE => 'empty-file',
74 self::FILE_TOO_LARGE => 'file-too-large',
75 self::FILETYPE_MISSING => 'filetype-missing',
76 self::FILETYPE_BADTYPE => 'filetype-banned',
77 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
78 self::ILLEGAL_FILENAME => 'illegal-filename',
79 self::OVERWRITE_EXISTING_FILE => 'overwrite',
80 self::VERIFICATION_ERROR => 'verification-error',
81 self::HOOK_ABORTED => 'hookaborted',
82 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
83 self::FILENAME_TOO_LONG => 'filename-toolong',
84 );
85 if( isset( $code_to_status[$error] ) ) {
86 return $code_to_status[$error];
87 }
88
89 return 'unknown-error';
90 }
91
92 /**
93 * Returns true if uploads are enabled.
94 * Can be override by subclasses.
95 * @return bool
96 */
97 public static function isEnabled() {
98 global $wgEnableUploads;
99
100 if ( !$wgEnableUploads ) {
101 return false;
102 }
103
104 # Check php's file_uploads setting
105 return wfIsHipHop() || wfIniGetBool( 'file_uploads' );
106 }
107
108 /**
109 * Returns true if the user can use this upload module or else a string
110 * identifying the missing permission.
111 * Can be overriden by subclasses.
112 *
113 * @param $user User
114 * @return bool
115 */
116 public static function isAllowed( $user ) {
117 foreach ( array( 'upload', 'edit' ) as $permission ) {
118 if ( !$user->isAllowed( $permission ) ) {
119 return $permission;
120 }
121 }
122 return true;
123 }
124
125 // Upload handlers. Should probably just be a global.
126 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
127
128 /**
129 * Create a form of UploadBase depending on wpSourceType and initializes it
130 *
131 * @param $request WebRequest
132 * @param $type
133 * @return null
134 */
135 public static function createFromRequest( &$request, $type = null ) {
136 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
137
138 if( !$type ) {
139 return null;
140 }
141
142 // Get the upload class
143 $type = ucfirst( $type );
144
145 // Give hooks the chance to handle this request
146 $className = null;
147 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
148 if ( is_null( $className ) ) {
149 $className = 'UploadFrom' . $type;
150 wfDebug( __METHOD__ . ": class name: $className\n" );
151 if( !in_array( $type, self::$uploadHandlers ) ) {
152 return null;
153 }
154 }
155
156 // Check whether this upload class is enabled
157 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
158 return null;
159 }
160
161 // Check whether the request is valid
162 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
163 return null;
164 }
165
166 $handler = new $className;
167
168 $handler->initializeFromRequest( $request );
169 return $handler;
170 }
171
172 /**
173 * Check whether a request if valid for this handler
174 * @param $request
175 * @return bool
176 */
177 public static function isValidRequest( $request ) {
178 return false;
179 }
180
181 public function __construct() {}
182
183 /**
184 * Returns the upload type. Should be overridden by child classes
185 *
186 * @since 1.18
187 * @return string
188 */
189 public function getSourceType() { return null; }
190
191 /**
192 * Initialize the path information
193 * @param $name string the desired destination name
194 * @param $tempPath string the temporary path
195 * @param $fileSize int the file size
196 * @param $removeTempFile bool (false) remove the temporary file?
197 * @throws MWException
198 */
199 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
200 $this->mDesiredDestName = $name;
201 if ( FileBackend::isStoragePath( $tempPath ) ) {
202 throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
203 }
204 $this->mTempPath = $tempPath;
205 $this->mFileSize = $fileSize;
206 $this->mRemoveTempFile = $removeTempFile;
207 }
208
209 /**
210 * Initialize from a WebRequest. Override this in a subclass.
211 */
212 abstract public function initializeFromRequest( &$request );
213
214 /**
215 * Fetch the file. Usually a no-op
216 * @return Status
217 */
218 public function fetchFile() {
219 return Status::newGood();
220 }
221
222 /**
223 * Return true if the file is empty
224 * @return bool
225 */
226 public function isEmptyFile() {
227 return empty( $this->mFileSize );
228 }
229
230 /**
231 * Return the file size
232 * @return integer
233 */
234 public function getFileSize() {
235 return $this->mFileSize;
236 }
237
238 /**
239 * Get the base 36 SHA1 of the file
240 * @return string
241 */
242 public function getTempFileSha1Base36() {
243 return FSFile::getSha1Base36FromPath( $this->mTempPath );
244 }
245
246 /**
247 * @param $srcPath String: the source path
248 * @return string the real path if it was a virtual URL
249 */
250 function getRealPath( $srcPath ) {
251 wfProfileIn( __METHOD__ );
252 $repo = RepoGroup::singleton()->getLocalRepo();
253 if ( $repo->isVirtualUrl( $srcPath ) ) {
254 // @TODO: just make uploads work with storage paths
255 // UploadFromStash loads files via virtuals URLs
256 $tmpFile = $repo->getLocalCopy( $srcPath );
257 $tmpFile->bind( $this ); // keep alive with $this
258 wfProfileOut( __METHOD__ );
259 return $tmpFile->getPath();
260 }
261 wfProfileOut( __METHOD__ );
262 return $srcPath;
263 }
264
265 /**
266 * Verify whether the upload is sane.
267 * @return mixed self::OK or else an array with error information
268 */
269 public function verifyUpload() {
270 wfProfileIn( __METHOD__ );
271
272 /**
273 * If there was no filename or a zero size given, give up quick.
274 */
275 if( $this->isEmptyFile() ) {
276 wfProfileOut( __METHOD__ );
277 return array( 'status' => self::EMPTY_FILE );
278 }
279
280 /**
281 * Honor $wgMaxUploadSize
282 */
283 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
284 if( $this->mFileSize > $maxSize ) {
285 wfProfileOut( __METHOD__ );
286 return array(
287 'status' => self::FILE_TOO_LARGE,
288 'max' => $maxSize,
289 );
290 }
291
292 /**
293 * Look at the contents of the file; if we can recognize the
294 * type but it's corrupt or data of the wrong type, we should
295 * probably not accept it.
296 */
297 $verification = $this->verifyFile();
298 if( $verification !== true ) {
299 wfProfileOut( __METHOD__ );
300 return array(
301 'status' => self::VERIFICATION_ERROR,
302 'details' => $verification
303 );
304 }
305
306 /**
307 * Make sure this file can be created
308 */
309 $result = $this->validateName();
310 if( $result !== true ) {
311 wfProfileOut( __METHOD__ );
312 return $result;
313 }
314
315 $error = '';
316 if( !wfRunHooks( 'UploadVerification',
317 array( $this->mDestName, $this->mTempPath, &$error ) ) )
318 {
319 wfProfileOut( __METHOD__ );
320 return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
321 }
322
323 wfProfileOut( __METHOD__ );
324 return array( 'status' => self::OK );
325 }
326
327 /**
328 * Verify that the name is valid and, if necessary, that we can overwrite
329 *
330 * @return mixed true if valid, otherwise and array with 'status'
331 * and other keys
332 **/
333 protected function validateName() {
334 $nt = $this->getTitle();
335 if( is_null( $nt ) ) {
336 $result = array( 'status' => $this->mTitleError );
337 if( $this->mTitleError == self::ILLEGAL_FILENAME ) {
338 $result['filtered'] = $this->mFilteredName;
339 }
340 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
341 $result['finalExt'] = $this->mFinalExtension;
342 if ( count( $this->mBlackListedExtensions ) ) {
343 $result['blacklistedExt'] = $this->mBlackListedExtensions;
344 }
345 }
346 return $result;
347 }
348 $this->mDestName = $this->getLocalFile()->getName();
349
350 return true;
351 }
352
353 /**
354 * Verify the mime type
355 *
356 * @param $mime string representing the mime
357 * @return mixed true if the file is verified, an array otherwise
358 */
359 protected function verifyMimeType( $mime ) {
360 global $wgVerifyMimeType;
361 wfProfileIn( __METHOD__ );
362 if ( $wgVerifyMimeType ) {
363 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" );
364 global $wgMimeTypeBlacklist;
365 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
366 wfProfileOut( __METHOD__ );
367 return array( 'filetype-badmime', $mime );
368 }
369
370 # XXX: Missing extension will be caught by validateName() via getTitle()
371 if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
372 wfProfileOut( __METHOD__ );
373 return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
374 }
375
376 # Check IE type
377 $fp = fopen( $this->mTempPath, 'rb' );
378 $chunk = fread( $fp, 256 );
379 fclose( $fp );
380
381 $magic = MimeMagic::singleton();
382 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
383 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
384 foreach ( $ieTypes as $ieType ) {
385 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
386 wfProfileOut( __METHOD__ );
387 return array( 'filetype-bad-ie-mime', $ieType );
388 }
389 }
390 }
391
392 wfProfileOut( __METHOD__ );
393 return true;
394 }
395
396 /**
397 * Verifies that it's ok to include the uploaded file
398 *
399 * @return mixed true of the file is verified, array otherwise.
400 */
401 protected function verifyFile() {
402 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
403 wfProfileIn( __METHOD__ );
404
405 # get the title, even though we are doing nothing with it, because
406 # we need to populate mFinalExtension
407 $this->getTitle();
408
409 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
410
411 # check mime type, if desired
412 $mime = $this->mFileProps['file-mime'];
413 $status = $this->verifyMimeType( $mime );
414 if ( $status !== true ) {
415 wfProfileOut( __METHOD__ );
416 return $status;
417 }
418
419 # check for htmlish code and javascript
420 if ( !$wgDisableUploadScriptChecks ) {
421 if( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
422 wfProfileOut( __METHOD__ );
423 return array( 'uploadscripted' );
424 }
425 if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
426 if( $this->detectScriptInSvg( $this->mTempPath ) ) {
427 wfProfileOut( __METHOD__ );
428 return array( 'uploadscripted' );
429 }
430 }
431 }
432
433 # Check for Java applets, which if uploaded can bypass cross-site
434 # restrictions.
435 if ( !$wgAllowJavaUploads ) {
436 $this->mJavaDetected = false;
437 $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
438 array( $this, 'zipEntryCallback' ) );
439 if ( !$zipStatus->isOK() ) {
440 $errors = $zipStatus->getErrorsArray();
441 $error = reset( $errors );
442 if ( $error[0] !== 'zip-wrong-format' ) {
443 wfProfileOut( __METHOD__ );
444 return $error;
445 }
446 }
447 if ( $this->mJavaDetected ) {
448 wfProfileOut( __METHOD__ );
449 return array( 'uploadjava' );
450 }
451 }
452
453 # Scan the uploaded file for viruses
454 $virus = $this->detectVirus( $this->mTempPath );
455 if ( $virus ) {
456 wfProfileOut( __METHOD__ );
457 return array( 'uploadvirus', $virus );
458 }
459
460 $handler = MediaHandler::getHandler( $mime );
461 if ( $handler ) {
462 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
463 if ( !$handlerStatus->isOK() ) {
464 $errors = $handlerStatus->getErrorsArray();
465 wfProfileOut( __METHOD__ );
466 return reset( $errors );
467 }
468 }
469
470 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
471 if ( $status !== true ) {
472 wfProfileOut( __METHOD__ );
473 return $status;
474 }
475
476 wfDebug( __METHOD__ . ": all clear; passing.\n" );
477 wfProfileOut( __METHOD__ );
478 return true;
479 }
480
481 /**
482 * Callback for ZipDirectoryReader to detect Java class files.
483 */
484 function zipEntryCallback( $entry ) {
485 $names = array( $entry['name'] );
486
487 // If there is a null character, cut off the name at it, because JDK's
488 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
489 // were constructed which had ".class\0" followed by a string chosen to
490 // make the hash collide with the truncated name, that file could be
491 // returned in response to a request for the .class file.
492 $nullPos = strpos( $entry['name'], "\000" );
493 if ( $nullPos !== false ) {
494 $names[] = substr( $entry['name'], 0, $nullPos );
495 }
496
497 // If there is a trailing slash in the file name, we have to strip it,
498 // because that's what ZIP_GetEntry() does.
499 if ( preg_grep( '!\.class/?$!', $names ) ) {
500 $this->mJavaDetected = true;
501 }
502 }
503
504 /**
505 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
506 * but that suggests it's checking the user, when it's really checking the title + user combination.
507 * @param $user User object to verify the permissions against
508 * @return mixed An array as returned by getUserPermissionsErrors or true
509 * in case the user has proper permissions.
510 */
511 public function verifyPermissions( $user ) {
512 return $this->verifyTitlePermissions( $user );
513 }
514
515 /**
516 * Check whether the user can edit, upload and create the image. This
517 * checks only against the current title; if it returns errors, it may
518 * very well be that another title will not give errors. Therefore
519 * isAllowed() should be called as well for generic is-user-blocked or
520 * can-user-upload checking.
521 *
522 * @param $user User object to verify the permissions against
523 * @return mixed An array as returned by getUserPermissionsErrors or true
524 * in case the user has proper permissions.
525 */
526 public function verifyTitlePermissions( $user ) {
527 /**
528 * If the image is protected, non-sysop users won't be able
529 * to modify it by uploading a new revision.
530 */
531 $nt = $this->getTitle();
532 if( is_null( $nt ) ) {
533 return true;
534 }
535 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
536 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
537 if ( !$nt->exists() ) {
538 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
539 } else {
540 $permErrorsCreate = array();
541 }
542 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
543 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
544 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
545 return $permErrors;
546 }
547
548 $overwriteError = $this->checkOverwrite( $user );
549 if ( $overwriteError !== true ) {
550 return array( $overwriteError );
551 }
552
553 return true;
554 }
555
556 /**
557 * Check for non fatal problems with the file.
558 *
559 * This should not assume that mTempPath is set.
560 *
561 * @return Array of warnings
562 */
563 public function checkWarnings() {
564 global $wgLang;
565 wfProfileIn( __METHOD__ );
566
567 $warnings = array();
568
569 $localFile = $this->getLocalFile();
570 $filename = $localFile->getName();
571
572 /**
573 * Check whether the resulting filename is different from the desired one,
574 * but ignore things like ucfirst() and spaces/underscore things
575 */
576 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
577 $comparableName = Title::capitalize( $comparableName, NS_FILE );
578
579 if( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
580 $warnings['badfilename'] = $filename;
581 }
582
583 // Check whether the file extension is on the unwanted list
584 global $wgCheckFileExtensions, $wgFileExtensions;
585 if ( $wgCheckFileExtensions ) {
586 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) {
587 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension,
588 $wgLang->commaList( $wgFileExtensions ), count( $wgFileExtensions ) );
589 }
590 }
591
592 global $wgUploadSizeWarning;
593 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
594 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize );
595 }
596
597 if ( $this->mFileSize == 0 ) {
598 $warnings['emptyfile'] = true;
599 }
600
601 $exists = self::getExistsWarning( $localFile );
602 if( $exists !== false ) {
603 $warnings['exists'] = $exists;
604 }
605
606 // Check dupes against existing files
607 $hash = $this->getTempFileSha1Base36();
608 $dupes = RepoGroup::singleton()->findBySha1( $hash );
609 $title = $this->getTitle();
610 // Remove all matches against self
611 foreach ( $dupes as $key => $dupe ) {
612 if( $title->equals( $dupe->getTitle() ) ) {
613 unset( $dupes[$key] );
614 }
615 }
616 if( $dupes ) {
617 $warnings['duplicate'] = $dupes;
618 }
619
620 // Check dupes against archives
621 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
622 if ( $archivedImage->getID() > 0 ) {
623 $warnings['duplicate-archive'] = $archivedImage->getName();
624 }
625
626 wfProfileOut( __METHOD__ );
627 return $warnings;
628 }
629
630 /**
631 * Really perform the upload. Stores the file in the local repo, watches
632 * if necessary and runs the UploadComplete hook.
633 *
634 * @param $comment
635 * @param $pageText
636 * @param $watch
637 * @param $user User
638 *
639 * @return Status indicating the whether the upload succeeded.
640 */
641 public function performUpload( $comment, $pageText, $watch, $user ) {
642 wfProfileIn( __METHOD__ );
643
644 $status = $this->getLocalFile()->upload(
645 $this->mTempPath,
646 $comment,
647 $pageText,
648 File::DELETE_SOURCE,
649 $this->mFileProps,
650 false,
651 $user
652 );
653
654 if( $status->isGood() ) {
655 if ( $watch ) {
656 $user->addWatch( $this->getLocalFile()->getTitle() );
657 }
658 wfRunHooks( 'UploadComplete', array( &$this ) );
659 }
660
661 wfProfileOut( __METHOD__ );
662 return $status;
663 }
664
665 /**
666 * Returns the title of the file to be uploaded. Sets mTitleError in case
667 * the name was illegal.
668 *
669 * @return Title The title of the file or null in case the name was illegal
670 */
671 public function getTitle() {
672 if ( $this->mTitle !== false ) {
673 return $this->mTitle;
674 }
675
676 /* Assume that if a user specified File:Something.jpg, this is an error
677 * and that the namespace prefix needs to be stripped of.
678 */
679 $title = Title::newFromText( $this->mDesiredDestName );
680 if ( $title && $title->getNamespace() == NS_FILE ) {
681 $this->mFilteredName = $title->getDBkey();
682 } else {
683 $this->mFilteredName = $this->mDesiredDestName;
684 }
685
686 # oi_archive_name is max 255 bytes, which include a timestamp and an
687 # exclamation mark, so restrict file name to 240 bytes.
688 if ( strlen( $this->mFilteredName ) > 240 ) {
689 $this->mTitleError = self::FILENAME_TOO_LONG;
690 return $this->mTitle = null;
691 }
692
693 /**
694 * Chop off any directories in the given filename. Then
695 * filter out illegal characters, and try to make a legible name
696 * out of it. We'll strip some silently that Title would die on.
697 */
698 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
699 /* Normalize to title form before we do any further processing */
700 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
701 if( is_null( $nt ) ) {
702 $this->mTitleError = self::ILLEGAL_FILENAME;
703 return $this->mTitle = null;
704 }
705 $this->mFilteredName = $nt->getDBkey();
706
707
708
709 /**
710 * We'll want to blacklist against *any* 'extension', and use
711 * only the final one for the whitelist.
712 */
713 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
714
715 if( count( $ext ) ) {
716 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
717 } else {
718 $this->mFinalExtension = '';
719
720 # No extension, try guessing one
721 $magic = MimeMagic::singleton();
722 $mime = $magic->guessMimeType( $this->mTempPath );
723 if ( $mime !== 'unknown/unknown' ) {
724 # Get a space separated list of extensions
725 $extList = $magic->getExtensionsForType( $mime );
726 if ( $extList ) {
727 # Set the extension to the canonical extension
728 $this->mFinalExtension = strtok( $extList, ' ' );
729
730 # Fix up the other variables
731 $this->mFilteredName .= ".{$this->mFinalExtension}";
732 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
733 $ext = array( $this->mFinalExtension );
734 }
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 $mime String: the mime type of the uploaded file
891 * @param $extension String: 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 $file String: pathname to the temporary upload file
932 * @param $mime String: the mime type of the file
933 * @param $extension String: 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 necessarry!
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 embeded 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 embeded (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 attibute '$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 attibute to '$value' in uploaded file.\n" );
1133 return true;
1134 }
1135
1136
1137 # use handler attribute with remote / data / script
1138 if( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1139 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1140 return true;
1141 }
1142
1143 # use CSS styles to bring in remote code
1144 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1145 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 ) ) {
1146 foreach ( $matches[1] as $match ) {
1147 if ( !preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1148 wfDebug( __METHOD__ . ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
1149 return true;
1150 }
1151 }
1152 }
1153
1154 # image filters can pull in url, which could be svg that executes scripts
1155 if( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1156 wfDebug( __METHOD__ . ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1157 return true;
1158 }
1159
1160 }
1161
1162 return false; //No scripts detected
1163 }
1164
1165 /**
1166 * @param $name string
1167 * @return string
1168 */
1169 private function stripXmlNamespace( $name ) {
1170 // 'http://www.w3.org/2000/svg:script' -> 'script'
1171 $parts = explode( ':', strtolower( $name ) );
1172 return array_pop( $parts );
1173 }
1174
1175 /**
1176 * Generic wrapper function for a virus scanner program.
1177 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1178 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1179 *
1180 * @param $file String: pathname to the temporary upload file
1181 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1182 * or a string containing feedback from the virus scanner if a virus was found.
1183 * If textual feedback is missing but a virus was found, this function returns true.
1184 */
1185 public static function detectVirus( $file ) {
1186 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1187 wfProfileIn( __METHOD__ );
1188
1189 if ( !$wgAntivirus ) {
1190 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1191 wfProfileOut( __METHOD__ );
1192 return null;
1193 }
1194
1195 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1196 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1197 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1198 array( 'virus-badscanner', $wgAntivirus ) );
1199 wfProfileOut( __METHOD__ );
1200 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1201 }
1202
1203 # look up scanner configuration
1204 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1205 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1206 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1207 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1208
1209 if ( strpos( $command, "%f" ) === false ) {
1210 # simple pattern: append file to scan
1211 $command .= " " . wfEscapeShellArg( $file );
1212 } else {
1213 # complex pattern: replace "%f" with file to scan
1214 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1215 }
1216
1217 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1218
1219 # execute virus scanner
1220 $exitCode = false;
1221
1222 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1223 # that does not seem to be worth the pain.
1224 # Ask me (Duesentrieb) about it if it's ever needed.
1225 $output = wfShellExec( "$command 2>&1", $exitCode );
1226
1227 # map exit code to AV_xxx constants.
1228 $mappedCode = $exitCode;
1229 if ( $exitCodeMap ) {
1230 if ( isset( $exitCodeMap[$exitCode] ) ) {
1231 $mappedCode = $exitCodeMap[$exitCode];
1232 } elseif ( isset( $exitCodeMap["*"] ) ) {
1233 $mappedCode = $exitCodeMap["*"];
1234 }
1235 }
1236
1237 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1238 * so we need the strict equalities === and thus can't use a switch here
1239 */
1240 if ( $mappedCode === AV_SCAN_FAILED ) {
1241 # scan failed (code was mapped to false by $exitCodeMap)
1242 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1243
1244 $output = $wgAntivirusRequired ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text() : null;
1245 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1246 # scan failed because filetype is unknown (probably imune)
1247 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1248 $output = null;
1249 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1250 # no virus found
1251 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1252 $output = false;
1253 } else {
1254 $output = trim( $output );
1255
1256 if ( !$output ) {
1257 $output = true; #if there's no output, return true
1258 } elseif ( $msgPattern ) {
1259 $groups = array();
1260 if ( preg_match( $msgPattern, $output, $groups ) ) {
1261 if ( $groups[1] ) {
1262 $output = $groups[1];
1263 }
1264 }
1265 }
1266
1267 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1268 }
1269
1270 wfProfileOut( __METHOD__ );
1271 return $output;
1272 }
1273
1274 /**
1275 * Check if there's an overwrite conflict and, if so, if restrictions
1276 * forbid this user from performing the upload.
1277 *
1278 * @param $user User
1279 *
1280 * @return mixed true on success, array on failure
1281 */
1282 private function checkOverwrite( $user ) {
1283 // First check whether the local file can be overwritten
1284 $file = $this->getLocalFile();
1285 if( $file->exists() ) {
1286 if( !self::userCanReUpload( $user, $file ) ) {
1287 return array( 'fileexists-forbidden', $file->getName() );
1288 } else {
1289 return true;
1290 }
1291 }
1292
1293 /* Check shared conflicts: if the local file does not exist, but
1294 * wfFindFile finds a file, it exists in a shared repository.
1295 */
1296 $file = wfFindFile( $this->getTitle() );
1297 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1298 return array( 'fileexists-shared-forbidden', $file->getName() );
1299 }
1300
1301 return true;
1302 }
1303
1304 /**
1305 * Check if a user is the last uploader
1306 *
1307 * @param $user User object
1308 * @param $img String: image name
1309 * @return Boolean
1310 */
1311 public static function userCanReUpload( User $user, $img ) {
1312 if( $user->isAllowed( 'reupload' ) ) {
1313 return true; // non-conditional
1314 }
1315 if( !$user->isAllowed( 'reupload-own' ) ) {
1316 return false;
1317 }
1318 if( is_string( $img ) ) {
1319 $img = wfLocalFile( $img );
1320 }
1321 if ( !( $img instanceof LocalFile ) ) {
1322 return false;
1323 }
1324
1325 return $user->getId() == $img->getUser( 'id' );
1326 }
1327
1328 /**
1329 * Helper function that does various existence checks for a file.
1330 * The following checks are performed:
1331 * - The file exists
1332 * - Article with the same name as the file exists
1333 * - File exists with normalized extension
1334 * - The file looks like a thumbnail and the original exists
1335 *
1336 * @param $file File The File object to check
1337 * @return mixed False if the file does not exists, else an array
1338 */
1339 public static function getExistsWarning( $file ) {
1340 if( $file->exists() ) {
1341 return array( 'warning' => 'exists', 'file' => $file );
1342 }
1343
1344 if( $file->getTitle()->getArticleID() ) {
1345 return array( 'warning' => 'page-exists', 'file' => $file );
1346 }
1347
1348 if ( $file->wasDeleted() && !$file->exists() ) {
1349 return array( 'warning' => 'was-deleted', 'file' => $file );
1350 }
1351
1352 if( strpos( $file->getName(), '.' ) == false ) {
1353 $partname = $file->getName();
1354 $extension = '';
1355 } else {
1356 $n = strrpos( $file->getName(), '.' );
1357 $extension = substr( $file->getName(), $n + 1 );
1358 $partname = substr( $file->getName(), 0, $n );
1359 }
1360 $normalizedExtension = File::normalizeExtension( $extension );
1361
1362 if ( $normalizedExtension != $extension ) {
1363 // We're not using the normalized form of the extension.
1364 // Normal form is lowercase, using most common of alternate
1365 // extensions (eg 'jpg' rather than 'JPEG').
1366 //
1367 // Check for another file using the normalized form...
1368 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1369 $file_lc = wfLocalFile( $nt_lc );
1370
1371 if( $file_lc->exists() ) {
1372 return array(
1373 'warning' => 'exists-normalized',
1374 'file' => $file,
1375 'normalizedFile' => $file_lc
1376 );
1377 }
1378 }
1379
1380 if ( self::isThumbName( $file->getName() ) ) {
1381 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1382 $nt_thb = Title::newFromText( substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension, NS_FILE );
1383 $file_thb = wfLocalFile( $nt_thb );
1384 if( $file_thb->exists() ) {
1385 return array(
1386 'warning' => 'thumb',
1387 'file' => $file,
1388 'thumbFile' => $file_thb
1389 );
1390 } else {
1391 // File does not exist, but we just don't like the name
1392 return array(
1393 'warning' => 'thumb-name',
1394 'file' => $file,
1395 'thumbFile' => $file_thb
1396 );
1397 }
1398 }
1399
1400
1401 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
1402 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1403 return array(
1404 'warning' => 'bad-prefix',
1405 'file' => $file,
1406 'prefix' => $prefix
1407 );
1408 }
1409 }
1410
1411 return false;
1412 }
1413
1414 /**
1415 * Helper function that checks whether the filename looks like a thumbnail
1416 * @param $filename string
1417 * @return bool
1418 */
1419 public static function isThumbName( $filename ) {
1420 $n = strrpos( $filename, '.' );
1421 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1422 return (
1423 substr( $partname, 3, 3 ) == 'px-' ||
1424 substr( $partname, 2, 3 ) == 'px-'
1425 ) &&
1426 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1427 }
1428
1429 /**
1430 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1431 *
1432 * @return array list of prefixes
1433 */
1434 public static function getFilenamePrefixBlacklist() {
1435 $blacklist = array();
1436 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1437 if( !$message->isDisabled() ) {
1438 $lines = explode( "\n", $message->plain() );
1439 foreach( $lines as $line ) {
1440 // Remove comment lines
1441 $comment = substr( trim( $line ), 0, 1 );
1442 if ( $comment == '#' || $comment == '' ) {
1443 continue;
1444 }
1445 // Remove additional comments after a prefix
1446 $comment = strpos( $line, '#' );
1447 if ( $comment > 0 ) {
1448 $line = substr( $line, 0, $comment-1 );
1449 }
1450 $blacklist[] = trim( $line );
1451 }
1452 }
1453 return $blacklist;
1454 }
1455
1456 /**
1457 * Gets image info about the file just uploaded.
1458 *
1459 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1460 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1461 * with the appropriate format, presumably.
1462 *
1463 * @param $result ApiResult:
1464 * @return Array: image info
1465 */
1466 public function getImageInfo( $result ) {
1467 $file = $this->getLocalFile();
1468 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1469 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1470 if ( $file instanceof UploadStashFile ) {
1471 $imParam = ApiQueryStashImageInfo::getPropertyNames();
1472 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1473 } else {
1474 $imParam = ApiQueryImageInfo::getPropertyNames();
1475 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1476 }
1477 return $info;
1478 }
1479
1480 /**
1481 * @param $error array
1482 * @return Status
1483 */
1484 public function convertVerifyErrorToStatus( $error ) {
1485 $code = $error['status'];
1486 unset( $code['status'] );
1487 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1488 }
1489
1490 /**
1491 * @param $forType null|string
1492 * @return int
1493 */
1494 public static function getMaxUploadSize( $forType = null ) {
1495 global $wgMaxUploadSize;
1496
1497 if ( is_array( $wgMaxUploadSize ) ) {
1498 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1499 return $wgMaxUploadSize[$forType];
1500 } else {
1501 return $wgMaxUploadSize['*'];
1502 }
1503 } else {
1504 return intval( $wgMaxUploadSize );
1505 }
1506 }
1507
1508 /**
1509 * Get the current status of a chunked upload (used for polling).
1510 * The status will be read from the *current* user session.
1511 * @param $statusKey string
1512 * @return Array|bool
1513 */
1514 public static function getSessionStatus( $statusKey ) {
1515 return isset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] )
1516 ? $_SESSION[self::SESSION_STATUS_KEY][$statusKey]
1517 : false;
1518 }
1519
1520 /**
1521 * Set the current status of a chunked upload (used for polling).
1522 * The status will be stored in the *current* user session.
1523 * @param $statusKey string
1524 * @param $value array|false
1525 * @return void
1526 */
1527 public static function setSessionStatus( $statusKey, $value ) {
1528 if ( $value === false ) {
1529 unset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] );
1530 } else {
1531 $_SESSION[self::SESSION_STATUS_KEY][$statusKey] = $value;
1532 }
1533 }
1534 }