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 
65  # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
67  const HOOK_ABORTED = 11;
68  const FILE_TOO_LARGE = 12;
70  const FILENAME_TOO_LONG = 14;
71 
76  public function getVerificationErrorCode( $error ) {
77  $code_to_status = array(
78  self::EMPTY_FILE => 'empty-file',
79  self::FILE_TOO_LARGE => 'file-too-large',
80  self::FILETYPE_MISSING => 'filetype-missing',
81  self::FILETYPE_BADTYPE => 'filetype-banned',
82  self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
83  self::ILLEGAL_FILENAME => 'illegal-filename',
84  self::OVERWRITE_EXISTING_FILE => 'overwrite',
85  self::VERIFICATION_ERROR => 'verification-error',
86  self::HOOK_ABORTED => 'hookaborted',
87  self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
88  self::FILENAME_TOO_LONG => 'filename-toolong',
89  );
90  if ( isset( $code_to_status[$error] ) ) {
91  return $code_to_status[$error];
92  }
93 
94  return 'unknown-error';
95  }
96 
102  public static function isEnabled() {
104 
105  if ( !$wgEnableUploads ) {
106  return false;
107  }
108 
109  # Check php's file_uploads setting
110  return wfIsHHVM() || wfIniGetBool( 'file_uploads' );
111  }
112 
121  public static function isAllowed( $user ) {
122  foreach ( array( 'upload', 'edit' ) as $permission ) {
123  if ( !$user->isAllowed( $permission ) ) {
124  return $permission;
125  }
126  }
127 
128  return true;
129  }
130 
131  // Upload handlers. Should probably just be a global.
132  private static $uploadHandlers = array( 'Stash', 'File', 'Url' );
133 
141  public static function createFromRequest( &$request, $type = null ) {
142  $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
143 
144  if ( !$type ) {
145  return null;
146  }
147 
148  // Get the upload class
149  $type = ucfirst( $type );
150 
151  // Give hooks the chance to handle this request
152  $className = null;
153  Hooks::run( 'UploadCreateFromRequest', array( $type, &$className ) );
154  if ( is_null( $className ) ) {
155  $className = 'UploadFrom' . $type;
156  wfDebug( __METHOD__ . ": class name: $className\n" );
157  if ( !in_array( $type, self::$uploadHandlers ) ) {
158  return null;
159  }
160  }
161 
162  // Check whether this upload class is enabled
163  if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
164  return null;
165  }
166 
167  // Check whether the request is valid
168  if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
169  return null;
170  }
171 
173  $handler = new $className;
174 
175  $handler->initializeFromRequest( $request );
176 
177  return $handler;
178  }
179 
185  public static function isValidRequest( $request ) {
186  return false;
187  }
188 
189  public function __construct() {
190  }
191 
198  public function getSourceType() {
199  return null;
200  }
201 
210  public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
211  $this->mDesiredDestName = $name;
212  if ( FileBackend::isStoragePath( $tempPath ) ) {
213  throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
214  }
215  $this->mTempPath = $tempPath;
216  $this->mFileSize = $fileSize;
217  $this->mRemoveTempFile = $removeTempFile;
218  }
219 
225  abstract public function initializeFromRequest( &$request );
226 
231  public function fetchFile() {
232  return Status::newGood();
233  }
234 
239  public function isEmptyFile() {
240  return empty( $this->mFileSize );
241  }
242 
247  public function getFileSize() {
248  return $this->mFileSize;
249  }
250 
255  public function getTempFileSha1Base36() {
256  return FSFile::getSha1Base36FromPath( $this->mTempPath );
257  }
258 
263  function getRealPath( $srcPath ) {
264  $repo = RepoGroup::singleton()->getLocalRepo();
265  if ( $repo->isVirtualUrl( $srcPath ) ) {
269  $tmpFile = $repo->getLocalCopy( $srcPath );
270  if ( $tmpFile ) {
271  $tmpFile->bind( $this ); // keep alive with $this
272  }
273  $path = $tmpFile ? $tmpFile->getPath() : false;
274  } else {
275  $path = $srcPath;
276  }
277 
278  return $path;
279  }
280 
285  public function verifyUpload() {
286 
290  if ( $this->isEmptyFile() ) {
291  return array( 'status' => self::EMPTY_FILE );
292  }
293 
297  $maxSize = self::getMaxUploadSize( $this->getSourceType() );
298  if ( $this->mFileSize > $maxSize ) {
299  return array(
300  'status' => self::FILE_TOO_LARGE,
301  'max' => $maxSize,
302  );
303  }
304 
310  $verification = $this->verifyFile();
311  if ( $verification !== true ) {
312  return array(
313  'status' => self::VERIFICATION_ERROR,
314  'details' => $verification
315  );
316  }
317 
321  $result = $this->validateName();
322  if ( $result !== true ) {
323  return $result;
324  }
325 
326  $error = '';
327  if ( !Hooks::run( 'UploadVerification',
328  array( $this->mDestName, $this->mTempPath, &$error ) )
329  ) {
330  return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
331  }
332 
333  return array( 'status' => self::OK );
334  }
335 
342  public function validateName() {
343  $nt = $this->getTitle();
344  if ( is_null( $nt ) ) {
345  $result = array( 'status' => $this->mTitleError );
346  if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
347  $result['filtered'] = $this->mFilteredName;
348  }
349  if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
350  $result['finalExt'] = $this->mFinalExtension;
351  if ( count( $this->mBlackListedExtensions ) ) {
352  $result['blacklistedExt'] = $this->mBlackListedExtensions;
353  }
354  }
355 
356  return $result;
357  }
358  $this->mDestName = $this->getLocalFile()->getName();
359 
360  return true;
361  }
362 
372  protected function verifyMimeType( $mime ) {
374  if ( $wgVerifyMimeType ) {
375  wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
377  if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
378  return array( 'filetype-badmime', $mime );
379  }
380 
381  # Check what Internet Explorer would detect
382  $fp = fopen( $this->mTempPath, 'rb' );
383  $chunk = fread( $fp, 256 );
384  fclose( $fp );
385 
386  $magic = MimeMagic::singleton();
387  $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
388  $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
389  foreach ( $ieTypes as $ieType ) {
390  if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
391  return array( 'filetype-bad-ie-mime', $ieType );
392  }
393  }
394  }
395 
396  return true;
397  }
398 
404  protected function verifyFile() {
406 
407  $status = $this->verifyPartialFile();
408  if ( $status !== true ) {
409  return $status;
410  }
411 
412  $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
413  $mime = $this->mFileProps['mime'];
414 
415  if ( $wgVerifyMimeType ) {
416  # XXX: Missing extension will be caught by validateName() via getTitle()
417  if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
418  return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
419  }
420  }
421 
422  # check for htmlish code and javascript
423  if ( !$wgDisableUploadScriptChecks ) {
424  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
425  $svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
426  if ( $svgStatus !== false ) {
427  return $svgStatus;
428  }
429  }
430  }
431 
432  $handler = MediaHandler::getHandler( $mime );
433  if ( $handler ) {
434  $handlerStatus = $handler->verifyUpload( $this->mTempPath );
435  if ( !$handlerStatus->isOK() ) {
436  $errors = $handlerStatus->getErrorsArray();
437 
438  return reset( $errors );
439  }
440  }
441 
442  Hooks::run( 'UploadVerifyFile', array( $this, $mime, &$status ) );
443  if ( $status !== true ) {
444  return $status;
445  }
446 
447  wfDebug( __METHOD__ . ": all clear; passing.\n" );
448 
449  return true;
450  }
451 
460  protected function verifyPartialFile() {
462 
463  # getTitle() sets some internal parameters like $this->mFinalExtension
464  $this->getTitle();
465 
466  $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
467 
468  # check MIME type, if desired
469  $mime = $this->mFileProps['file-mime'];
470  $status = $this->verifyMimeType( $mime );
471  if ( $status !== true ) {
472  return $status;
473  }
474 
475  # check for htmlish code and javascript
476  if ( !$wgDisableUploadScriptChecks ) {
477  if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
478  return array( 'uploadscripted' );
479  }
480  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
481  $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
482  if ( $svgStatus !== false ) {
483  return $svgStatus;
484  }
485  }
486  }
487 
488  # Check for Java applets, which if uploaded can bypass cross-site
489  # restrictions.
490  if ( !$wgAllowJavaUploads ) {
491  $this->mJavaDetected = false;
492  $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
493  array( $this, 'zipEntryCallback' ) );
494  if ( !$zipStatus->isOK() ) {
495  $errors = $zipStatus->getErrorsArray();
496  $error = reset( $errors );
497  if ( $error[0] !== 'zip-wrong-format' ) {
498  return $error;
499  }
500  }
501  if ( $this->mJavaDetected ) {
502  return array( 'uploadjava' );
503  }
504  }
505 
506  # Scan the uploaded file for viruses
507  $virus = $this->detectVirus( $this->mTempPath );
508  if ( $virus ) {
509  return array( 'uploadvirus', $virus );
510  }
511 
512  return true;
513  }
514 
520  function zipEntryCallback( $entry ) {
521  $names = array( $entry['name'] );
522 
523  // If there is a null character, cut off the name at it, because JDK's
524  // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
525  // were constructed which had ".class\0" followed by a string chosen to
526  // make the hash collide with the truncated name, that file could be
527  // returned in response to a request for the .class file.
528  $nullPos = strpos( $entry['name'], "\000" );
529  if ( $nullPos !== false ) {
530  $names[] = substr( $entry['name'], 0, $nullPos );
531  }
532 
533  // If there is a trailing slash in the file name, we have to strip it,
534  // because that's what ZIP_GetEntry() does.
535  if ( preg_grep( '!\.class/?$!', $names ) ) {
536  $this->mJavaDetected = true;
537  }
538  }
539 
549  public function verifyPermissions( $user ) {
550  return $this->verifyTitlePermissions( $user );
551  }
552 
564  public function verifyTitlePermissions( $user ) {
569  $nt = $this->getTitle();
570  if ( is_null( $nt ) ) {
571  return true;
572  }
573  $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
574  $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
575  if ( !$nt->exists() ) {
576  $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
577  } else {
578  $permErrorsCreate = array();
579  }
580  if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
581  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
582  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
583 
584  return $permErrors;
585  }
586 
587  $overwriteError = $this->checkOverwrite( $user );
588  if ( $overwriteError !== true ) {
589  return array( $overwriteError );
590  }
591 
592  return true;
593  }
594 
602  public function checkWarnings() {
603  global $wgLang;
604 
605  $warnings = array();
606 
607  $localFile = $this->getLocalFile();
608  $localFile->load( File::READ_LATEST );
609  $filename = $localFile->getName();
610 
615  $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
616  $comparableName = Title::capitalize( $comparableName, NS_FILE );
617 
618  if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
619  $warnings['badfilename'] = $filename;
620  // Debugging for bug 62241
621  wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: "
622  . "'$this->mDesiredDestName', comparableName: '$comparableName'" );
623  }
624 
625  // Check whether the file extension is on the unwanted list
627  if ( $wgCheckFileExtensions ) {
628  $extensions = array_unique( $wgFileExtensions );
629  if ( !$this->checkFileExtension( $this->mFinalExtension, $extensions ) ) {
630  $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension,
631  $wgLang->commaList( $extensions ), count( $extensions ) );
632  }
633  }
634 
636  if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
637  $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize );
638  }
639 
640  if ( $this->mFileSize == 0 ) {
641  $warnings['emptyfile'] = true;
642  }
643 
644  $exists = self::getExistsWarning( $localFile );
645  if ( $exists !== false ) {
646  $warnings['exists'] = $exists;
647  }
648 
649  // Check dupes against existing files
650  $hash = $this->getTempFileSha1Base36();
651  $dupes = RepoGroup::singleton()->findBySha1( $hash );
652  $title = $this->getTitle();
653  // Remove all matches against self
654  foreach ( $dupes as $key => $dupe ) {
655  if ( $title->equals( $dupe->getTitle() ) ) {
656  unset( $dupes[$key] );
657  }
658  }
659  if ( $dupes ) {
660  $warnings['duplicate'] = $dupes;
661  }
662 
663  // Check dupes against archives
664  $archivedFile = new ArchivedFile( null, 0, '', $hash );
665  if ( $archivedFile->getID() > 0 ) {
666  if ( $archivedFile->userCan( File::DELETED_FILE ) ) {
667  $warnings['duplicate-archive'] = $archivedFile->getName();
668  } else {
669  $warnings['duplicate-archive'] = '';
670  }
671  }
672 
673  return $warnings;
674  }
675 
687  public function performUpload( $comment, $pageText, $watch, $user ) {
688  $this->getLocalFile()->load( File::READ_LATEST );
689 
690  $status = $this->getLocalFile()->upload(
691  $this->mTempPath,
692  $comment,
693  $pageText,
695  $this->mFileProps,
696  false,
697  $user
698  );
699 
700  if ( $status->isGood() ) {
701  if ( $watch ) {
703  $this->getLocalFile()->getTitle(),
704  $user,
706  );
707  }
708  Hooks::run( 'UploadComplete', array( &$this ) );
709 
710  $this->postProcessUpload();
711  }
712 
713  return $status;
714  }
715 
721  public function postProcessUpload() {
723 
724  $jobs = array();
725 
727  rsort( $sizes );
728 
729  $file = $this->getLocalFile();
730 
731  foreach ( $sizes as $size ) {
732  if ( $file->isVectorized() || $file->getWidth() > $size ) {
733  $jobs[] = new ThumbnailRenderJob(
734  $file->getTitle(),
735  array( 'transformParams' => array( 'width' => $size ) )
736  );
737  }
738  }
739 
740  if ( $jobs ) {
741  JobQueueGroup::singleton()->push( $jobs );
742  }
743  }
744 
751  public function getTitle() {
752  if ( $this->mTitle !== false ) {
753  return $this->mTitle;
754  }
755  /* Assume that if a user specified File:Something.jpg, this is an error
756  * and that the namespace prefix needs to be stripped of.
757  */
758  $title = Title::newFromText( $this->mDesiredDestName );
759  if ( $title && $title->getNamespace() == NS_FILE ) {
760  $this->mFilteredName = $title->getDBkey();
761  } else {
762  $this->mFilteredName = $this->mDesiredDestName;
763  }
764 
765  # oi_archive_name is max 255 bytes, which include a timestamp and an
766  # exclamation mark, so restrict file name to 240 bytes.
767  if ( strlen( $this->mFilteredName ) > 240 ) {
768  $this->mTitleError = self::FILENAME_TOO_LONG;
769  $this->mTitle = null;
770 
771  return $this->mTitle;
772  }
773 
779  $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
780  /* Normalize to title form before we do any further processing */
781  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
782  if ( is_null( $nt ) ) {
783  $this->mTitleError = self::ILLEGAL_FILENAME;
784  $this->mTitle = null;
785 
786  return $this->mTitle;
787  }
788  $this->mFilteredName = $nt->getDBkey();
789 
794  list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
795 
796  if ( count( $ext ) ) {
797  $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
798  } else {
799  $this->mFinalExtension = '';
800 
801  # No extension, try guessing one
802  $magic = MimeMagic::singleton();
803  $mime = $magic->guessMimeType( $this->mTempPath );
804  if ( $mime !== 'unknown/unknown' ) {
805  # Get a space separated list of extensions
806  $extList = $magic->getExtensionsForType( $mime );
807  if ( $extList ) {
808  # Set the extension to the canonical extension
809  $this->mFinalExtension = strtok( $extList, ' ' );
810 
811  # Fix up the other variables
812  $this->mFilteredName .= ".{$this->mFinalExtension}";
813  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
814  $ext = array( $this->mFinalExtension );
815  }
816  }
817  }
818 
819  /* Don't allow users to override the blacklist (check file extension) */
822 
823  $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
824 
825  if ( $this->mFinalExtension == '' ) {
826  $this->mTitleError = self::FILETYPE_MISSING;
827  $this->mTitle = null;
828 
829  return $this->mTitle;
830  } elseif ( $blackListedExtensions ||
831  ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
832  !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
833  ) {
834  $this->mBlackListedExtensions = $blackListedExtensions;
835  $this->mTitleError = self::FILETYPE_BADTYPE;
836  $this->mTitle = null;
837 
838  return $this->mTitle;
839  }
840 
841  // Windows may be broken with special characters, see bug 1780
842  if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
843  && !RepoGroup::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
844  ) {
845  $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
846  $this->mTitle = null;
847 
848  return $this->mTitle;
849  }
850 
851  # If there was more than one "extension", reassemble the base
852  # filename to prevent bogus complaints about length
853  if ( count( $ext ) > 1 ) {
854  $iterations = count( $ext ) - 1;
855  for ( $i = 0; $i < $iterations; $i++ ) {
856  $partname .= '.' . $ext[$i];
857  }
858  }
859 
860  if ( strlen( $partname ) < 1 ) {
861  $this->mTitleError = self::MIN_LENGTH_PARTNAME;
862  $this->mTitle = null;
863 
864  return $this->mTitle;
865  }
866 
867  $this->mTitle = $nt;
868 
869  return $this->mTitle;
870  }
871 
877  public function getLocalFile() {
878  if ( is_null( $this->mLocalFile ) ) {
879  $nt = $this->getTitle();
880  $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
881  }
882 
883  return $this->mLocalFile;
884  }
885 
901  public function stashFile( User $user = null ) {
902  // was stashSessionFile
903 
904  $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user );
905  $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
906  $this->mLocalFile = $file;
907 
908  return $file;
909  }
910 
917  public function stashFileGetKey() {
918  return $this->stashFile()->getFileKey();
919  }
920 
926  public function stashSession() {
927  return $this->stashFileGetKey();
928  }
929 
934  public function cleanupTempFile() {
935  if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
936  wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
937  unlink( $this->mTempPath );
938  }
939  }
940 
941  public function getTempPath() {
942  return $this->mTempPath;
943  }
944 
954  public static function splitExtensions( $filename ) {
955  $bits = explode( '.', $filename );
956  $basename = array_shift( $bits );
957 
958  return array( $basename, $bits );
959  }
960 
969  public static function checkFileExtension( $ext, $list ) {
970  return in_array( strtolower( $ext ), $list );
971  }
972 
981  public static function checkFileExtensionList( $ext, $list ) {
982  return array_intersect( array_map( 'strtolower', $ext ), $list );
983  }
984 
992  public static function verifyExtension( $mime, $extension ) {
993  $magic = MimeMagic::singleton();
994 
995  if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) {
996  if ( !$magic->isRecognizableExtension( $extension ) ) {
997  wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
998  "unrecognized extension '$extension', can't verify\n" );
999 
1000  return true;
1001  } else {
1002  wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1003  "recognized extension '$extension', so probably invalid file\n" );
1004 
1005  return false;
1006  }
1007  }
1008 
1009  $match = $magic->isMatchingExtension( $extension, $mime );
1010 
1011  if ( $match === null ) {
1012  if ( $magic->getTypesForExtension( $extension ) !== null ) {
1013  wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension\n" );
1014 
1015  return false;
1016  } else {
1017  wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
1018 
1019  return true;
1020  }
1021  } elseif ( $match === true ) {
1022  wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
1023 
1025  return true;
1026  } else {
1027  wfDebug( __METHOD__
1028  . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
1029 
1030  return false;
1031  }
1032  }
1033 
1045  public static function detectScript( $file, $mime, $extension ) {
1047 
1048  # ugly hack: for text files, always look at the entire file.
1049  # For binary field, just check the first K.
1050 
1051  if ( strpos( $mime, 'text/' ) === 0 ) {
1052  $chunk = file_get_contents( $file );
1053  } else {
1054  $fp = fopen( $file, 'rb' );
1055  $chunk = fread( $fp, 1024 );
1056  fclose( $fp );
1057  }
1058 
1059  $chunk = strtolower( $chunk );
1060 
1061  if ( !$chunk ) {
1062  return false;
1063  }
1064 
1065  # decode from UTF-16 if needed (could be used for obfuscation).
1066  if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1067  $enc = 'UTF-16BE';
1068  } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1069  $enc = 'UTF-16LE';
1070  } else {
1071  $enc = null;
1072  }
1073 
1074  if ( $enc ) {
1075  $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1076  }
1077 
1078  $chunk = trim( $chunk );
1079 
1081  wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
1082 
1083  # check for HTML doctype
1084  if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1085  return true;
1086  }
1087 
1088  // Some browsers will interpret obscure xml encodings as UTF-8, while
1089  // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1090  if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
1091  if ( self::checkXMLEncodingMissmatch( $file ) ) {
1092  return true;
1093  }
1094  }
1095 
1111  $tags = array(
1112  '<a href',
1113  '<body',
1114  '<head',
1115  '<html', #also in safari
1116  '<img',
1117  '<pre',
1118  '<script', #also in safari
1119  '<table'
1120  );
1121 
1122  if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1123  $tags[] = '<title';
1124  }
1125 
1126  foreach ( $tags as $tag ) {
1127  if ( false !== strpos( $chunk, $tag ) ) {
1128  wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
1129 
1130  return true;
1131  }
1132  }
1133 
1134  /*
1135  * look for JavaScript
1136  */
1137 
1138  # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1139  $chunk = Sanitizer::decodeCharReferences( $chunk );
1140 
1141  # look for script-types
1142  if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1143  wfDebug( __METHOD__ . ": found script types\n" );
1144 
1145  return true;
1146  }
1147 
1148  # look for html-style script-urls
1149  if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1150  wfDebug( __METHOD__ . ": found html-style script urls\n" );
1151 
1152  return true;
1153  }
1154 
1155  # look for css-style script-urls
1156  if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1157  wfDebug( __METHOD__ . ": found css-style script urls\n" );
1158 
1159  return true;
1160  }
1161 
1162  wfDebug( __METHOD__ . ": no scripts found\n" );
1163 
1164  return false;
1165  }
1166 
1174  public static function checkXMLEncodingMissmatch( $file ) {
1176  $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1177  $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1178 
1179  if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1180  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1181  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1182  ) {
1183  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1184 
1185  return true;
1186  }
1187  } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1188  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1189  // bytes. There shouldn't be a legitimate reason for this to happen.
1190  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1191 
1192  return true;
1193  } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1194  // EBCDIC encoded XML
1195  wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" );
1196 
1197  return true;
1198  }
1199 
1200  // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1201  // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1202  $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1203  foreach ( $attemptEncodings as $encoding ) {
1204  MediaWiki\suppressWarnings();
1205  $str = iconv( $encoding, 'UTF-8', $contents );
1206  MediaWiki\restoreWarnings();
1207  if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1208  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1209  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1210  ) {
1211  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1212 
1213  return true;
1214  }
1215  } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1216  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1217  // bytes. There shouldn't be a legitimate reason for this to happen.
1218  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1219 
1220  return true;
1221  }
1222  }
1223 
1224  return false;
1225  }
1226 
1232  protected function detectScriptInSvg( $filename, $partial ) {
1233  $this->mSVGNSError = false;
1234  $check = new XmlTypeCheck(
1235  $filename,
1236  array( $this, 'checkSvgScriptCallback' ),
1237  true,
1238  array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1239  );
1240  if ( $check->wellFormed !== true ) {
1241  // Invalid xml (bug 58553)
1242  // But only when non-partial (bug 65724)
1243  return $partial ? false : array( 'uploadinvalidxml' );
1244  } elseif ( $check->filterMatch ) {
1245  if ( $this->mSVGNSError ) {
1246  return array( 'uploadscriptednamespace', $this->mSVGNSError );
1247  }
1248 
1249  return $check->filterMatchType;
1250  }
1251 
1252  return false;
1253  }
1254 
1261  public static function checkSvgPICallback( $target, $data ) {
1262  // Don't allow external stylesheets (bug 57550)
1263  if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1264  return array( 'upload-scripted-pi-callback' );
1265  }
1266 
1267  return false;
1268  }
1269 
1276  public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1277 
1278  list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1279 
1280  // We specifically don't include:
1281  // http://www.w3.org/1999/xhtml (bug 60771)
1282  static $validNamespaces = array(
1283  '',
1284  'adobe:ns:meta/',
1285  'http://creativecommons.org/ns#',
1286  'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1287  'http://ns.adobe.com/adobeillustrator/10.0/',
1288  'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1289  'http://ns.adobe.com/extensibility/1.0/',
1290  'http://ns.adobe.com/flows/1.0/',
1291  'http://ns.adobe.com/illustrator/1.0/',
1292  'http://ns.adobe.com/imagereplacement/1.0/',
1293  'http://ns.adobe.com/pdf/1.3/',
1294  'http://ns.adobe.com/photoshop/1.0/',
1295  'http://ns.adobe.com/saveforweb/1.0/',
1296  'http://ns.adobe.com/variables/1.0/',
1297  'http://ns.adobe.com/xap/1.0/',
1298  'http://ns.adobe.com/xap/1.0/g/',
1299  'http://ns.adobe.com/xap/1.0/g/img/',
1300  'http://ns.adobe.com/xap/1.0/mm/',
1301  'http://ns.adobe.com/xap/1.0/rights/',
1302  'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1303  'http://ns.adobe.com/xap/1.0/stype/font#',
1304  'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1305  'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1306  'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1307  'http://ns.adobe.com/xap/1.0/t/pg/',
1308  'http://purl.org/dc/elements/1.1/',
1309  'http://purl.org/dc/elements/1.1',
1310  'http://schemas.microsoft.com/visio/2003/svgextensions/',
1311  'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1312  'http://taptrix.com/inkpad/svg_extensions',
1313  'http://web.resource.org/cc/',
1314  'http://www.freesoftware.fsf.org/bkchem/cdml',
1315  'http://www.inkscape.org/namespaces/inkscape',
1316  'http://www.opengis.net/gml',
1317  'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1318  'http://www.w3.org/2000/svg',
1319  'http://www.w3.org/tr/rec-rdf-syntax/',
1320  );
1321 
1322  if ( !in_array( $namespace, $validNamespaces ) ) {
1323  wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" );
1325  $this->mSVGNSError = $namespace;
1326 
1327  return true;
1328  }
1329 
1330  /*
1331  * check for elements that can contain javascript
1332  */
1333  if ( $strippedElement == 'script' ) {
1334  wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1335 
1336  return array( 'uploaded-script-svg', $strippedElement );
1337  }
1338 
1339  # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1340  # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1341  if ( $strippedElement == 'handler' ) {
1342  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1343 
1344  return array( 'uploaded-script-svg', $strippedElement );
1345  }
1346 
1347  # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1348  if ( $strippedElement == 'stylesheet' ) {
1349  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1350 
1351  return array( 'uploaded-script-svg', $strippedElement );
1352  }
1353 
1354  # Block iframes, in case they pass the namespace check
1355  if ( $strippedElement == 'iframe' ) {
1356  wfDebug( __METHOD__ . ": iframe in uploaded file.\n" );
1357 
1358  return array( 'uploaded-script-svg', $strippedElement );
1359  }
1360 
1361  # Check <style> css
1362  if ( $strippedElement == 'style'
1363  && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1364  ) {
1365  wfDebug( __METHOD__ . ": hostile css in style element.\n" );
1366  return array( 'uploaded-hostile-svg' );
1367  }
1368 
1369  foreach ( $attribs as $attrib => $value ) {
1370  $stripped = $this->stripXmlNamespace( $attrib );
1371  $value = strtolower( $value );
1372 
1373  if ( substr( $stripped, 0, 2 ) == 'on' ) {
1374  wfDebug( __METHOD__
1375  . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1376 
1377  return array( 'uploaded-event-handler-on-svg', $attrib, $value );
1378  }
1379 
1380  # href with non-local target (don't allow http://, javascript:, etc)
1381  if ( $stripped == 'href'
1382  && strpos( $value, 'data:' ) !== 0
1383  && strpos( $value, '#' ) !== 0
1384  ) {
1385  if ( !( $strippedElement === 'a'
1386  && preg_match( '!^https?://!im', $value ) )
1387  ) {
1388  wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1389  . "'$attrib'='$value' in uploaded file.\n" );
1390 
1391  return array( 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value );
1392  }
1393  }
1394 
1395  # only allow data: targets that should be safe. This prevents vectors like,
1396  # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1397  if ( $stripped == 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1398  // rfc2397 parameters. This is only slightly slower than (;[\w;]+)*.
1399  $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1400  if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1401  wfDebug( __METHOD__ . ": Found href to unwhitelisted data: uri "
1402  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1403  return array( 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value );
1404  }
1405  }
1406 
1407  # Change href with animate from (http://html5sec.org/#137).
1408  if ( $stripped === 'attributename'
1409  && $strippedElement === 'animate'
1410  && $this->stripXmlNamespace( $value ) == 'href'
1411  ) {
1412  wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1413  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1414 
1415  return array( 'uploaded-animate-svg', $strippedElement, $attrib, $value );
1416  }
1417 
1418  # use set/animate to add event-handler attribute to parent
1419  if ( ( $strippedElement == 'set' || $strippedElement == 'animate' )
1420  && $stripped == 'attributename'
1421  && substr( $value, 0, 2 ) == 'on'
1422  ) {
1423  wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1424  . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1425 
1426  return array( 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value );
1427  }
1428 
1429  # use set to add href attribute to parent element
1430  if ( $strippedElement == 'set'
1431  && $stripped == 'attributename'
1432  && strpos( $value, 'href' ) !== false
1433  ) {
1434  wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" );
1435 
1436  return array( 'uploaded-setting-href-svg' );
1437  }
1438 
1439  # use set to add a remote / data / script target to an element
1440  if ( $strippedElement == 'set'
1441  && $stripped == 'to'
1442  && preg_match( '!(http|https|data|script):!sim', $value )
1443  ) {
1444  wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" );
1445 
1446  return array( 'uploaded-wrong-setting-svg', $value );
1447  }
1448 
1449  # use handler attribute with remote / data / script
1450  if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1451  wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1452  . "'$attrib'='$value' in uploaded file.\n" );
1453 
1454  return array( 'uploaded-setting-handler-svg', $attrib, $value );
1455  }
1456 
1457  # use CSS styles to bring in remote code
1458  if ( $stripped == 'style'
1459  && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1460  ) {
1461  wfDebug( __METHOD__ . ": Found svg setting a style with "
1462  . "remote url '$attrib'='$value' in uploaded file.\n" );
1463  return array( 'uploaded-remote-url-svg', $attrib, $value );
1464  }
1465 
1466  # Several attributes can include css, css character escaping isn't allowed
1467  $cssAttrs = array( 'font', 'clip-path', 'fill', 'filter', 'marker',
1468  'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' );
1469  if ( in_array( $stripped, $cssAttrs )
1470  && self::checkCssFragment( $value )
1471  ) {
1472  wfDebug( __METHOD__ . ": Found svg setting a style with "
1473  . "remote url '$attrib'='$value' in uploaded file.\n" );
1474  return array( 'uploaded-remote-url-svg', $attrib, $value );
1475  }
1476 
1477  # image filters can pull in url, which could be svg that executes scripts
1478  if ( $strippedElement == 'image'
1479  && $stripped == 'filter'
1480  && preg_match( '!url\s*\(!sim', $value )
1481  ) {
1482  wfDebug( __METHOD__ . ": Found image filter with url: "
1483  . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1484 
1485  return array( 'uploaded-image-filter-svg', $strippedElement, $stripped, $value );
1486  }
1487  }
1488 
1489  return false; //No scripts detected
1490  }
1491 
1499  private static function checkCssFragment( $value ) {
1500 
1501  # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1502  if ( stripos( $value, '@import' ) !== false ) {
1503  return true;
1504  }
1505 
1506  # We allow @font-face to embed fonts with data: urls, so we snip the string
1507  # 'url' out so this case won't match when we check for urls below
1508  $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1509  $value = preg_replace( $pattern, '$1$2', $value );
1510 
1511  # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1512  # properties filter and accelerator don't seem to be useful for xss in SVG files.
1513  # Expression and -o-link don't seem to work either, but filtering them here in case.
1514  # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1515  # but not local ones such as url("#..., url('#..., url(#....
1516  if ( preg_match( '!expression
1517  | -o-link\s*:
1518  | -o-link-source\s*:
1519  | -o-replace\s*:!imx', $value ) ) {
1520  return true;
1521  }
1522 
1523  if ( preg_match_all(
1524  "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1525  $value,
1526  $matches
1527  ) !== 0
1528  ) {
1529  # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1530  foreach ( $matches[1] as $match ) {
1531  if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1532  return true;
1533  }
1534  }
1535  }
1536 
1537  if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1538  return true;
1539  }
1540 
1541  return false;
1542  }
1543 
1549  private static function splitXmlNamespace( $element ) {
1550  // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1551  $parts = explode( ':', strtolower( $element ) );
1552  $name = array_pop( $parts );
1553  $ns = implode( ':', $parts );
1554 
1555  return array( $ns, $name );
1556  }
1557 
1562  private function stripXmlNamespace( $name ) {
1563  // 'http://www.w3.org/2000/svg:script' -> 'script'
1564  $parts = explode( ':', strtolower( $name ) );
1565 
1566  return array_pop( $parts );
1567  }
1568 
1579  public static function detectVirus( $file ) {
1581 
1582  if ( !$wgAntivirus ) {
1583  wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1584 
1585  return null;
1586  }
1587 
1588  if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1589  wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1590  $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1591  array( 'virus-badscanner', $wgAntivirus ) );
1592 
1593  return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1594  }
1595 
1596  # look up scanner configuration
1597  $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1598  $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1599  $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1600  $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1601 
1602  if ( strpos( $command, "%f" ) === false ) {
1603  # simple pattern: append file to scan
1604  $command .= " " . wfEscapeShellArg( $file );
1605  } else {
1606  # complex pattern: replace "%f" with file to scan
1607  $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1608  }
1609 
1610  wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1611 
1612  # execute virus scanner
1613  $exitCode = false;
1614 
1615  # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1616  # that does not seem to be worth the pain.
1617  # Ask me (Duesentrieb) about it if it's ever needed.
1618  $output = wfShellExecWithStderr( $command, $exitCode );
1619 
1620  # map exit code to AV_xxx constants.
1621  $mappedCode = $exitCode;
1622  if ( $exitCodeMap ) {
1623  if ( isset( $exitCodeMap[$exitCode] ) ) {
1624  $mappedCode = $exitCodeMap[$exitCode];
1625  } elseif ( isset( $exitCodeMap["*"] ) ) {
1626  $mappedCode = $exitCodeMap["*"];
1627  }
1628  }
1629 
1630  /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1631  * so we need the strict equalities === and thus can't use a switch here
1632  */
1633  if ( $mappedCode === AV_SCAN_FAILED ) {
1634  # scan failed (code was mapped to false by $exitCodeMap)
1635  wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1636 
1637  $output = $wgAntivirusRequired
1638  ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text()
1639  : null;
1640  } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1641  # scan failed because filetype is unknown (probably imune)
1642  wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1643  $output = null;
1644  } elseif ( $mappedCode === AV_NO_VIRUS ) {
1645  # no virus found
1646  wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1647  $output = false;
1648  } else {
1649  $output = trim( $output );
1650 
1651  if ( !$output ) {
1652  $output = true; #if there's no output, return true
1653  } elseif ( $msgPattern ) {
1654  $groups = array();
1655  if ( preg_match( $msgPattern, $output, $groups ) ) {
1656  if ( $groups[1] ) {
1657  $output = $groups[1];
1658  }
1659  }
1660  }
1661 
1662  wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1663  }
1664 
1665  return $output;
1666  }
1667 
1676  private function checkOverwrite( $user ) {
1677  // First check whether the local file can be overwritten
1678  $file = $this->getLocalFile();
1679  $file->load( File::READ_LATEST );
1680  if ( $file->exists() ) {
1681  if ( !self::userCanReUpload( $user, $file ) ) {
1682  return array( 'fileexists-forbidden', $file->getName() );
1683  } else {
1684  return true;
1685  }
1686  }
1687 
1688  /* Check shared conflicts: if the local file does not exist, but
1689  * wfFindFile finds a file, it exists in a shared repository.
1690  */
1691  $file = wfFindFile( $this->getTitle(), array( 'latest' => true ) );
1692  if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1693  return array( 'fileexists-shared-forbidden', $file->getName() );
1694  }
1695 
1696  return true;
1697  }
1698 
1706  public static function userCanReUpload( User $user, $img ) {
1707  if ( $user->isAllowed( 'reupload' ) ) {
1708  return true; // non-conditional
1709  }
1710  if ( !$user->isAllowed( 'reupload-own' ) ) {
1711  return false;
1712  }
1713  if ( is_string( $img ) ) {
1714  $img = wfLocalFile( $img );
1715  }
1716  if ( !( $img instanceof LocalFile ) ) {
1717  return false;
1718  }
1719 
1720  $img->load( File::READ_LATEST );
1721 
1722  return $user->getId() == $img->getUser( 'id' );
1723  }
1724 
1736  public static function getExistsWarning( $file ) {
1737  if ( $file->exists() ) {
1738  return array( 'warning' => 'exists', 'file' => $file );
1739  }
1740 
1741  if ( $file->getTitle()->getArticleID() ) {
1742  return array( 'warning' => 'page-exists', 'file' => $file );
1743  }
1744 
1745  if ( $file->wasDeleted() && !$file->exists() ) {
1746  return array( 'warning' => 'was-deleted', 'file' => $file );
1747  }
1748 
1749  if ( strpos( $file->getName(), '.' ) == false ) {
1750  $partname = $file->getName();
1751  $extension = '';
1752  } else {
1753  $n = strrpos( $file->getName(), '.' );
1754  $extension = substr( $file->getName(), $n + 1 );
1755  $partname = substr( $file->getName(), 0, $n );
1756  }
1757  $normalizedExtension = File::normalizeExtension( $extension );
1758 
1759  if ( $normalizedExtension != $extension ) {
1760  // We're not using the normalized form of the extension.
1761  // Normal form is lowercase, using most common of alternate
1762  // extensions (eg 'jpg' rather than 'JPEG').
1763  //
1764  // Check for another file using the normalized form...
1765  $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1766  $file_lc = wfLocalFile( $nt_lc );
1767 
1768  if ( $file_lc->exists() ) {
1769  return array(
1770  'warning' => 'exists-normalized',
1771  'file' => $file,
1772  'normalizedFile' => $file_lc
1773  );
1774  }
1775  }
1776 
1777  // Check for files with the same name but a different extension
1778  $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix(
1779  "{$partname}.", 1 );
1780  if ( count( $similarFiles ) ) {
1781  return array(
1782  'warning' => 'exists-normalized',
1783  'file' => $file,
1784  'normalizedFile' => $similarFiles[0],
1785  );
1786  }
1787 
1788  if ( self::isThumbName( $file->getName() ) ) {
1789  # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1790  $nt_thb = Title::newFromText(
1791  substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
1792  NS_FILE
1793  );
1794  $file_thb = wfLocalFile( $nt_thb );
1795  if ( $file_thb->exists() ) {
1796  return array(
1797  'warning' => 'thumb',
1798  'file' => $file,
1799  'thumbFile' => $file_thb
1800  );
1801  } else {
1802  // File does not exist, but we just don't like the name
1803  return array(
1804  'warning' => 'thumb-name',
1805  'file' => $file,
1806  'thumbFile' => $file_thb
1807  );
1808  }
1809  }
1810 
1811  foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
1812  if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1813  return array(
1814  'warning' => 'bad-prefix',
1815  'file' => $file,
1816  'prefix' => $prefix
1817  );
1818  }
1819  }
1820 
1821  return false;
1822  }
1823 
1829  public static function isThumbName( $filename ) {
1830  $n = strrpos( $filename, '.' );
1831  $partname = $n ? substr( $filename, 0, $n ) : $filename;
1832 
1833  return (
1834  substr( $partname, 3, 3 ) == 'px-' ||
1835  substr( $partname, 2, 3 ) == 'px-'
1836  ) &&
1837  preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1838  }
1839 
1845  public static function getFilenamePrefixBlacklist() {
1846  $blacklist = array();
1847  $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1848  if ( !$message->isDisabled() ) {
1849  $lines = explode( "\n", $message->plain() );
1850  foreach ( $lines as $line ) {
1851  // Remove comment lines
1852  $comment = substr( trim( $line ), 0, 1 );
1853  if ( $comment == '#' || $comment == '' ) {
1854  continue;
1855  }
1856  // Remove additional comments after a prefix
1857  $comment = strpos( $line, '#' );
1858  if ( $comment > 0 ) {
1859  $line = substr( $line, 0, $comment - 1 );
1860  }
1861  $blacklist[] = trim( $line );
1862  }
1863  }
1864 
1865  return $blacklist;
1866  }
1867 
1879  public function getImageInfo( $result ) {
1880  $file = $this->getLocalFile();
1886  if ( $file instanceof UploadStashFile ) {
1888  $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1889  } else {
1891  $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1892  }
1893 
1894  return $info;
1895  }
1896 
1901  public function convertVerifyErrorToStatus( $error ) {
1902  $code = $error['status'];
1903  unset( $code['status'] );
1904 
1905  return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1906  }
1907 
1912  public static function getMaxUploadSize( $forType = null ) {
1914 
1915  if ( is_array( $wgMaxUploadSize ) ) {
1916  if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1917  return $wgMaxUploadSize[$forType];
1918  } else {
1919  return $wgMaxUploadSize['*'];
1920  }
1921  } else {
1922  return intval( $wgMaxUploadSize );
1923  }
1924  }
1925 
1935  public static function getSessionStatus( User $user, $statusKey ) {
1936  $key = wfMemcKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
1937 
1938  return ObjectCache::getMainStashInstance()->get( $key );
1939  }
1940 
1951  public static function setSessionStatus( User $user, $statusKey, $value ) {
1952  $key = wfMemcKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
1953 
1955  if ( $value === false ) {
1956  $cache->delete( $key );
1957  } else {
1958  $cache->set( $key, $value, 86400 );
1959  }
1960  }
1961 }
$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.
Definition: UploadBase.php:981
getImageInfo($result)
Gets image info about the file just uploaded.
getVerificationErrorCode($error)
Definition: UploadBase.php:76
null means default in associative array form
Definition: hooks.txt:1740
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:70
$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:2266
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:141
static isAllowed($user)
Returns true if the user can use this upload module or else a string identifying the missing permissi...
Definition: UploadBase.php:121
performUpload($comment, $pageText, $watch, $user)
Really perform the upload.
Definition: UploadBase.php:687
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:324
const UPLOAD_VERIFICATION_ERROR
Definition: UploadBase.php:66
static singleton()
Get an instance of this class.
Definition: MimeMagic.php:357
$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:968
static checkFileExtension($ext, $list)
Perform case-insensitive match against a list of file extensions.
Definition: UploadBase.php:969
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:185
$comment
wfDebug($text, $dest= 'all', array $context=array())
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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:549
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:235
const ILLEGAL_FILENAME
Definition: UploadBase.php:59
isEmptyFile()
Return true if the file is empty.
Definition: UploadBase.php:239
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:83
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:2007
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
Definition: globals.txt:10
verifyMimeType($mime)
Verify the MIME type.
Definition: UploadBase.php:372
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)
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
verifyPartialFile()
A verification routine suitable for partial files.
Definition: UploadBase.php:460
$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, password, email address, options, last login time).
Definition: User.php:39
static decodeCharReferences($text)
Decode any character references, numeric or named entities, in the text and return a UTF-8 string...
Definition: Sanitizer.php:1421
$wgEnableUploads
Uploads have to be specially set up to be secure.
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 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
static isThumbName($filename)
Helper function that checks whether the filename looks like a thumbnail.
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:47
zipEntryCallback($entry)
Callback for ZipDirectoryReader to detect Java class files.
Definition: UploadBase.php:520
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:882
$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:255
stashFileGetKey()
Stash a file in a temporary directory, returning a key which can be used to find the file again...
Definition: UploadBase.php:917
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.
you don t have to do a grep find to see where the $wgReverseTitle variable is used
Definition: hooks.txt:117
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:53
fetchFile()
Fetch the file.
Definition: UploadBase.php:231
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:137
stashSession()
alias for stashFileGetKey, for backwards compatibility
Definition: UploadBase.php:926
postProcessUpload()
Perform extra steps after a successful upload.
Definition: UploadBase.php:721
$cache
Definition: mcc.php:32
getTitle()
Returns the title of the file to be uploaded.
Definition: UploadBase.php:751
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:954
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:502
cleanupTempFile()
If we've modified the upload file we need to manually remove it on exit to clean up.
Definition: UploadBase.php:934
getSourceType()
Returns the upload type.
Definition: UploadBase.php:198
const FILE_TOO_LARGE
Definition: UploadBase.php:68
Allows to change the fields on the form that will be generated just before adding its HTML to parser output an object of one of the gallery classes(inheriting from ImageGalleryBase) $html conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:327
checkWarnings()
Check for non fatal problems with the file.
Definition: UploadBase.php:602
initializeFromRequest(&$request)
Initialize from a WebRequest.
verifyUpload()
Verify whether the upload is sane.
Definition: UploadBase.php:285
const MIN_LENGTH_PARTNAME
Definition: UploadBase.php:58
getFileSize()
Return the file size.
Definition: UploadBase.php:247
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:251
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:102
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
#define the
validateName()
Verify that the name is valid and, if necessary, that we can overwrite.
Definition: UploadBase.php:342
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:877
static singleton($wiki=false)
$wgAntivirusSetup
Configuration for different virus scanners.
Prior to maintenance scripts were a hodgepodge of code that had no cohesion or formal method of action Beginning in
Definition: maintenance.txt:1
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:968
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 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:2283
static normalizeCss($value)
Normalize CSS into a format we can easily search for hostile input.
Definition: Sanitizer.php:853
$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:564
$lines
Definition: router.php:66
const HOOK_ABORTED
Definition: UploadBase.php:67
stashFile(User $user=null)
If the user does not supply all necessary information in the first upload form submission (either by ...
Definition: UploadBase.php:901
getId()
Get the user's ID.
Definition: User.php:1983
static verifyExtension($mime, $extension)
Checks if the MIME type of the uploaded file matches the file extension.
Definition: UploadBase.php:992
detectScriptInSvg($filename, $partial)
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
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)
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 '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 wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() '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:1738
$line
Definition: cdb.php:59
static $uploadHandlers
Definition: UploadBase.php:132
const WINDOWS_NONASCII_FILENAME
Definition: UploadBase.php:69
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...
wfMemcKey()
Make a cache key for the local wiki.
$wgOut
Definition: Setup.php:666
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:404
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:235
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 one of or reset my talk page
Definition: hooks.txt:2283
const EMPTY_FILE
Definition: UploadBase.php:57
static capitalize($text, $ns=NS_MAIN)
Capitalize a text string for a title if it belongs to a namespace that capitalizes.
Definition: Title.php:3298
static & makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:478
static newGood($value=null)
Factory function for good results.
Definition: Status.php:95
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:1740
getRealPath($srcPath)
Definition: UploadBase.php:263
initializePathInfo($name, $tempPath, $fileSize, $removeTempFile=false)
Initialize the path information.
Definition: UploadBase.php:210
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