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