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