MediaWiki  master
UploadBase.php
Go to the documentation of this file.
1 <?php
38 abstract class UploadBase {
39  protected $mTempPath;
41  protected $mTitle = false, $mTitleError = 0;
46 
47  protected static $safeXmlEncodings = array(
48  'UTF-8',
49  'ISO-8859-1',
50  'ISO-8859-2',
51  'UTF-16',
52  'UTF-32'
53  );
54 
55  const SUCCESS = 0;
56  const OK = 0;
57  const EMPTY_FILE = 3;
59  const ILLEGAL_FILENAME = 5;
60  const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
61  const FILETYPE_MISSING = 8;
62  const FILETYPE_BADTYPE = 9;
63  const VERIFICATION_ERROR = 10;
64  const HOOK_ABORTED = 11;
65  const FILE_TOO_LARGE = 12;
67  const FILENAME_TOO_LONG = 14;
68 
74  $code_to_status = array(
75  self::EMPTY_FILE => 'empty-file',
76  self::FILE_TOO_LARGE => 'file-too-large',
77  self::FILETYPE_MISSING => 'filetype-missing',
78  self::FILETYPE_BADTYPE => 'filetype-banned',
79  self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
80  self::ILLEGAL_FILENAME => 'illegal-filename',
81  self::OVERWRITE_EXISTING_FILE => 'overwrite',
82  self::VERIFICATION_ERROR => 'verification-error',
83  self::HOOK_ABORTED => 'hookaborted',
84  self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
85  self::FILENAME_TOO_LONG => 'filename-toolong',
86  );
87  if ( isset( $code_to_status[$error] ) ) {
88  return $code_to_status[$error];
89  }
90 
91  return 'unknown-error';
92  }
93 
99  public static function isEnabled() {
101 
102  if ( !$wgEnableUploads ) {
103  return false;
104  }
105 
106  # Check php's file_uploads setting
107  return wfIsHHVM() || wfIniGetBool( 'file_uploads' );
108  }
109 
118  public static function isAllowed( $user ) {
119  foreach ( array( 'upload', 'edit' ) as $permission ) {
120  if ( !$user->isAllowed( $permission ) ) {
121  return $permission;
122  }
123  }
124 
125  return true;
126  }
127 
134  public static function isThrottled( $user ) {
135  return $user->pingLimiter( 'upload' );
136  }
137 
138  // Upload handlers. Should probably just be a global.
139  private static $uploadHandlers = array( 'Stash', 'File', 'Url' );
140 
148  public static function createFromRequest( &$request, $type = null ) {
149  $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
150 
151  if ( !$type ) {
152  return null;
153  }
154 
155  // Get the upload class
156  $type = ucfirst( $type );
157 
158  // Give hooks the chance to handle this request
159  $className = null;
160  Hooks::run( 'UploadCreateFromRequest', array( $type, &$className ) );
161  if ( is_null( $className ) ) {
162  $className = 'UploadFrom' . $type;
163  wfDebug( __METHOD__ . ": class name: $className\n" );
164  if ( !in_array( $type, self::$uploadHandlers ) ) {
165  return null;
166  }
167  }
168 
169  // Check whether this upload class is enabled
170  if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
171  return null;
172  }
173 
174  // Check whether the request is valid
175  if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
176  return null;
177  }
178 
180  $handler = new $className;
181 
182  $handler->initializeFromRequest( $request );
183 
184  return $handler;
185  }
186 
192  public static function isValidRequest( $request ) {
193  return false;
194  }
195 
196  public function __construct() {
197  }
198 
205  public function getSourceType() {
206  return null;
207  }
208 
217  public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
218  $this->mDesiredDestName = $name;
219  if ( FileBackend::isStoragePath( $tempPath ) ) {
220  throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
221  }
222  $this->mTempPath = $tempPath;
223  $this->mFileSize = $fileSize;
224  $this->mRemoveTempFile = $removeTempFile;
225  }
226 
232  abstract public function initializeFromRequest( &$request );
233 
238  public function fetchFile() {
239  return Status::newGood();
240  }
241 
246  public function isEmptyFile() {
247  return empty( $this->mFileSize );
248  }
249 
254  public function getFileSize() {
255  return $this->mFileSize;
256  }
257 
262  public function getTempFileSha1Base36() {
263  return FSFile::getSha1Base36FromPath( $this->mTempPath );
264  }
265 
270  function getRealPath( $srcPath ) {
271  $repo = RepoGroup::singleton()->getLocalRepo();
272  if ( $repo->isVirtualUrl( $srcPath ) ) {
276  $tmpFile = $repo->getLocalCopy( $srcPath );
277  if ( $tmpFile ) {
278  $tmpFile->bind( $this ); // keep alive with $this
279  }
280  $path = $tmpFile ? $tmpFile->getPath() : false;
281  } else {
282  $path = $srcPath;
283  }
284 
285  return $path;
286  }
287 
292  public function verifyUpload() {
293 
297  if ( $this->isEmptyFile() ) {
298  return array( 'status' => self::EMPTY_FILE );
299  }
300 
304  $maxSize = self::getMaxUploadSize( $this->getSourceType() );
305  if ( $this->mFileSize > $maxSize ) {
306  return array(
307  'status' => self::FILE_TOO_LARGE,
308  'max' => $maxSize,
309  );
310  }
311 
317  $verification = $this->verifyFile();
318  if ( $verification !== true ) {
319  return array(
320  'status' => self::VERIFICATION_ERROR,
321  'details' => $verification
322  );
323  }
324 
328  $result = $this->validateName();
329  if ( $result !== true ) {
330  return $result;
331  }
332 
333  $error = '';
334  if ( !Hooks::run( 'UploadVerification',
335  array( $this->mDestName, $this->mTempPath, &$error ) )
336  ) {
337  return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
338  }
339 
340  return array( 'status' => self::OK );
341  }
342 
349  public function validateName() {
350  $nt = $this->getTitle();
351  if ( is_null( $nt ) ) {
352  $result = array( 'status' => $this->mTitleError );
353  if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
354  $result['filtered'] = $this->mFilteredName;
355  }
356  if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
357  $result['finalExt'] = $this->mFinalExtension;
358  if ( count( $this->mBlackListedExtensions ) ) {
359  $result['blacklistedExt'] = $this->mBlackListedExtensions;
360  }
361  }
362 
363  return $result;
364  }
365  $this->mDestName = $this->getLocalFile()->getName();
366 
367  return true;
368  }
369 
379  protected function verifyMimeType( $mime ) {
381  if ( $wgVerifyMimeType ) {
382  wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
384  if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
385  return array( 'filetype-badmime', $mime );
386  }
387 
388  # Check what Internet Explorer would detect
389  $fp = fopen( $this->mTempPath, 'rb' );
390  $chunk = fread( $fp, 256 );
391  fclose( $fp );
392 
393  $magic = MimeMagic::singleton();
394  $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
395  $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
396  foreach ( $ieTypes as $ieType ) {
397  if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
398  return array( 'filetype-bad-ie-mime', $ieType );
399  }
400  }
401  }
402 
403  return true;
404  }
405 
411  protected function verifyFile() {
413 
414  $status = $this->verifyPartialFile();
415  if ( $status !== true ) {
416  return $status;
417  }
418 
419  $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
420  $mime = $this->mFileProps['mime'];
421 
422  if ( $wgVerifyMimeType ) {
423  # XXX: Missing extension will be caught by validateName() via getTitle()
424  if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
425  return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
426  }
427  }
428 
429  # check for htmlish code and javascript
430  if ( !$wgDisableUploadScriptChecks ) {
431  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
432  $svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
433  if ( $svgStatus !== false ) {
434  return $svgStatus;
435  }
436  }
437  }
438 
439  $handler = MediaHandler::getHandler( $mime );
440  if ( $handler ) {
441  $handlerStatus = $handler->verifyUpload( $this->mTempPath );
442  if ( !$handlerStatus->isOK() ) {
443  $errors = $handlerStatus->getErrorsArray();
444 
445  return reset( $errors );
446  }
447  }
448 
449  Hooks::run( 'UploadVerifyFile', array( $this, $mime, &$status ) );
450  if ( $status !== true ) {
451  return $status;
452  }
453 
454  wfDebug( __METHOD__ . ": all clear; passing.\n" );
455 
456  return true;
457  }
458 
467  protected function verifyPartialFile() {
469 
470  # getTitle() sets some internal parameters like $this->mFinalExtension
471  $this->getTitle();
472 
473  $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
474 
475  # check MIME type, if desired
476  $mime = $this->mFileProps['file-mime'];
477  $status = $this->verifyMimeType( $mime );
478  if ( $status !== true ) {
479  return $status;
480  }
481 
482  # check for htmlish code and javascript
483  if ( !$wgDisableUploadScriptChecks ) {
484  if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
485  return array( 'uploadscripted' );
486  }
487  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
488  $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
489  if ( $svgStatus !== false ) {
490  return $svgStatus;
491  }
492  }
493  }
494 
495  # Check for Java applets, which if uploaded can bypass cross-site
496  # restrictions.
497  if ( !$wgAllowJavaUploads ) {
498  $this->mJavaDetected = false;
499  $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
500  array( $this, 'zipEntryCallback' ) );
501  if ( !$zipStatus->isOK() ) {
502  $errors = $zipStatus->getErrorsArray();
503  $error = reset( $errors );
504  if ( $error[0] !== 'zip-wrong-format' ) {
505  return $error;
506  }
507  }
508  if ( $this->mJavaDetected ) {
509  return array( 'uploadjava' );
510  }
511  }
512 
513  # Scan the uploaded file for viruses
514  $virus = $this->detectVirus( $this->mTempPath );
515  if ( $virus ) {
516  return array( 'uploadvirus', $virus );
517  }
518 
519  return true;
520  }
521 
527  function zipEntryCallback( $entry ) {
528  $names = array( $entry['name'] );
529 
530  // If there is a null character, cut off the name at it, because JDK's
531  // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
532  // were constructed which had ".class\0" followed by a string chosen to
533  // make the hash collide with the truncated name, that file could be
534  // returned in response to a request for the .class file.
535  $nullPos = strpos( $entry['name'], "\000" );
536  if ( $nullPos !== false ) {
537  $names[] = substr( $entry['name'], 0, $nullPos );
538  }
539 
540  // If there is a trailing slash in the file name, we have to strip it,
541  // because that's what ZIP_GetEntry() does.
542  if ( preg_grep( '!\.class/?$!', $names ) ) {
543  $this->mJavaDetected = true;
544  }
545  }
546 
556  public function verifyPermissions( $user ) {
557  return $this->verifyTitlePermissions( $user );
558  }
559 
571  public function verifyTitlePermissions( $user ) {
576  $nt = $this->getTitle();
577  if ( is_null( $nt ) ) {
578  return true;
579  }
580  $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
581  $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
582  if ( !$nt->exists() ) {
583  $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
584  } else {
585  $permErrorsCreate = array();
586  }
587  if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
588  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
589  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
590 
591  return $permErrors;
592  }
593 
594  $overwriteError = $this->checkOverwrite( $user );
595  if ( $overwriteError !== true ) {
596  return array( $overwriteError );
597  }
598 
599  return true;
600  }
601 
609  public function checkWarnings() {
610  global $wgLang;
611 
612  $warnings = array();
613 
614  $localFile = $this->getLocalFile();
615  $localFile->load( File::READ_LATEST );
616  $filename = $localFile->getName();
617 
622  $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
623  $comparableName = Title::capitalize( $comparableName, NS_FILE );
624 
625  if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
626  $warnings['badfilename'] = $filename;
627  // Debugging for bug 62241
628  wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: "
629  . "'$this->mDesiredDestName', comparableName: '$comparableName'" );
630  }
631 
632  // Check whether the file extension is on the unwanted list
634  if ( $wgCheckFileExtensions ) {
635  $extensions = array_unique( $wgFileExtensions );
636  if ( !$this->checkFileExtension( $this->mFinalExtension, $extensions ) ) {
637  $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension,
638  $wgLang->commaList( $extensions ), count( $extensions ) );
639  }
640  }
641 
643  if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
644  $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize );
645  }
646 
647  if ( $this->mFileSize == 0 ) {
648  $warnings['emptyfile'] = true;
649  }
650 
651  $exists = self::getExistsWarning( $localFile );
652  if ( $exists !== false ) {
653  $warnings['exists'] = $exists;
654  }
655 
656  if ( $localFile->wasDeleted() && !$localFile->exists() ) {
657  $warnings['was-deleted'] = $filename;
658  }
659 
660  // Check dupes against existing files
661  $hash = $this->getTempFileSha1Base36();
662  $dupes = RepoGroup::singleton()->findBySha1( $hash );
663  $title = $this->getTitle();
664  // Remove all matches against self
665  foreach ( $dupes as $key => $dupe ) {
666  if ( $title->equals( $dupe->getTitle() ) ) {
667  unset( $dupes[$key] );
668  }
669  }
670  if ( $dupes ) {
671  $warnings['duplicate'] = $dupes;
672  }
673 
674  // Check dupes against archives
675  $archivedFile = new ArchivedFile( null, 0, '', $hash );
676  if ( $archivedFile->getID() > 0 ) {
677  if ( $archivedFile->userCan( File::DELETED_FILE ) ) {
678  $warnings['duplicate-archive'] = $archivedFile->getName();
679  } else {
680  $warnings['duplicate-archive'] = '';
681  }
682  }
683 
684  return $warnings;
685  }
686 
700  public function performUpload( $comment, $pageText, $watch, $user, $tags = array() ) {
701  $this->getLocalFile()->load( File::READ_LATEST );
702 
703  $status = $this->getLocalFile()->upload(
704  $this->mTempPath,
705  $comment,
706  $pageText,
708  $this->mFileProps,
709  false,
710  $user,
711  $tags
712  );
713 
714  if ( $status->isGood() ) {
715  if ( $watch ) {
717  $this->getLocalFile()->getTitle(),
718  $user,
720  );
721  }
722  Hooks::run( 'UploadComplete', array( &$this ) );
723 
724  $this->postProcessUpload();
725  }
726 
727  return $status;
728  }
729 
735  public function postProcessUpload() {
737 
738  $jobs = array();
739 
741  rsort( $sizes );
742 
743  $file = $this->getLocalFile();
744 
745  foreach ( $sizes as $size ) {
746  if ( $file->isVectorized() || $file->getWidth() > $size ) {
747  $jobs[] = new ThumbnailRenderJob(
748  $file->getTitle(),
749  array( 'transformParams' => array( 'width' => $size ) )
750  );
751  }
752  }
753 
754  if ( $jobs ) {
755  JobQueueGroup::singleton()->push( $jobs );
756  }
757  }
758 
765  public function getTitle() {
766  if ( $this->mTitle !== false ) {
767  return $this->mTitle;
768  }
769  if ( !is_string( $this->mDesiredDestName ) ) {
770  $this->mTitleError = self::ILLEGAL_FILENAME;
771  $this->mTitle = null;
772 
773  return $this->mTitle;
774  }
775  /* Assume that if a user specified File:Something.jpg, this is an error
776  * and that the namespace prefix needs to be stripped of.
777  */
778  $title = Title::newFromText( $this->mDesiredDestName );
779  if ( $title && $title->getNamespace() == NS_FILE ) {
780  $this->mFilteredName = $title->getDBkey();
781  } else {
782  $this->mFilteredName = $this->mDesiredDestName;
783  }
784 
785  # oi_archive_name is max 255 bytes, which include a timestamp and an
786  # exclamation mark, so restrict file name to 240 bytes.
787  if ( strlen( $this->mFilteredName ) > 240 ) {
788  $this->mTitleError = self::FILENAME_TOO_LONG;
789  $this->mTitle = null;
790 
791  return $this->mTitle;
792  }
793 
799  $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
800  /* Normalize to title form before we do any further processing */
801  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
802  if ( is_null( $nt ) ) {
803  $this->mTitleError = self::ILLEGAL_FILENAME;
804  $this->mTitle = null;
805 
806  return $this->mTitle;
807  }
808  $this->mFilteredName = $nt->getDBkey();
809 
814  list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
815 
816  if ( count( $ext ) ) {
817  $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
818  } else {
819  $this->mFinalExtension = '';
820 
821  # No extension, try guessing one
822  $magic = MimeMagic::singleton();
823  $mime = $magic->guessMimeType( $this->mTempPath );
824  if ( $mime !== 'unknown/unknown' ) {
825  # Get a space separated list of extensions
826  $extList = $magic->getExtensionsForType( $mime );
827  if ( $extList ) {
828  # Set the extension to the canonical extension
829  $this->mFinalExtension = strtok( $extList, ' ' );
830 
831  # Fix up the other variables
832  $this->mFilteredName .= ".{$this->mFinalExtension}";
833  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
834  $ext = array( $this->mFinalExtension );
835  }
836  }
837  }
838 
839  /* Don't allow users to override the blacklist (check file extension) */
842 
843  $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
844 
845  if ( $this->mFinalExtension == '' ) {
846  $this->mTitleError = self::FILETYPE_MISSING;
847  $this->mTitle = null;
848 
849  return $this->mTitle;
850  } elseif ( $blackListedExtensions ||
851  ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
852  !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
853  ) {
854  $this->mBlackListedExtensions = $blackListedExtensions;
855  $this->mTitleError = self::FILETYPE_BADTYPE;
856  $this->mTitle = null;
857 
858  return $this->mTitle;
859  }
860 
861  // Windows may be broken with special characters, see bug 1780
862  if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
863  && !RepoGroup::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
864  ) {
865  $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
866  $this->mTitle = null;
867 
868  return $this->mTitle;
869  }
870 
871  # If there was more than one "extension", reassemble the base
872  # filename to prevent bogus complaints about length
873  if ( count( $ext ) > 1 ) {
874  $iterations = count( $ext ) - 1;
875  for ( $i = 0; $i < $iterations; $i++ ) {
876  $partname .= '.' . $ext[$i];
877  }
878  }
879 
880  if ( strlen( $partname ) < 1 ) {
881  $this->mTitleError = self::MIN_LENGTH_PARTNAME;
882  $this->mTitle = null;
883 
884  return $this->mTitle;
885  }
886 
887  $this->mTitle = $nt;
888 
889  return $this->mTitle;
890  }
891 
897  public function getLocalFile() {
898  if ( is_null( $this->mLocalFile ) ) {
899  $nt = $this->getTitle();
900  $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
901  }
902 
903  return $this->mLocalFile;
904  }
905 
921  public function stashFile( User $user = null ) {
922  // was stashSessionFile
923 
924  $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user );
925  $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
926  $this->mLocalFile = $file;
927 
928  return $file;
929  }
930 
937  public function stashFileGetKey() {
938  return $this->stashFile()->getFileKey();
939  }
940 
946  public function stashSession() {
947  return $this->stashFileGetKey();
948  }
949 
954  public function cleanupTempFile() {
955  if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
956  wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
957  unlink( $this->mTempPath );
958  }
959  }
960 
961  public function getTempPath() {
962  return $this->mTempPath;
963  }
964 
974  public static function splitExtensions( $filename ) {
975  $bits = explode( '.', $filename );
976  $basename = array_shift( $bits );
977 
978  return array( $basename, $bits );
979  }
980 
989  public static function checkFileExtension( $ext, $list ) {
990  return in_array( strtolower( $ext ), $list );
991  }
992 
1001  public static function checkFileExtensionList( $ext, $list ) {
1002  return array_intersect( array_map( 'strtolower', $ext ), $list );
1003  }
1004 
1012  public static function verifyExtension( $mime, $extension ) {
1013  $magic = MimeMagic::singleton();
1014 
1015  if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) {
1016  if ( !$magic->isRecognizableExtension( $extension ) ) {
1017  wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
1018  "unrecognized extension '$extension', can't verify\n" );
1019 
1020  return true;
1021  } else {
1022  wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1023  "recognized extension '$extension', so probably invalid file\n" );
1024 
1025  return false;
1026  }
1027  }
1028 
1029  $match = $magic->isMatchingExtension( $extension, $mime );
1030 
1031  if ( $match === null ) {
1032  if ( $magic->getTypesForExtension( $extension ) !== null ) {
1033  wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension\n" );
1034 
1035  return false;
1036  } else {
1037  wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
1038 
1039  return true;
1040  }
1041  } elseif ( $match === true ) {
1042  wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
1043 
1045  return true;
1046  } else {
1047  wfDebug( __METHOD__
1048  . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
1049 
1050  return false;
1051  }
1052  }
1053 
1065  public static function detectScript( $file, $mime, $extension ) {
1067 
1068  # ugly hack: for text files, always look at the entire file.
1069  # For binary field, just check the first K.
1070 
1071  if ( strpos( $mime, 'text/' ) === 0 ) {
1072  $chunk = file_get_contents( $file );
1073  } else {
1074  $fp = fopen( $file, 'rb' );
1075  $chunk = fread( $fp, 1024 );
1076  fclose( $fp );
1077  }
1078 
1079  $chunk = strtolower( $chunk );
1080 
1081  if ( !$chunk ) {
1082  return false;
1083  }
1084 
1085  # decode from UTF-16 if needed (could be used for obfuscation).
1086  if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1087  $enc = 'UTF-16BE';
1088  } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1089  $enc = 'UTF-16LE';
1090  } else {
1091  $enc = null;
1092  }
1093 
1094  if ( $enc ) {
1095  $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1096  }
1097 
1098  $chunk = trim( $chunk );
1099 
1101  wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
1102 
1103  # check for HTML doctype
1104  if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1105  return true;
1106  }
1107 
1108  // Some browsers will interpret obscure xml encodings as UTF-8, while
1109  // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1110  if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
1111  if ( self::checkXMLEncodingMissmatch( $file ) ) {
1112  return true;
1113  }
1114  }
1115 
1131  $tags = array(
1132  '<a href',
1133  '<body',
1134  '<head',
1135  '<html', # also in safari
1136  '<img',
1137  '<pre',
1138  '<script', # also in safari
1139  '<table'
1140  );
1141 
1142  if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1143  $tags[] = '<title';
1144  }
1145 
1146  foreach ( $tags as $tag ) {
1147  if ( false !== strpos( $chunk, $tag ) ) {
1148  wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
1149 
1150  return true;
1151  }
1152  }
1153 
1154  /*
1155  * look for JavaScript
1156  */
1157 
1158  # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1159  $chunk = Sanitizer::decodeCharReferences( $chunk );
1160 
1161  # look for script-types
1162  if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1163  wfDebug( __METHOD__ . ": found script types\n" );
1164 
1165  return true;
1166  }
1167 
1168  # look for html-style script-urls
1169  if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1170  wfDebug( __METHOD__ . ": found html-style script urls\n" );
1171 
1172  return true;
1173  }
1174 
1175  # look for css-style script-urls
1176  if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1177  wfDebug( __METHOD__ . ": found css-style script urls\n" );
1178 
1179  return true;
1180  }
1181 
1182  wfDebug( __METHOD__ . ": no scripts found\n" );
1183 
1184  return false;
1185  }
1186 
1194  public static function checkXMLEncodingMissmatch( $file ) {
1196  $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1197  $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1198 
1199  if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1200  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1201  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1202  ) {
1203  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1204 
1205  return true;
1206  }
1207  } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1208  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1209  // bytes. There shouldn't be a legitimate reason for this to happen.
1210  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1211 
1212  return true;
1213  } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1214  // EBCDIC encoded XML
1215  wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" );
1216 
1217  return true;
1218  }
1219 
1220  // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1221  // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1222  $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1223  foreach ( $attemptEncodings as $encoding ) {
1224  MediaWiki\suppressWarnings();
1225  $str = iconv( $encoding, 'UTF-8', $contents );
1226  MediaWiki\restoreWarnings();
1227  if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1228  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1229  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1230  ) {
1231  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1232 
1233  return true;
1234  }
1235  } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1236  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1237  // bytes. There shouldn't be a legitimate reason for this to happen.
1238  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1239 
1240  return true;
1241  }
1242  }
1243 
1244  return false;
1245  }
1246 
1252  protected function detectScriptInSvg( $filename, $partial ) {
1253  $this->mSVGNSError = false;
1254  $check = new XmlTypeCheck(
1255  $filename,
1256  array( $this, 'checkSvgScriptCallback' ),
1257  true,
1258  array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1259  );
1260  if ( $check->wellFormed !== true ) {
1261  // Invalid xml (bug 58553)
1262  // But only when non-partial (bug 65724)
1263  return $partial ? false : array( 'uploadinvalidxml' );
1264  } elseif ( $check->filterMatch ) {
1265  if ( $this->mSVGNSError ) {
1266  return array( 'uploadscriptednamespace', $this->mSVGNSError );
1267  }
1268 
1269  return $check->filterMatchType;
1270  }
1271 
1272  return false;
1273  }
1274 
1281  public static function checkSvgPICallback( $target, $data ) {
1282  // Don't allow external stylesheets (bug 57550)
1283  if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1284  return array( 'upload-scripted-pi-callback' );
1285  }
1286 
1287  return false;
1288  }
1289 
1296  public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1297 
1298  list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1299 
1300  // We specifically don't include:
1301  // http://www.w3.org/1999/xhtml (bug 60771)
1302  static $validNamespaces = array(
1303  '',
1304  'adobe:ns:meta/',
1305  'http://creativecommons.org/ns#',
1306  'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1307  'http://ns.adobe.com/adobeillustrator/10.0/',
1308  'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1309  'http://ns.adobe.com/extensibility/1.0/',
1310  'http://ns.adobe.com/flows/1.0/',
1311  'http://ns.adobe.com/illustrator/1.0/',
1312  'http://ns.adobe.com/imagereplacement/1.0/',
1313  'http://ns.adobe.com/pdf/1.3/',
1314  'http://ns.adobe.com/photoshop/1.0/',
1315  'http://ns.adobe.com/saveforweb/1.0/',
1316  'http://ns.adobe.com/variables/1.0/',
1317  'http://ns.adobe.com/xap/1.0/',
1318  'http://ns.adobe.com/xap/1.0/g/',
1319  'http://ns.adobe.com/xap/1.0/g/img/',
1320  'http://ns.adobe.com/xap/1.0/mm/',
1321  'http://ns.adobe.com/xap/1.0/rights/',
1322  'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1323  'http://ns.adobe.com/xap/1.0/stype/font#',
1324  'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1325  'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1326  'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1327  'http://ns.adobe.com/xap/1.0/t/pg/',
1328  'http://purl.org/dc/elements/1.1/',
1329  'http://purl.org/dc/elements/1.1',
1330  'http://schemas.microsoft.com/visio/2003/svgextensions/',
1331  'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1332  'http://taptrix.com/inkpad/svg_extensions',
1333  'http://web.resource.org/cc/',
1334  'http://www.freesoftware.fsf.org/bkchem/cdml',
1335  'http://www.inkscape.org/namespaces/inkscape',
1336  'http://www.opengis.net/gml',
1337  'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1338  'http://www.w3.org/2000/svg',
1339  'http://www.w3.org/tr/rec-rdf-syntax/',
1340  );
1341 
1342  if ( !in_array( $namespace, $validNamespaces ) ) {
1343  wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" );
1345  $this->mSVGNSError = $namespace;
1346 
1347  return true;
1348  }
1349 
1350  /*
1351  * check for elements that can contain javascript
1352  */
1353  if ( $strippedElement == 'script' ) {
1354  wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1355 
1356  return array( 'uploaded-script-svg', $strippedElement );
1357  }
1358 
1359  # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1360  # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1361  if ( $strippedElement == 'handler' ) {
1362  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1363 
1364  return array( 'uploaded-script-svg', $strippedElement );
1365  }
1366 
1367  # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1368  if ( $strippedElement == 'stylesheet' ) {
1369  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1370 
1371  return array( 'uploaded-script-svg', $strippedElement );
1372  }
1373 
1374  # Block iframes, in case they pass the namespace check
1375  if ( $strippedElement == 'iframe' ) {
1376  wfDebug( __METHOD__ . ": iframe in uploaded file.\n" );
1377 
1378  return array( 'uploaded-script-svg', $strippedElement );
1379  }
1380 
1381  # Check <style> css
1382  if ( $strippedElement == 'style'
1383  && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1384  ) {
1385  wfDebug( __METHOD__ . ": hostile css in style element.\n" );
1386  return array( 'uploaded-hostile-svg' );
1387  }
1388 
1389  foreach ( $attribs as $attrib => $value ) {
1390  $stripped = $this->stripXmlNamespace( $attrib );
1391  $value = strtolower( $value );
1392 
1393  if ( substr( $stripped, 0, 2 ) == 'on' ) {
1394  wfDebug( __METHOD__
1395  . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1396 
1397  return array( 'uploaded-event-handler-on-svg', $attrib, $value );
1398  }
1399 
1400  # href with non-local target (don't allow http://, javascript:, etc)
1401  if ( $stripped == 'href'
1402  && strpos( $value, 'data:' ) !== 0
1403  && strpos( $value, '#' ) !== 0
1404  ) {
1405  if ( !( $strippedElement === 'a'
1406  && preg_match( '!^https?://!im', $value ) )
1407  ) {
1408  wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1409  . "'$attrib'='$value' in uploaded file.\n" );
1410 
1411  return array( 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value );
1412  }
1413  }
1414 
1415  # only allow data: targets that should be safe. This prevents vectors like,
1416  # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1417  if ( $stripped == 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1418  // rfc2397 parameters. This is only slightly slower than (;[\w;]+)*.
1419  // @codingStandardsIgnoreStart Generic.Files.LineLength
1420  $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1421  // @codingStandardsIgnoreEnd
1422 
1423  if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1424  wfDebug( __METHOD__ . ": Found href to unwhitelisted data: uri "
1425  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1426  return array( 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value );
1427  }
1428  }
1429 
1430  # Change href with animate from (http://html5sec.org/#137).
1431  if ( $stripped === 'attributename'
1432  && $strippedElement === 'animate'
1433  && $this->stripXmlNamespace( $value ) == 'href'
1434  ) {
1435  wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1436  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1437 
1438  return array( 'uploaded-animate-svg', $strippedElement, $attrib, $value );
1439  }
1440 
1441  # use set/animate to add event-handler attribute to parent
1442  if ( ( $strippedElement == 'set' || $strippedElement == 'animate' )
1443  && $stripped == 'attributename'
1444  && substr( $value, 0, 2 ) == 'on'
1445  ) {
1446  wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1447  . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1448 
1449  return array( 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value );
1450  }
1451 
1452  # use set to add href attribute to parent element
1453  if ( $strippedElement == 'set'
1454  && $stripped == 'attributename'
1455  && strpos( $value, 'href' ) !== false
1456  ) {
1457  wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" );
1458 
1459  return array( 'uploaded-setting-href-svg' );
1460  }
1461 
1462  # use set to add a remote / data / script target to an element
1463  if ( $strippedElement == 'set'
1464  && $stripped == 'to'
1465  && preg_match( '!(http|https|data|script):!sim', $value )
1466  ) {
1467  wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" );
1468 
1469  return array( 'uploaded-wrong-setting-svg', $value );
1470  }
1471 
1472  # use handler attribute with remote / data / script
1473  if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1474  wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1475  . "'$attrib'='$value' in uploaded file.\n" );
1476 
1477  return array( 'uploaded-setting-handler-svg', $attrib, $value );
1478  }
1479 
1480  # use CSS styles to bring in remote code
1481  if ( $stripped == 'style'
1482  && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1483  ) {
1484  wfDebug( __METHOD__ . ": Found svg setting a style with "
1485  . "remote url '$attrib'='$value' in uploaded file.\n" );
1486  return array( 'uploaded-remote-url-svg', $attrib, $value );
1487  }
1488 
1489  # Several attributes can include css, css character escaping isn't allowed
1490  $cssAttrs = array( 'font', 'clip-path', 'fill', 'filter', 'marker',
1491  'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' );
1492  if ( in_array( $stripped, $cssAttrs )
1493  && self::checkCssFragment( $value )
1494  ) {
1495  wfDebug( __METHOD__ . ": Found svg setting a style with "
1496  . "remote url '$attrib'='$value' in uploaded file.\n" );
1497  return array( 'uploaded-remote-url-svg', $attrib, $value );
1498  }
1499 
1500  # image filters can pull in url, which could be svg that executes scripts
1501  if ( $strippedElement == 'image'
1502  && $stripped == 'filter'
1503  && preg_match( '!url\s*\(!sim', $value )
1504  ) {
1505  wfDebug( __METHOD__ . ": Found image filter with url: "
1506  . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1507 
1508  return array( 'uploaded-image-filter-svg', $strippedElement, $stripped, $value );
1509  }
1510  }
1511 
1512  return false; // No scripts detected
1513  }
1514 
1522  private static function checkCssFragment( $value ) {
1523 
1524  # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1525  if ( stripos( $value, '@import' ) !== false ) {
1526  return true;
1527  }
1528 
1529  # We allow @font-face to embed fonts with data: urls, so we snip the string
1530  # 'url' out so this case won't match when we check for urls below
1531  $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1532  $value = preg_replace( $pattern, '$1$2', $value );
1533 
1534  # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1535  # properties filter and accelerator don't seem to be useful for xss in SVG files.
1536  # Expression and -o-link don't seem to work either, but filtering them here in case.
1537  # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1538  # but not local ones such as url("#..., url('#..., url(#....
1539  if ( preg_match( '!expression
1540  | -o-link\s*:
1541  | -o-link-source\s*:
1542  | -o-replace\s*:!imx', $value ) ) {
1543  return true;
1544  }
1545 
1546  if ( preg_match_all(
1547  "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1548  $value,
1549  $matches
1550  ) !== 0
1551  ) {
1552  # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1553  foreach ( $matches[1] as $match ) {
1554  if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1555  return true;
1556  }
1557  }
1558  }
1559 
1560  if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1561  return true;
1562  }
1563 
1564  return false;
1565  }
1566 
1572  private static function splitXmlNamespace( $element ) {
1573  // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1574  $parts = explode( ':', strtolower( $element ) );
1575  $name = array_pop( $parts );
1576  $ns = implode( ':', $parts );
1577 
1578  return array( $ns, $name );
1579  }
1580 
1585  private function stripXmlNamespace( $name ) {
1586  // 'http://www.w3.org/2000/svg:script' -> 'script'
1587  $parts = explode( ':', strtolower( $name ) );
1588 
1589  return array_pop( $parts );
1590  }
1591 
1602  public static function detectVirus( $file ) {
1604 
1605  if ( !$wgAntivirus ) {
1606  wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1607 
1608  return null;
1609  }
1610 
1611  if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1612  wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1613  $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1614  array( 'virus-badscanner', $wgAntivirus ) );
1615 
1616  return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1617  }
1618 
1619  # look up scanner configuration
1620  $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1621  $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1622  $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1623  $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1624 
1625  if ( strpos( $command, "%f" ) === false ) {
1626  # simple pattern: append file to scan
1627  $command .= " " . wfEscapeShellArg( $file );
1628  } else {
1629  # complex pattern: replace "%f" with file to scan
1630  $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1631  }
1632 
1633  wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1634 
1635  # execute virus scanner
1636  $exitCode = false;
1637 
1638  # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1639  # that does not seem to be worth the pain.
1640  # Ask me (Duesentrieb) about it if it's ever needed.
1641  $output = wfShellExecWithStderr( $command, $exitCode );
1642 
1643  # map exit code to AV_xxx constants.
1644  $mappedCode = $exitCode;
1645  if ( $exitCodeMap ) {
1646  if ( isset( $exitCodeMap[$exitCode] ) ) {
1647  $mappedCode = $exitCodeMap[$exitCode];
1648  } elseif ( isset( $exitCodeMap["*"] ) ) {
1649  $mappedCode = $exitCodeMap["*"];
1650  }
1651  }
1652 
1653  /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1654  * so we need the strict equalities === and thus can't use a switch here
1655  */
1656  if ( $mappedCode === AV_SCAN_FAILED ) {
1657  # scan failed (code was mapped to false by $exitCodeMap)
1658  wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1659 
1660  $output = $wgAntivirusRequired
1661  ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text()
1662  : null;
1663  } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1664  # scan failed because filetype is unknown (probably imune)
1665  wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1666  $output = null;
1667  } elseif ( $mappedCode === AV_NO_VIRUS ) {
1668  # no virus found
1669  wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1670  $output = false;
1671  } else {
1672  $output = trim( $output );
1673 
1674  if ( !$output ) {
1675  $output = true; # if there's no output, return true
1676  } elseif ( $msgPattern ) {
1677  $groups = array();
1678  if ( preg_match( $msgPattern, $output, $groups ) ) {
1679  if ( $groups[1] ) {
1680  $output = $groups[1];
1681  }
1682  }
1683  }
1684 
1685  wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1686  }
1687 
1688  return $output;
1689  }
1690 
1699  private function checkOverwrite( $user ) {
1700  // First check whether the local file can be overwritten
1701  $file = $this->getLocalFile();
1702  $file->load( File::READ_LATEST );
1703  if ( $file->exists() ) {
1704  if ( !self::userCanReUpload( $user, $file ) ) {
1705  return array( 'fileexists-forbidden', $file->getName() );
1706  } else {
1707  return true;
1708  }
1709  }
1710 
1711  /* Check shared conflicts: if the local file does not exist, but
1712  * wfFindFile finds a file, it exists in a shared repository.
1713  */
1714  $file = wfFindFile( $this->getTitle(), array( 'latest' => true ) );
1715  if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1716  return array( 'fileexists-shared-forbidden', $file->getName() );
1717  }
1718 
1719  return true;
1720  }
1721 
1729  public static function userCanReUpload( User $user, File $img ) {
1730  if ( $user->isAllowed( 'reupload' ) ) {
1731  return true; // non-conditional
1732  } elseif ( !$user->isAllowed( 'reupload-own' ) ) {
1733  return false;
1734  }
1735 
1736  if ( !( $img instanceof LocalFile ) ) {
1737  return false;
1738  }
1739 
1740  $img->load();
1741 
1742  return $user->getId() == $img->getUser( 'id' );
1743  }
1744 
1756  public static function getExistsWarning( $file ) {
1757  if ( $file->exists() ) {
1758  return array( 'warning' => 'exists', 'file' => $file );
1759  }
1760 
1761  if ( $file->getTitle()->getArticleID() ) {
1762  return array( 'warning' => 'page-exists', 'file' => $file );
1763  }
1764 
1765  if ( strpos( $file->getName(), '.' ) == false ) {
1766  $partname = $file->getName();
1767  $extension = '';
1768  } else {
1769  $n = strrpos( $file->getName(), '.' );
1770  $extension = substr( $file->getName(), $n + 1 );
1771  $partname = substr( $file->getName(), 0, $n );
1772  }
1773  $normalizedExtension = File::normalizeExtension( $extension );
1774 
1775  if ( $normalizedExtension != $extension ) {
1776  // We're not using the normalized form of the extension.
1777  // Normal form is lowercase, using most common of alternate
1778  // extensions (eg 'jpg' rather than 'JPEG').
1779 
1780  // Check for another file using the normalized form...
1781  $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1782  $file_lc = wfLocalFile( $nt_lc );
1783 
1784  if ( $file_lc->exists() ) {
1785  return array(
1786  'warning' => 'exists-normalized',
1787  'file' => $file,
1788  'normalizedFile' => $file_lc
1789  );
1790  }
1791  }
1792 
1793  // Check for files with the same name but a different extension
1794  $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix(
1795  "{$partname}.", 1 );
1796  if ( count( $similarFiles ) ) {
1797  return array(
1798  'warning' => 'exists-normalized',
1799  'file' => $file,
1800  'normalizedFile' => $similarFiles[0],
1801  );
1802  }
1803 
1804  if ( self::isThumbName( $file->getName() ) ) {
1805  # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1806  $nt_thb = Title::newFromText(
1807  substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
1808  NS_FILE
1809  );
1810  $file_thb = wfLocalFile( $nt_thb );
1811  if ( $file_thb->exists() ) {
1812  return array(
1813  'warning' => 'thumb',
1814  'file' => $file,
1815  'thumbFile' => $file_thb
1816  );
1817  } else {
1818  // File does not exist, but we just don't like the name
1819  return array(
1820  'warning' => 'thumb-name',
1821  'file' => $file,
1822  'thumbFile' => $file_thb
1823  );
1824  }
1825  }
1826 
1827  foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
1828  if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1829  return array(
1830  'warning' => 'bad-prefix',
1831  'file' => $file,
1832  'prefix' => $prefix
1833  );
1834  }
1835  }
1836 
1837  return false;
1838  }
1839 
1845  public static function isThumbName( $filename ) {
1846  $n = strrpos( $filename, '.' );
1847  $partname = $n ? substr( $filename, 0, $n ) : $filename;
1848 
1849  return (
1850  substr( $partname, 3, 3 ) == 'px-' ||
1851  substr( $partname, 2, 3 ) == 'px-'
1852  ) &&
1853  preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1854  }
1855 
1861  public static function getFilenamePrefixBlacklist() {
1862  $blacklist = array();
1863  $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1864  if ( !$message->isDisabled() ) {
1865  $lines = explode( "\n", $message->plain() );
1866  foreach ( $lines as $line ) {
1867  // Remove comment lines
1868  $comment = substr( trim( $line ), 0, 1 );
1869  if ( $comment == '#' || $comment == '' ) {
1870  continue;
1871  }
1872  // Remove additional comments after a prefix
1873  $comment = strpos( $line, '#' );
1874  if ( $comment > 0 ) {
1875  $line = substr( $line, 0, $comment - 1 );
1876  }
1877  $blacklist[] = trim( $line );
1878  }
1879  }
1880 
1881  return $blacklist;
1882  }
1883 
1895  public function getImageInfo( $result ) {
1896  $file = $this->getLocalFile();
1902  if ( $file instanceof UploadStashFile ) {
1904  $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1905  } else {
1907  $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1908  }
1909 
1910  return $info;
1911  }
1912 
1917  public function convertVerifyErrorToStatus( $error ) {
1918  $code = $error['status'];
1919  unset( $code['status'] );
1920 
1921  return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1922  }
1923 
1931  public static function getMaxUploadSize( $forType = null ) {
1933 
1934  if ( is_array( $wgMaxUploadSize ) ) {
1935  if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1936  return $wgMaxUploadSize[$forType];
1937  } else {
1938  return $wgMaxUploadSize['*'];
1939  }
1940  } else {
1941  return intval( $wgMaxUploadSize );
1942  }
1943  }
1944 
1952  public static function getMaxPhpUploadSize() {
1953  $phpMaxFileSize = wfShorthandToInteger(
1954  ini_get( 'upload_max_filesize' ) ?: ini_get( 'hhvm.server.upload.upload_max_file_size' ),
1955  PHP_INT_MAX
1956  );
1957  $phpMaxPostSize = wfShorthandToInteger(
1958  ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
1959  PHP_INT_MAX
1960  ) ?: PHP_INT_MAX;
1961  return min( $phpMaxFileSize, $phpMaxPostSize );
1962  }
1963 
1973  public static function getSessionStatus( User $user, $statusKey ) {
1974  $key = wfMemcKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
1975 
1976  return ObjectCache::getMainStashInstance()->get( $key );
1977  }
1978 
1989  public static function setSessionStatus( User $user, $statusKey, $value ) {
1990  $key = wfMemcKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
1991 
1993  if ( $value === false ) {
1994  $cache->delete( $key );
1995  } else {
1996  $cache->set( $key, $value, $cache::TTL_DAY );
1997  }
1998  }
1999 }
$wgStrictFileExtensions
If this is turned off, users may override the warning for files not covered by $wgFileExtensions.
checkSvgScriptCallback($element, $attribs, $data=null)
static checkFileExtensionList($ext, $list)
Perform case-insensitive match against a list of file extensions.
#define the
table suitable for use with IDatabase::select()
getImageInfo($result)
Gets image info about the file just uploaded.
getVerificationErrorCode($error)
Definition: UploadBase.php:73
you don t have to do a grep find to see where the $wgReverseTitle variable is used
Definition: hooks.txt:117
null means default in associative array form
Definition: hooks.txt:1769
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
const FILENAME_TOO_LONG
Definition: UploadBase.php:67
the array() calling protocol came about after MediaWiki 1.4rc1.
$wgSVGMetadataCutoff
Don't read SVG metadata beyond this point.
$wgDisableUploadScriptChecks
Setting this to true will disable the upload system's checks for HTML/JavaScript. ...
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2303
wfIsHHVM()
Check if we are running under HHVM.
const SUCCESS
Definition: UploadBase.php:55
static createFromRequest(&$request, $type=null)
Create a form of UploadBase depending on wpSourceType and initializes it.
Definition: UploadBase.php:148
static isAllowed($user)
Returns true if the user can use this upload module or else a string identifying the missing permissi...
Definition: UploadBase.php:118
wfShorthandToInteger($string= '', $default=-1)
Converts shorthand byte notation to integer form.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:311
static singleton()
Get an instance of this class.
Definition: MimeMagic.php:366
$command
Definition: cdb.php:65
namespace and then decline to actually register it file or subcat img or subcat RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:975
static checkFileExtension($ext, $list)
Perform case-insensitive match against a list of file extensions.
Definition: UploadBase.php:989
globals txt Globals are evil The original MediaWiki code relied on globals for processing context far too often MediaWiki development since then has been a story of slowly moving context out of global variables and into objects Storing processing context in object member variables allows those objects to be reused in a much more flexible way Consider the elegance of
database rows
Definition: globals.txt:10
const DELETE_SOURCE
Definition: File.php:65
static getSessionStatus(User $user, $statusKey)
Get the current status of a chunked upload (used for polling)
const OVERWRITE_EXISTING_FILE
Definition: UploadBase.php:60
static $safeXmlEncodings
Definition: UploadBase.php:47
static isValidRequest($request)
Check whether a request if valid for this handler.
Definition: UploadBase.php:192
performUpload($comment, $pageText, $watch, $user, $tags=array())
Really perform the upload.
Definition: UploadBase.php:700
$comment
wfDebug($text, $dest= 'all', array $context=array())
Sends a line to the debug log if enabled or, optionally, to a comment in output.
null for the local wiki Added in
Definition: hooks.txt:1389
has been added to your &Future changes to this page and its associated Talk page will be listed there
$value
const AV_NO_VIRUS
Definition: Defines.php:138
verifyPermissions($user)
Alias for verifyTitlePermissions.
Definition: UploadBase.php:556
if($ext== 'php'||$ext== 'php5') $mime
Definition: router.php:65
stripXmlNamespace($name)
static splitXmlNamespace($element)
Divide the element name passed by the xml parser to the callback into URI and prifix.
static getMainStashInstance()
Get the cache object for the main stash.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:269
const ILLEGAL_FILENAME
Definition: UploadBase.php:59
isEmptyFile()
Return true if the file is empty.
Definition: UploadBase.php:246
const AV_SCAN_FAILED
Definition: Defines.php:141
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
wfLocalFile($title)
Get an object referring to a locally registered file.
$wgAllowJavaUploads
Allow Java archive uploads.
wfStripIllegalFilenameChars($name)
Replace all invalid characters with - Additional characters can be defined in $wgIllegalFileChars (se...
static checkSvgPICallback($target, $data)
Callback to filter SVG Processing Instructions.
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2037
verifyMimeType($mime)
Verify the MIME type.
Definition: UploadBase.php:379
wfArrayDiff2($a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
const AV_SCAN_ABORTED
Definition: Defines.php:140
static getMaxUploadSize($forType=null)
Get the MediaWiki maximum uploaded file size for given type of upload, based on $wgMaxUploadSize.
const DELETED_FILE
Definition: File.php:52
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition: design.txt:56
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1767
verifyPartialFile()
A verification routine suitable for partial files.
Definition: UploadBase.php:467
$wgCheckFileExtensions
This is a flag to determine whether or not to check file extensions on upload.
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:42
static decodeCharReferences($text)
Decode any character references, numeric or named entities, in the text and return a UTF-8 string...
Definition: Sanitizer.php:1463
$wgEnableUploads
Uploads have to be specially set up to be secure.
static isThumbName($filename)
Helper function that checks whether the filename looks like a thumbnail.
static isThrottled($user)
Returns true if the user has surpassed the upload rate limit, false otherwise.
Definition: UploadBase.php:134
Class representing a row of the 'filearchive' table.
static read($fileName, $callback, $options=array())
Read a ZIP file and call a function for each file discovered in it.
const IGNORE_USER_RIGHTS
Constant to specify that user rights 'editmywatchlist' and 'viewmywatchlist' should not be checked...
Definition: WatchedItem.php:53
zipEntryCallback($entry)
Callback for ZipDirectoryReader to detect Java class files.
Definition: UploadBase.php:527
namespace and then decline to actually register it file or subcat img or subcat RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition: hooks.txt:889
$wgAntivirusRequired
Determines if a failed virus scan (AV_SCAN_FAILED) will cause the file to be rejected.
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
Definition: hooks.txt:93
getTempFileSha1Base36()
Get the base 36 SHA1 of the file.
Definition: UploadBase.php:262
stashFileGetKey()
Stash a file in a temporary directory, returning a key which can be used to find the file again...
Definition: UploadBase.php:937
UploadBase and subclasses are the backend of MediaWiki's file uploads.
Definition: UploadBase.php:38
wfIniGetBool($setting)
Safety wrapper around ini_get() for boolean settings.
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
fetchFile()
Fetch the file.
Definition: UploadBase.php:238
static isStoragePath($path)
Check if a given path is a "mwstore://" path.
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
wfShellExecWithStderr($cmd, &$retval=null, $environ=array(), $limits=array())
Execute a shell command, returning both stdout and stderr.
MediaWiki exception.
Definition: MWException.php:26
static run($event, array $args=array(), $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
stashSession()
alias for stashFileGetKey, for backwards compatibility
Definition: UploadBase.php:946
postProcessUpload()
Perform extra steps after a successful upload.
Definition: UploadBase.php:735
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
$cache
Definition: mcc.php:32
getTitle()
Returns the title of the file to be uploaded.
Definition: UploadBase.php:765
static getPropertyNames($filter=array())
Returns all possible parameters to iiprop.
static detectVirus($file)
Generic wrapper function for a virus scanner program.
static splitExtensions($filename)
Split a file into a base name and all dot-delimited 'extensions' on the end.
Definition: UploadBase.php:974
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:540
cleanupTempFile()
If we've modified the upload file we need to manually remove it on exit to clean up.
Definition: UploadBase.php:954
getSourceType()
Returns the upload type.
Definition: UploadBase.php:205
const FILE_TOO_LARGE
Definition: UploadBase.php:65
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead.&$feedLinks conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:313
checkWarnings()
Check for non fatal problems with the file.
Definition: UploadBase.php:609
initializeFromRequest(&$request)
Initialize from a WebRequest.
verifyUpload()
Verify whether the upload is sane.
Definition: UploadBase.php:292
const MIN_LENGTH_PARTNAME
Definition: UploadBase.php:58
getFileSize()
Return the file size.
Definition: UploadBase.php:254
const NS_FILE
Definition: Defines.php:75
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this submitted means any form of or written communication sent to the Licensor or its including but not limited to communication on electronic mailing source code control and issue tracking systems that are managed by
static getSha1Base36FromPath($path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding, zero padded to 31 digits.
Definition: FSFile.php:253
const VERIFICATION_ERROR
Definition: UploadBase.php:63
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static isEnabled()
Returns true if uploads are enabled.
Definition: UploadBase.php:99
equals(Content $that=null)
Returns true if this Content objects is conceptually equivalent to the given Content object...
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:240
validateName()
Verify that the name is valid and, if necessary, that we can overwrite.
Definition: UploadBase.php:349
const FILETYPE_BADTYPE
Definition: UploadBase.php:62
$wgMaxUploadSize
Max size for uploads, in bytes.
wfDebugLog($logGroup, $text, $dest= 'all', array $context=array())
Send a line to a supplementary debug log file, if configured, or main debug log if not...
getLocalFile()
Return the local file and initializes if necessary.
Definition: UploadBase.php:897
static singleton($wiki=false)
$wgAntivirusSetup
Configuration for different virus scanners.
const FILETYPE_MISSING
Definition: UploadBase.php:61
namespace and then decline to actually register it file or subcat img or subcat RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:975
static normalizeCss($value)
Normalize CSS into a format we can easily search for hostile input.
Definition: Sanitizer.php:863
$wgFileExtensions
This is the list of preferred extensions for uploading files.
static getFilenamePrefixBlacklist()
Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]].
$wgUploadSizeWarning
Warn if uploaded files are larger than this (in bytes), or false to disable.
verifyTitlePermissions($user)
Check whether the user can edit, upload and create the image.
Definition: UploadBase.php:571
$lines
Definition: router.php:66
const HOOK_ABORTED
Definition: UploadBase.php:64
stashFile(User $user=null)
If the user does not supply all necessary information in the first upload form submission (either by ...
Definition: UploadBase.php:921
getId()
Get the user's ID.
Definition: User.php:2013
static verifyExtension($mime, $extension)
Checks if the MIME type of the uploaded file matches the file extension.
detectScriptInSvg($filename, $partial)
Job for asynchronous rendering of thumbnails.
static detectScript($file, $mime, $extension)
Heuristic for detecting files that could contain JavaScript instructions or things that may look like...
static doWatch(Title $title, User $user, $checkRights=WatchedItem::CHECK_USER_RIGHTS)
Watch a page.
convertVerifyErrorToStatus($error)
$line
Definition: cdb.php:59
static $uploadHandlers
Definition: UploadBase.php:139
when a variable name is used in a function
Definition: design.txt:93
const WINDOWS_NONASCII_FILENAME
Definition: UploadBase.php:66
static getHandler($type)
Get a MediaHandler for a given MIME type from the instance cache.
$wgAllowTitlesInSVG
Disallow <title> element in SVG files.
static checkXMLEncodingMissmatch($file)
Check a whitelist of xml encodings that are known not to be interpreted differently by the server's x...
wfEscapeShellArg()
Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell...
static checkCssFragment($value)
Check a block of CSS or CSS fragment for anything that looks like it is bringing in remote code...
static getMaxPhpUploadSize()
Get the PHP maximum uploaded file size, based on ini settings.
wfMemcKey()
Make a cache key for the local wiki.
$wgOut
Definition: Setup.php:759
static setSessionStatus(User $user, $statusKey, $value)
Set the current status of a chunked upload (used for polling)
$extensions
$mBlackListedExtensions
Definition: UploadBase.php:44
maintenance dev scripts can help quickly setup a local MediaWiki for development purposes Wikis setup in this way are NOT meant to be publicly available They use a development database not acceptible for use in production Place a sqlite database in an unsafe location a real wiki should never place it in And use predictable default logins for the initial administrator user Running maintenance dev install sh will download and install a local copy of php
Definition: README:5
$wgMimeTypeBlacklist
Files with these MIME types will never be allowed as uploads if $wgVerifyMimeType is enabled...
verifyFile()
Verifies that it's ok to include the uploaded file.
Definition: UploadBase.php:411
const OK
Definition: UploadBase.php:56
$wgVerifyMimeType
Determines if the MIME type of uploaded files should be checked.
$wgFileBlacklist
Files with these extensions will never be allowed as uploads.
static getPropsFromPath($path, $ext=true)
Get an associative array containing information about a file in the local filesystem.
Definition: FSFile.php:237
static getInfo($file, $prop, $result, $thumbParams=null, $opts=false)
Get result information for an image revision.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk page
Definition: hooks.txt:2320
const EMPTY_FILE
Definition: UploadBase.php:57
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2320
static capitalize($text, $ns=NS_MAIN)
Capitalize a text string for a title if it belongs to a namespace that capitalizes.
Definition: Title.php:3323
static & makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:516
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition: hooks.txt:1769
getRealPath($srcPath)
Definition: UploadBase.php:270
initializePathInfo($name, $tempPath, $fileSize, $removeTempFile=false)
Initialize the path information.
Definition: UploadBase.php:217
checkOverwrite($user)
Check if there's an overwrite conflict and, if so, if restrictions forbid this user from performing t...
$wgAntivirus
Internal name of virus scanner.
$matches