MediaWiki  1.23.2
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( 'UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'UTF-16', 'UTF-32' );
48 
49  const SUCCESS = 0;
50  const OK = 0;
51  const EMPTY_FILE = 3;
53  const ILLEGAL_FILENAME = 5;
54  const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
55  const FILETYPE_MISSING = 8;
56  const FILETYPE_BADTYPE = 9;
57  const VERIFICATION_ERROR = 10;
58 
59  # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
61  const HOOK_ABORTED = 11;
62  const FILE_TOO_LARGE = 12;
64  const FILENAME_TOO_LONG = 14;
65 
66  const SESSION_STATUS_KEY = 'wsUploadStatusData';
67 
72  public function getVerificationErrorCode( $error ) {
73  $code_to_status = array(
74  self::EMPTY_FILE => 'empty-file',
75  self::FILE_TOO_LARGE => 'file-too-large',
76  self::FILETYPE_MISSING => 'filetype-missing',
77  self::FILETYPE_BADTYPE => 'filetype-banned',
78  self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
79  self::ILLEGAL_FILENAME => 'illegal-filename',
80  self::OVERWRITE_EXISTING_FILE => 'overwrite',
81  self::VERIFICATION_ERROR => 'verification-error',
82  self::HOOK_ABORTED => 'hookaborted',
83  self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
84  self::FILENAME_TOO_LONG => 'filename-toolong',
85  );
86  if ( isset( $code_to_status[$error] ) ) {
87  return $code_to_status[$error];
88  }
89 
90  return 'unknown-error';
91  }
92 
98  public static function isEnabled() {
99  global $wgEnableUploads;
100 
101  if ( !$wgEnableUploads ) {
102  return false;
103  }
104 
105  # Check php's file_uploads setting
106  return wfIsHHVM() || wfIniGetBool( 'file_uploads' );
107  }
108 
117  public static function isAllowed( $user ) {
118  foreach ( array( 'upload', 'edit' ) as $permission ) {
119  if ( !$user->isAllowed( $permission ) ) {
120  return $permission;
121  }
122  }
123  return true;
124  }
125 
126  // Upload handlers. Should probably just be a global.
127  static $uploadHandlers = array( 'Stash', 'File', 'Url' );
128 
136  public static function createFromRequest( &$request, $type = null ) {
137  $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
138 
139  if ( !$type ) {
140  return null;
141  }
142 
143  // Get the upload class
144  $type = ucfirst( $type );
145 
146  // Give hooks the chance to handle this request
147  $className = null;
148  wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
149  if ( is_null( $className ) ) {
150  $className = 'UploadFrom' . $type;
151  wfDebug( __METHOD__ . ": class name: $className\n" );
152  if ( !in_array( $type, self::$uploadHandlers ) ) {
153  return null;
154  }
155  }
156 
157  // Check whether this upload class is enabled
158  if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
159  return null;
160  }
161 
162  // Check whether the request is valid
163  if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
164  return null;
165  }
166 
167  $handler = new $className;
168 
169  $handler->initializeFromRequest( $request );
170  return $handler;
171  }
172 
178  public static function isValidRequest( $request ) {
179  return false;
180  }
181 
182  public function __construct() {}
183 
190  public function getSourceType() {
191  return null;
192  }
193 
202  public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
203  $this->mDesiredDestName = $name;
204  if ( FileBackend::isStoragePath( $tempPath ) ) {
205  throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
206  }
207  $this->mTempPath = $tempPath;
208  $this->mFileSize = $fileSize;
209  $this->mRemoveTempFile = $removeTempFile;
210  }
211 
215  abstract public function initializeFromRequest( &$request );
216 
221  public function fetchFile() {
222  return Status::newGood();
223  }
224 
229  public function isEmptyFile() {
230  return empty( $this->mFileSize );
231  }
232 
237  public function getFileSize() {
238  return $this->mFileSize;
239  }
240 
245  public function getTempFileSha1Base36() {
246  return FSFile::getSha1Base36FromPath( $this->mTempPath );
247  }
248 
253  function getRealPath( $srcPath ) {
254  wfProfileIn( __METHOD__ );
255  $repo = RepoGroup::singleton()->getLocalRepo();
256  if ( $repo->isVirtualUrl( $srcPath ) ) {
257  // @todo just make uploads work with storage paths
258  // UploadFromStash loads files via virtual URLs
259  $tmpFile = $repo->getLocalCopy( $srcPath );
260  if ( $tmpFile ) {
261  $tmpFile->bind( $this ); // keep alive with $this
262  }
263  $path = $tmpFile ? $tmpFile->getPath() : false;
264  } else {
265  $path = $srcPath;
266  }
267  wfProfileOut( __METHOD__ );
268  return $path;
269  }
270 
275  public function verifyUpload() {
276  wfProfileIn( __METHOD__ );
277 
281  if ( $this->isEmptyFile() ) {
282  wfProfileOut( __METHOD__ );
283  return array( 'status' => self::EMPTY_FILE );
284  }
285 
289  $maxSize = self::getMaxUploadSize( $this->getSourceType() );
290  if ( $this->mFileSize > $maxSize ) {
291  wfProfileOut( __METHOD__ );
292  return array(
293  'status' => self::FILE_TOO_LARGE,
294  'max' => $maxSize,
295  );
296  }
297 
303  $verification = $this->verifyFile();
304  if ( $verification !== true ) {
305  wfProfileOut( __METHOD__ );
306  return array(
307  'status' => self::VERIFICATION_ERROR,
308  'details' => $verification
309  );
310  }
311 
315  $result = $this->validateName();
316  if ( $result !== true ) {
317  wfProfileOut( __METHOD__ );
318  return $result;
319  }
320 
321  $error = '';
322  if ( !wfRunHooks( 'UploadVerification',
323  array( $this->mDestName, $this->mTempPath, &$error ) )
324  ) {
325  wfProfileOut( __METHOD__ );
326  return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
327  }
328 
329  wfProfileOut( __METHOD__ );
330  return array( 'status' => self::OK );
331  }
332 
339  public function validateName() {
340  $nt = $this->getTitle();
341  if ( is_null( $nt ) ) {
342  $result = array( 'status' => $this->mTitleError );
343  if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
344  $result['filtered'] = $this->mFilteredName;
345  }
346  if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
347  $result['finalExt'] = $this->mFinalExtension;
348  if ( count( $this->mBlackListedExtensions ) ) {
349  $result['blacklistedExt'] = $this->mBlackListedExtensions;
350  }
351  }
352  return $result;
353  }
354  $this->mDestName = $this->getLocalFile()->getName();
355 
356  return true;
357  }
358 
367  protected function verifyMimeType( $mime ) {
368  global $wgVerifyMimeType;
369  wfProfileIn( __METHOD__ );
370  if ( $wgVerifyMimeType ) {
371  wfDebug( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" );
372  global $wgMimeTypeBlacklist;
373  if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
374  wfProfileOut( __METHOD__ );
375  return array( 'filetype-badmime', $mime );
376  }
377 
378  # Check IE type
379  $fp = fopen( $this->mTempPath, 'rb' );
380  $chunk = fread( $fp, 256 );
381  fclose( $fp );
382 
383  $magic = MimeMagic::singleton();
384  $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
385  $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
386  foreach ( $ieTypes as $ieType ) {
387  if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
388  wfProfileOut( __METHOD__ );
389  return array( 'filetype-bad-ie-mime', $ieType );
390  }
391  }
392  }
393 
394  wfProfileOut( __METHOD__ );
395  return true;
396  }
397 
403  protected function verifyFile() {
404  global $wgVerifyMimeType;
405  wfProfileIn( __METHOD__ );
406 
407  $status = $this->verifyPartialFile();
408  if ( $status !== true ) {
409  wfProfileOut( __METHOD__ );
410  return $status;
411  }
412 
413  $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
414  $mime = $this->mFileProps['file-mime'];
415 
416  if ( $wgVerifyMimeType ) {
417  # XXX: Missing extension will be caught by validateName() via getTitle()
418  if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
419  wfProfileOut( __METHOD__ );
420  return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
421  }
422  }
423 
424  $handler = MediaHandler::getHandler( $mime );
425  if ( $handler ) {
426  $handlerStatus = $handler->verifyUpload( $this->mTempPath );
427  if ( !$handlerStatus->isOK() ) {
428  $errors = $handlerStatus->getErrorsArray();
429  wfProfileOut( __METHOD__ );
430  return reset( $errors );
431  }
432  }
433 
434  wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
435  if ( $status !== true ) {
436  wfProfileOut( __METHOD__ );
437  return $status;
438  }
439 
440  wfDebug( __METHOD__ . ": all clear; passing.\n" );
441  wfProfileOut( __METHOD__ );
442  return true;
443  }
444 
453  protected function verifyPartialFile() {
454  global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
455  wfProfileIn( __METHOD__ );
456 
457  # getTitle() sets some internal parameters like $this->mFinalExtension
458  $this->getTitle();
459 
460  $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
461 
462  # check mime type, if desired
463  $mime = $this->mFileProps['file-mime'];
464  $status = $this->verifyMimeType( $mime );
465  if ( $status !== true ) {
466  wfProfileOut( __METHOD__ );
467  return $status;
468  }
469 
470  # check for htmlish code and javascript
471  if ( !$wgDisableUploadScriptChecks ) {
472  if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
473  wfProfileOut( __METHOD__ );
474  return array( 'uploadscripted' );
475  }
476  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
477  $svgStatus = $this->detectScriptInSvg( $this->mTempPath );
478  if ( $svgStatus !== false ) {
479  wfProfileOut( __METHOD__ );
480  return $svgStatus;
481  }
482  }
483  }
484 
485  # Check for Java applets, which if uploaded can bypass cross-site
486  # restrictions.
487  if ( !$wgAllowJavaUploads ) {
488  $this->mJavaDetected = false;
489  $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
490  array( $this, 'zipEntryCallback' ) );
491  if ( !$zipStatus->isOK() ) {
492  $errors = $zipStatus->getErrorsArray();
493  $error = reset( $errors );
494  if ( $error[0] !== 'zip-wrong-format' ) {
495  wfProfileOut( __METHOD__ );
496  return $error;
497  }
498  }
499  if ( $this->mJavaDetected ) {
500  wfProfileOut( __METHOD__ );
501  return array( 'uploadjava' );
502  }
503  }
504 
505  # Scan the uploaded file for viruses
506  $virus = $this->detectVirus( $this->mTempPath );
507  if ( $virus ) {
508  wfProfileOut( __METHOD__ );
509  return array( 'uploadvirus', $virus );
510  }
511 
512  wfProfileOut( __METHOD__ );
513  return true;
514  }
515 
519  function zipEntryCallback( $entry ) {
520  $names = array( $entry['name'] );
521 
522  // If there is a null character, cut off the name at it, because JDK's
523  // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
524  // were constructed which had ".class\0" followed by a string chosen to
525  // make the hash collide with the truncated name, that file could be
526  // returned in response to a request for the .class file.
527  $nullPos = strpos( $entry['name'], "\000" );
528  if ( $nullPos !== false ) {
529  $names[] = substr( $entry['name'], 0, $nullPos );
530  }
531 
532  // If there is a trailing slash in the file name, we have to strip it,
533  // because that's what ZIP_GetEntry() does.
534  if ( preg_grep( '!\.class/?$!', $names ) ) {
535  $this->mJavaDetected = true;
536  }
537  }
538 
546  public function verifyPermissions( $user ) {
547  return $this->verifyTitlePermissions( $user );
548  }
549 
561  public function verifyTitlePermissions( $user ) {
566  $nt = $this->getTitle();
567  if ( is_null( $nt ) ) {
568  return true;
569  }
570  $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
571  $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
572  if ( !$nt->exists() ) {
573  $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
574  } else {
575  $permErrorsCreate = array();
576  }
577  if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
578  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
579  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
580  return $permErrors;
581  }
582 
583  $overwriteError = $this->checkOverwrite( $user );
584  if ( $overwriteError !== true ) {
585  return array( $overwriteError );
586  }
587 
588  return true;
589  }
590 
598  public function checkWarnings() {
599  global $wgLang;
600  wfProfileIn( __METHOD__ );
601 
602  $warnings = array();
603 
604  $localFile = $this->getLocalFile();
605  $filename = $localFile->getName();
606 
611  $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
612  $comparableName = Title::capitalize( $comparableName, NS_FILE );
613 
614  if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
615  $warnings['badfilename'] = $filename;
616  // Debugging for bug 62241
617  wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: '$this->mDesiredDestName', comparableName: '$comparableName'" );
618  }
619 
620  // Check whether the file extension is on the unwanted list
621  global $wgCheckFileExtensions, $wgFileExtensions;
622  if ( $wgCheckFileExtensions ) {
623  $extensions = array_unique( $wgFileExtensions );
624  if ( !$this->checkFileExtension( $this->mFinalExtension, $extensions ) ) {
625  $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension,
626  $wgLang->commaList( $extensions ), count( $extensions ) );
627  }
628  }
629 
630  global $wgUploadSizeWarning;
631  if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
632  $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize );
633  }
634 
635  if ( $this->mFileSize == 0 ) {
636  $warnings['emptyfile'] = true;
637  }
638 
639  $exists = self::getExistsWarning( $localFile );
640  if ( $exists !== false ) {
641  $warnings['exists'] = $exists;
642  }
643 
644  // Check dupes against existing files
645  $hash = $this->getTempFileSha1Base36();
646  $dupes = RepoGroup::singleton()->findBySha1( $hash );
647  $title = $this->getTitle();
648  // Remove all matches against self
649  foreach ( $dupes as $key => $dupe ) {
650  if ( $title->equals( $dupe->getTitle() ) ) {
651  unset( $dupes[$key] );
652  }
653  }
654  if ( $dupes ) {
655  $warnings['duplicate'] = $dupes;
656  }
657 
658  // Check dupes against archives
659  $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
660  if ( $archivedImage->getID() > 0 ) {
661  if ( $archivedImage->userCan( File::DELETED_FILE ) ) {
662  $warnings['duplicate-archive'] = $archivedImage->getName();
663  } else {
664  $warnings['duplicate-archive'] = '';
665  }
666  }
667 
668  wfProfileOut( __METHOD__ );
669  return $warnings;
670  }
671 
683  public function performUpload( $comment, $pageText, $watch, $user ) {
684  wfProfileIn( __METHOD__ );
685 
686  $status = $this->getLocalFile()->upload(
687  $this->mTempPath,
688  $comment,
689  $pageText,
691  $this->mFileProps,
692  false,
693  $user
694  );
695 
696  if ( $status->isGood() ) {
697  if ( $watch ) {
699  }
700  wfRunHooks( 'UploadComplete', array( &$this ) );
701  }
702 
703  wfProfileOut( __METHOD__ );
704  return $status;
705  }
706 
713  public function getTitle() {
714  if ( $this->mTitle !== false ) {
715  return $this->mTitle;
716  }
717  /* Assume that if a user specified File:Something.jpg, this is an error
718  * and that the namespace prefix needs to be stripped of.
719  */
720  $title = Title::newFromText( $this->mDesiredDestName );
721  if ( $title && $title->getNamespace() == NS_FILE ) {
722  $this->mFilteredName = $title->getDBkey();
723  } else {
724  $this->mFilteredName = $this->mDesiredDestName;
725  }
726 
727  # oi_archive_name is max 255 bytes, which include a timestamp and an
728  # exclamation mark, so restrict file name to 240 bytes.
729  if ( strlen( $this->mFilteredName ) > 240 ) {
730  $this->mTitleError = self::FILENAME_TOO_LONG;
731  $this->mTitle = null;
732  return $this->mTitle;
733  }
734 
740  $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
741  /* Normalize to title form before we do any further processing */
742  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
743  if ( is_null( $nt ) ) {
744  $this->mTitleError = self::ILLEGAL_FILENAME;
745  $this->mTitle = null;
746  return $this->mTitle;
747  }
748  $this->mFilteredName = $nt->getDBkey();
749 
754  list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
755 
756  if ( count( $ext ) ) {
757  $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
758  } else {
759  $this->mFinalExtension = '';
760 
761  # No extension, try guessing one
762  $magic = MimeMagic::singleton();
763  $mime = $magic->guessMimeType( $this->mTempPath );
764  if ( $mime !== 'unknown/unknown' ) {
765  # Get a space separated list of extensions
766  $extList = $magic->getExtensionsForType( $mime );
767  if ( $extList ) {
768  # Set the extension to the canonical extension
769  $this->mFinalExtension = strtok( $extList, ' ' );
770 
771  # Fix up the other variables
772  $this->mFilteredName .= ".{$this->mFinalExtension}";
773  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
774  $ext = array( $this->mFinalExtension );
775  }
776  }
777  }
778 
779  /* Don't allow users to override the blacklist (check file extension) */
780  global $wgCheckFileExtensions, $wgStrictFileExtensions;
781  global $wgFileExtensions, $wgFileBlacklist;
782 
783  $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
784 
785  if ( $this->mFinalExtension == '' ) {
786  $this->mTitleError = self::FILETYPE_MISSING;
787  $this->mTitle = null;
788  return $this->mTitle;
789  } elseif ( $blackListedExtensions ||
790  ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
791  !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
792  $this->mBlackListedExtensions = $blackListedExtensions;
793  $this->mTitleError = self::FILETYPE_BADTYPE;
794  $this->mTitle = null;
795  return $this->mTitle;
796  }
797 
798  // Windows may be broken with special characters, see bug XXX
799  if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
800  $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
801  $this->mTitle = null;
802  return $this->mTitle;
803  }
804 
805  # If there was more than one "extension", reassemble the base
806  # filename to prevent bogus complaints about length
807  if ( count( $ext ) > 1 ) {
808  for ( $i = 0; $i < count( $ext ) - 1; $i++ ) {
809  $partname .= '.' . $ext[$i];
810  }
811  }
812 
813  if ( strlen( $partname ) < 1 ) {
814  $this->mTitleError = self::MIN_LENGTH_PARTNAME;
815  $this->mTitle = null;
816  return $this->mTitle;
817  }
818 
819  $this->mTitle = $nt;
820  return $this->mTitle;
821  }
822 
828  public function getLocalFile() {
829  if ( is_null( $this->mLocalFile ) ) {
830  $nt = $this->getTitle();
831  $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
832  }
833  return $this->mLocalFile;
834  }
835 
848  public function stashFile( User $user = null ) {
849  // was stashSessionFile
850  wfProfileIn( __METHOD__ );
851 
852  $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user );
853  $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
854  $this->mLocalFile = $file;
855 
856  wfProfileOut( __METHOD__ );
857  return $file;
858  }
859 
865  public function stashFileGetKey() {
866  return $this->stashFile()->getFileKey();
867  }
868 
874  public function stashSession() {
875  return $this->stashFileGetKey();
876  }
877 
882  public function cleanupTempFile() {
883  if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
884  wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
885  unlink( $this->mTempPath );
886  }
887  }
888 
889  public function getTempPath() {
890  return $this->mTempPath;
891  }
892 
902  public static function splitExtensions( $filename ) {
903  $bits = explode( '.', $filename );
904  $basename = array_shift( $bits );
905  return array( $basename, $bits );
906  }
907 
916  public static function checkFileExtension( $ext, $list ) {
917  return in_array( strtolower( $ext ), $list );
918  }
919 
928  public static function checkFileExtensionList( $ext, $list ) {
929  return array_intersect( array_map( 'strtolower', $ext ), $list );
930  }
931 
939  public static function verifyExtension( $mime, $extension ) {
940  $magic = MimeMagic::singleton();
941 
942  if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) {
943  if ( !$magic->isRecognizableExtension( $extension ) ) {
944  wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
945  "unrecognized extension '$extension', can't verify\n" );
946  return true;
947  } else {
948  wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
949  "recognized extension '$extension', so probably invalid file\n" );
950  return false;
951  }
952  }
953 
954  $match = $magic->isMatchingExtension( $extension, $mime );
955 
956  if ( $match === null ) {
957  if ( $magic->getTypesForExtension( $extension ) !== null ) {
958  wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension\n" );
959  return false;
960  } else {
961  wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
962  return true;
963  }
964  } elseif ( $match === true ) {
965  wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
966 
967  #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
968  return true;
969 
970  } else {
971  wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
972  return false;
973  }
974  }
975 
987  public static function detectScript( $file, $mime, $extension ) {
988  global $wgAllowTitlesInSVG;
989  wfProfileIn( __METHOD__ );
990 
991  # ugly hack: for text files, always look at the entire file.
992  # For binary field, just check the first K.
993 
994  if ( strpos( $mime, 'text/' ) === 0 ) {
995  $chunk = file_get_contents( $file );
996  } else {
997  $fp = fopen( $file, 'rb' );
998  $chunk = fread( $fp, 1024 );
999  fclose( $fp );
1000  }
1001 
1002  $chunk = strtolower( $chunk );
1003 
1004  if ( !$chunk ) {
1005  wfProfileOut( __METHOD__ );
1006  return false;
1007  }
1008 
1009  # decode from UTF-16 if needed (could be used for obfuscation).
1010  if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1011  $enc = 'UTF-16BE';
1012  } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1013  $enc = 'UTF-16LE';
1014  } else {
1015  $enc = null;
1016  }
1017 
1018  if ( $enc ) {
1019  $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1020  }
1021 
1022  $chunk = trim( $chunk );
1023 
1024  # @todo FIXME: Convert from UTF-16 if necessary!
1025  wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
1026 
1027  # check for HTML doctype
1028  if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1029  wfProfileOut( __METHOD__ );
1030  return true;
1031  }
1032 
1033  // Some browsers will interpret obscure xml encodings as UTF-8, while
1034  // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1035  if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
1036  if ( self::checkXMLEncodingMissmatch( $file ) ) {
1037  wfProfileOut( __METHOD__ );
1038  return true;
1039  }
1040  }
1041 
1057  $tags = array(
1058  '<a href',
1059  '<body',
1060  '<head',
1061  '<html', #also in safari
1062  '<img',
1063  '<pre',
1064  '<script', #also in safari
1065  '<table'
1066  );
1067 
1068  if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1069  $tags[] = '<title';
1070  }
1071 
1072  foreach ( $tags as $tag ) {
1073  if ( false !== strpos( $chunk, $tag ) ) {
1074  wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
1075  wfProfileOut( __METHOD__ );
1076  return true;
1077  }
1078  }
1079 
1080  /*
1081  * look for JavaScript
1082  */
1083 
1084  # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1085  $chunk = Sanitizer::decodeCharReferences( $chunk );
1086 
1087  # look for script-types
1088  if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1089  wfDebug( __METHOD__ . ": found script types\n" );
1090  wfProfileOut( __METHOD__ );
1091  return true;
1092  }
1093 
1094  # look for html-style script-urls
1095  if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1096  wfDebug( __METHOD__ . ": found html-style script urls\n" );
1097  wfProfileOut( __METHOD__ );
1098  return true;
1099  }
1100 
1101  # look for css-style script-urls
1102  if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1103  wfDebug( __METHOD__ . ": found css-style script urls\n" );
1104  wfProfileOut( __METHOD__ );
1105  return true;
1106  }
1107 
1108  wfDebug( __METHOD__ . ": no scripts found\n" );
1109  wfProfileOut( __METHOD__ );
1110  return false;
1111  }
1112 
1120  public static function checkXMLEncodingMissmatch( $file ) {
1121  global $wgSVGMetadataCutoff;
1122  $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1123  $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1124 
1125  if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1126  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1127  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1128  ) {
1129  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1130  return true;
1131  }
1132  } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1133  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1134  // bytes. There shouldn't be a legitimate reason for this to happen.
1135  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1136  return true;
1137  } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1138  // EBCDIC encoded XML
1139  wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" );
1140  return true;
1141  }
1142 
1143  // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1144  // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1145  $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1146  foreach ( $attemptEncodings as $encoding ) {
1148  $str = iconv( $encoding, 'UTF-8', $contents );
1150  if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1151  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1152  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1153  ) {
1154  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1155  return true;
1156  }
1157  } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1158  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1159  // bytes. There shouldn't be a legitimate reason for this to happen.
1160  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1161  return true;
1162  }
1163  }
1164 
1165  return false;
1166  }
1167 
1172  protected function detectScriptInSvg( $filename ) {
1173  $this->mSVGNSError = false;
1174  $check = new XmlTypeCheck(
1175  $filename,
1176  array( $this, 'checkSvgScriptCallback' ),
1177  true,
1178  array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1179  );
1180  if ( $check->wellFormed !== true ) {
1181  // Invalid xml (bug 58553)
1182  return array( 'uploadinvalidxml' );
1183  } elseif ( $check->filterMatch ) {
1184  if ( $this->mSVGNSError ) {
1185  return array( 'uploadscriptednamespace', $this->mSVGNSError );
1186  }
1187  return array( 'uploadscripted' );
1188  }
1189  return false;
1190  }
1191 
1198  public static function checkSvgPICallback( $target, $data ) {
1199  // Don't allow external stylesheets (bug 57550)
1200  if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1201  return true;
1202  }
1203  return false;
1204  }
1205 
1212  public function checkSvgScriptCallback( $element, $attribs ) {
1213  list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1214 
1215  static $validNamespaces = array(
1216  '',
1217  'adobe:ns:meta/',
1218  'http://creativecommons.org/ns#',
1219  'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1220  'http://ns.adobe.com/adobeillustrator/10.0/',
1221  'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1222  'http://ns.adobe.com/extensibility/1.0/',
1223  'http://ns.adobe.com/flows/1.0/',
1224  'http://ns.adobe.com/illustrator/1.0/',
1225  'http://ns.adobe.com/imagereplacement/1.0/',
1226  'http://ns.adobe.com/pdf/1.3/',
1227  'http://ns.adobe.com/photoshop/1.0/',
1228  'http://ns.adobe.com/saveforweb/1.0/',
1229  'http://ns.adobe.com/variables/1.0/',
1230  'http://ns.adobe.com/xap/1.0/',
1231  'http://ns.adobe.com/xap/1.0/g/',
1232  'http://ns.adobe.com/xap/1.0/g/img/',
1233  'http://ns.adobe.com/xap/1.0/mm/',
1234  'http://ns.adobe.com/xap/1.0/rights/',
1235  'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1236  'http://ns.adobe.com/xap/1.0/stype/font#',
1237  'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1238  'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1239  'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1240  'http://ns.adobe.com/xap/1.0/t/pg/',
1241  'http://purl.org/dc/elements/1.1/',
1242  'http://purl.org/dc/elements/1.1',
1243  'http://schemas.microsoft.com/visio/2003/svgextensions/',
1244  'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1245  'http://web.resource.org/cc/',
1246  'http://www.freesoftware.fsf.org/bkchem/cdml',
1247  'http://www.inkscape.org/namespaces/inkscape',
1248  'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1249  'http://www.w3.org/2000/svg',
1250  );
1251 
1252  if ( !in_array( $namespace, $validNamespaces ) ) {
1253  wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" );
1254  // @TODO return a status object to a closure in XmlTypeCheck, for MW1.21+
1255  $this->mSVGNSError = $namespace;
1256  return true;
1257  }
1258 
1259  /*
1260  * check for elements that can contain javascript
1261  */
1262  if ( $strippedElement == 'script' ) {
1263  wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1264  return true;
1265  }
1266 
1267  # e.g., <svg xmlns="http://www.w3.org/2000/svg"> <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1268  if ( $strippedElement == 'handler' ) {
1269  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1270  return true;
1271  }
1272 
1273  # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1274  if ( $strippedElement == 'stylesheet' ) {
1275  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1276  return true;
1277  }
1278 
1279  # Block iframes, in case they pass the namespace check
1280  if ( $strippedElement == 'iframe' ) {
1281  wfDebug( __METHOD__ . ": iframe in uploaded file.\n" );
1282  return true;
1283  }
1284 
1285  foreach ( $attribs as $attrib => $value ) {
1286  $stripped = $this->stripXmlNamespace( $attrib );
1287  $value = strtolower( $value );
1288 
1289  if ( substr( $stripped, 0, 2 ) == 'on' ) {
1290  wfDebug( __METHOD__ . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1291  return true;
1292  }
1293 
1294  # href with non-local target (don't allow http://, javascript:, etc)
1295  if ( $stripped == 'href'
1296  && strpos( $value, 'data:' ) !== 0
1297  && strpos( $value, '#' ) !== 0
1298  ) {
1299  if ( !( $strippedElement === 'a'
1300  && preg_match( '!^https?://!im', $value ) )
1301  ) {
1302  wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1303  . "'$attrib'='$value' in uploaded file.\n" );
1304 
1305  return true;
1306  }
1307  }
1308 
1309  # href with embedded svg as target
1310  if ( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1311  wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1312  return true;
1313  }
1314 
1315  # href with embedded (text/xml) svg as target
1316  if ( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1317  wfDebug( __METHOD__ . ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1318  return true;
1319  }
1320 
1321  # use set/animate to add event-handler attribute to parent
1322  if ( ( $strippedElement == 'set' || $strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
1323  wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1324  return true;
1325  }
1326 
1327  # use set to add href attribute to parent element
1328  if ( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
1329  wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" );
1330  return true;
1331  }
1332 
1333  # use set to add a remote / data / script target to an element
1334  if ( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1335  wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" );
1336  return true;
1337  }
1338 
1339  # use handler attribute with remote / data / script
1340  if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1341  wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1342  return true;
1343  }
1344 
1345  # use CSS styles to bring in remote code
1346  # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1347  if ( $stripped == 'style' && preg_match_all( '!((?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*["\']?\s*[^#]+.*?\))!sim', $value, $matches ) ) {
1348  foreach ( $matches[1] as $match ) {
1349  if ( !preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1350  wfDebug( __METHOD__ . ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
1351  return true;
1352  }
1353  }
1354  }
1355 
1356  # image filters can pull in url, which could be svg that executes scripts
1357  if ( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1358  wfDebug( __METHOD__ . ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1359  return true;
1360  }
1361 
1362  }
1363 
1364  return false; //No scripts detected
1365  }
1366 
1372  private static function splitXmlNamespace( $element ) {
1373  // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1374  $parts = explode( ':', strtolower( $element ) );
1375  $name = array_pop( $parts );
1376  $ns = implode( ':', $parts );
1377  return array( $ns, $name );
1378  }
1379 
1384  private function stripXmlNamespace( $name ) {
1385  // 'http://www.w3.org/2000/svg:script' -> 'script'
1386  $parts = explode( ':', strtolower( $name ) );
1387  return array_pop( $parts );
1388  }
1389 
1400  public static function detectVirus( $file ) {
1401  global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1402  wfProfileIn( __METHOD__ );
1403 
1404  if ( !$wgAntivirus ) {
1405  wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1406  wfProfileOut( __METHOD__ );
1407  return null;
1408  }
1409 
1410  if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1411  wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1412  $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1413  array( 'virus-badscanner', $wgAntivirus ) );
1414  wfProfileOut( __METHOD__ );
1415  return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1416  }
1417 
1418  # look up scanner configuration
1419  $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1420  $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1421  $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1422  $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1423 
1424  if ( strpos( $command, "%f" ) === false ) {
1425  # simple pattern: append file to scan
1426  $command .= " " . wfEscapeShellArg( $file );
1427  } else {
1428  # complex pattern: replace "%f" with file to scan
1429  $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1430  }
1431 
1432  wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1433 
1434  # execute virus scanner
1435  $exitCode = false;
1436 
1437  # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1438  # that does not seem to be worth the pain.
1439  # Ask me (Duesentrieb) about it if it's ever needed.
1440  $output = wfShellExecWithStderr( $command, $exitCode );
1441 
1442  # map exit code to AV_xxx constants.
1443  $mappedCode = $exitCode;
1444  if ( $exitCodeMap ) {
1445  if ( isset( $exitCodeMap[$exitCode] ) ) {
1446  $mappedCode = $exitCodeMap[$exitCode];
1447  } elseif ( isset( $exitCodeMap["*"] ) ) {
1448  $mappedCode = $exitCodeMap["*"];
1449  }
1450  }
1451 
1452  /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1453  * so we need the strict equalities === and thus can't use a switch here
1454  */
1455  if ( $mappedCode === AV_SCAN_FAILED ) {
1456  # scan failed (code was mapped to false by $exitCodeMap)
1457  wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1458 
1459  $output = $wgAntivirusRequired ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text() : null;
1460  } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1461  # scan failed because filetype is unknown (probably imune)
1462  wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1463  $output = null;
1464  } elseif ( $mappedCode === AV_NO_VIRUS ) {
1465  # no virus found
1466  wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1467  $output = false;
1468  } else {
1469  $output = trim( $output );
1470 
1471  if ( !$output ) {
1472  $output = true; #if there's no output, return true
1473  } elseif ( $msgPattern ) {
1474  $groups = array();
1475  if ( preg_match( $msgPattern, $output, $groups ) ) {
1476  if ( $groups[1] ) {
1477  $output = $groups[1];
1478  }
1479  }
1480  }
1481 
1482  wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1483  }
1484 
1485  wfProfileOut( __METHOD__ );
1486  return $output;
1487  }
1488 
1497  private function checkOverwrite( $user ) {
1498  // First check whether the local file can be overwritten
1499  $file = $this->getLocalFile();
1500  if ( $file->exists() ) {
1501  if ( !self::userCanReUpload( $user, $file ) ) {
1502  return array( 'fileexists-forbidden', $file->getName() );
1503  } else {
1504  return true;
1505  }
1506  }
1507 
1508  /* Check shared conflicts: if the local file does not exist, but
1509  * wfFindFile finds a file, it exists in a shared repository.
1510  */
1511  $file = wfFindFile( $this->getTitle() );
1512  if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1513  return array( 'fileexists-shared-forbidden', $file->getName() );
1514  }
1515 
1516  return true;
1517  }
1518 
1526  public static function userCanReUpload( User $user, $img ) {
1527  if ( $user->isAllowed( 'reupload' ) ) {
1528  return true; // non-conditional
1529  }
1530  if ( !$user->isAllowed( 'reupload-own' ) ) {
1531  return false;
1532  }
1533  if ( is_string( $img ) ) {
1534  $img = wfLocalFile( $img );
1535  }
1536  if ( !( $img instanceof LocalFile ) ) {
1537  return false;
1538  }
1539 
1540  return $user->getId() == $img->getUser( 'id' );
1541  }
1542 
1554  public static function getExistsWarning( $file ) {
1555  if ( $file->exists() ) {
1556  return array( 'warning' => 'exists', 'file' => $file );
1557  }
1558 
1559  if ( $file->getTitle()->getArticleID() ) {
1560  return array( 'warning' => 'page-exists', 'file' => $file );
1561  }
1562 
1563  if ( $file->wasDeleted() && !$file->exists() ) {
1564  return array( 'warning' => 'was-deleted', 'file' => $file );
1565  }
1566 
1567  if ( strpos( $file->getName(), '.' ) == false ) {
1568  $partname = $file->getName();
1569  $extension = '';
1570  } else {
1571  $n = strrpos( $file->getName(), '.' );
1572  $extension = substr( $file->getName(), $n + 1 );
1573  $partname = substr( $file->getName(), 0, $n );
1574  }
1575  $normalizedExtension = File::normalizeExtension( $extension );
1576 
1577  if ( $normalizedExtension != $extension ) {
1578  // We're not using the normalized form of the extension.
1579  // Normal form is lowercase, using most common of alternate
1580  // extensions (eg 'jpg' rather than 'JPEG').
1581  //
1582  // Check for another file using the normalized form...
1583  $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1584  $file_lc = wfLocalFile( $nt_lc );
1585 
1586  if ( $file_lc->exists() ) {
1587  return array(
1588  'warning' => 'exists-normalized',
1589  'file' => $file,
1590  'normalizedFile' => $file_lc
1591  );
1592  }
1593  }
1594 
1595  // Check for files with the same name but a different extension
1596  $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix(
1597  "{$partname}.", 1 );
1598  if ( count( $similarFiles ) ) {
1599  return array(
1600  'warning' => 'exists-normalized',
1601  'file' => $file,
1602  'normalizedFile' => $similarFiles[0],
1603  );
1604  }
1605 
1606  if ( self::isThumbName( $file->getName() ) ) {
1607  # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1608  $nt_thb = Title::newFromText( substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension, NS_FILE );
1609  $file_thb = wfLocalFile( $nt_thb );
1610  if ( $file_thb->exists() ) {
1611  return array(
1612  'warning' => 'thumb',
1613  'file' => $file,
1614  'thumbFile' => $file_thb
1615  );
1616  } else {
1617  // File does not exist, but we just don't like the name
1618  return array(
1619  'warning' => 'thumb-name',
1620  'file' => $file,
1621  'thumbFile' => $file_thb
1622  );
1623  }
1624  }
1625 
1626  foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
1627  if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1628  return array(
1629  'warning' => 'bad-prefix',
1630  'file' => $file,
1631  'prefix' => $prefix
1632  );
1633  }
1634  }
1635 
1636  return false;
1637  }
1638 
1644  public static function isThumbName( $filename ) {
1645  $n = strrpos( $filename, '.' );
1646  $partname = $n ? substr( $filename, 0, $n ) : $filename;
1647  return (
1648  substr( $partname, 3, 3 ) == 'px-' ||
1649  substr( $partname, 2, 3 ) == 'px-'
1650  ) &&
1651  preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1652  }
1653 
1659  public static function getFilenamePrefixBlacklist() {
1660  $blacklist = array();
1661  $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1662  if ( !$message->isDisabled() ) {
1663  $lines = explode( "\n", $message->plain() );
1664  foreach ( $lines as $line ) {
1665  // Remove comment lines
1666  $comment = substr( trim( $line ), 0, 1 );
1667  if ( $comment == '#' || $comment == '' ) {
1668  continue;
1669  }
1670  // Remove additional comments after a prefix
1671  $comment = strpos( $line, '#' );
1672  if ( $comment > 0 ) {
1673  $line = substr( $line, 0, $comment - 1 );
1674  }
1675  $blacklist[] = trim( $line );
1676  }
1677  }
1678  return $blacklist;
1679  }
1680 
1691  public function getImageInfo( $result ) {
1692  $file = $this->getLocalFile();
1693  // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1694  // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1695  if ( $file instanceof UploadStashFile ) {
1697  $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1698  } else {
1700  $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1701  }
1702  return $info;
1703  }
1704 
1709  public function convertVerifyErrorToStatus( $error ) {
1710  $code = $error['status'];
1711  unset( $code['status'] );
1712  return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1713  }
1714 
1719  public static function getMaxUploadSize( $forType = null ) {
1720  global $wgMaxUploadSize;
1721 
1722  if ( is_array( $wgMaxUploadSize ) ) {
1723  if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1724  return $wgMaxUploadSize[$forType];
1725  } else {
1726  return $wgMaxUploadSize['*'];
1727  }
1728  } else {
1729  return intval( $wgMaxUploadSize );
1730  }
1731  }
1732 
1739  public static function getSessionStatus( $statusKey ) {
1740  return isset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] )
1741  ? $_SESSION[self::SESSION_STATUS_KEY][$statusKey]
1742  : false;
1743  }
1744 
1752  public static function setSessionStatus( $statusKey, $value ) {
1753  if ( $value === false ) {
1754  unset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] );
1755  } else {
1756  $_SESSION[self::SESSION_STATUS_KEY][$statusKey] = $value;
1757  }
1758  }
1759 }
UploadBase
Definition: UploadBase.php:38
UploadBase\checkSvgScriptCallback
checkSvgScriptCallback( $element, $attribs)
Definition: UploadBase.php:1212
AV_NO_VIRUS
const AV_NO_VIRUS
Definition: Defines.php:148
UploadBase\getRealPath
getRealPath( $srcPath)
Definition: UploadBase.php:253
Title\makeTitle
static & makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:398
UploadBase\verifyTitlePermissions
verifyTitlePermissions( $user)
Check whether the user can edit, upload and create the image.
Definition: UploadBase.php:561
$result
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. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag '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 '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. '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 '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 '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 User::isValidEmailAddr(), 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. '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 '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) '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. '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:1528
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:189
UploadBase\VERIFICATION_ERROR
const VERIFICATION_ERROR
Definition: UploadBase.php:57
UploadBase\stashSession
stashSession()
alias for stashFileGetKey, for backwards compatibility
Definition: UploadBase.php:874
of
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
RepoGroup\singleton
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:53
UploadBase\stashFile
stashFile(User $user=null)
If the user does not supply all necessary information in the first upload form submission (either by ...
Definition: UploadBase.php:848
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
$mime
usually copyright or history_copyright This message must be in HTML not wikitext $subpages will be ignored and the rest of subPageSubtitle() will run. 'SkinTemplateBuildNavUrlsNav_urlsAfterPermalink' whether MediaWiki currently thinks this is a CSS JS page Hooks may change this value to override the return value of Title::isCssOrJsPage(). 'TitleIsAlwaysKnown' whether MediaWiki currently thinks this page is known isMovable() always returns false. $title whether MediaWiki currently thinks this page is movable Hooks may change this value to override the return value of Title::isMovable(). 'TitleIsWikitextPage' whether MediaWiki currently thinks this is a wikitext page Hooks may change this value to override the return value of Title::isWikitextPage() 'TitleMove' use UploadVerification and UploadVerifyFile instead where the first element is the message key and the remaining elements are used as parameters to the message based on mime etc Preferred in most cases over UploadVerification object with all info about the upload string $mime
Definition: hooks.txt:2573
UploadBase\isThumbName
static isThumbName( $filename)
Helper function that checks whether the filename looks like a thumbnail.
Definition: UploadBase.php:1644
UploadBase\SESSION_STATUS_KEY
const SESSION_STATUS_KEY
Definition: UploadBase.php:66
UploadBase\getSourceType
getSourceType()
Returns the upload type.
Definition: UploadBase.php:190
UploadBase\checkWarnings
checkWarnings()
Check for non fatal problems with the file.
Definition: UploadBase.php:598
AV_SCAN_FAILED
const AV_SCAN_FAILED
Definition: Defines.php:151
UploadBase\FILE_TOO_LARGE
const FILE_TOO_LARGE
Definition: UploadBase.php:62
UploadBase\MIN_LENGTH_PARTNAME
const MIN_LENGTH_PARTNAME
Definition: UploadBase.php:52
UploadBase\verifyUpload
verifyUpload()
Verify whether the upload is sane.
Definition: UploadBase.php:275
UploadBase\$mJavaDetected
$mJavaDetected
Definition: UploadBase.php:45
$extensions
$extensions
Definition: importImages.php:62
FSFile\getPropsFromPath
static getPropsFromPath( $path, $ext=true)
Get an associative array containing information about a file in the local filesystem.
Definition: FSFile.php:243
UploadBase\isEnabled
static isEnabled()
Returns true if uploads are enabled.
Definition: UploadBase.php:98
UploadBase\checkFileExtensionList
static checkFileExtensionList( $ext, $list)
Perform case-insensitive match against a list of file extensions.
Definition: UploadBase.php:928
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all')
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1040
UploadBase\getTitle
getTitle()
Returns the title of the file to be uploaded.
Definition: UploadBase.php:713
wfProfileIn
wfProfileIn( $functionname)
Begin profiling of a function.
Definition: Profiler.php:33
$n
$n
Definition: RandomTest.php:76
wfSuppressWarnings
wfSuppressWarnings( $end=false)
Reference-counted warning suppression.
Definition: GlobalFunctions.php:2387
UploadBase\cleanupTempFile
cleanupTempFile()
If we've modified the upload file we need to manually remove it on exit to clean up.
Definition: UploadBase.php:882
UploadBase\initializeFromRequest
initializeFromRequest(&$request)
Initialize from a WebRequest.
UploadBase\getLocalFile
getLocalFile()
Return the local file and initializes if necessary.
Definition: UploadBase.php:828
wfArrayDiff2
if(!defined( 'MEDIAWIKI')) wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
Definition: GlobalFunctions.php:113
Status\newGood
static newGood( $value=null)
Factory function for good results.
Definition: Status.php:77
NS_FILE
const NS_FILE
Definition: Defines.php:85
UploadBase\$uploadHandlers
static $uploadHandlers
Definition: UploadBase.php:127
UploadStashFile
Definition: UploadStash.php:508
wfShellExecWithStderr
wfShellExecWithStderr( $cmd, &$retval=null, $environ=array(), $limits=array())
Execute a shell command, returning both stdout and stderr.
Definition: GlobalFunctions.php:3020
UploadBase\getFilenamePrefixBlacklist
static getFilenamePrefixBlacklist()
Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]].
Definition: UploadBase.php:1659
ApiQueryImageInfo\getPropertyNames
static getPropertyNames( $filter=array())
Returns all possible parameters to iiprop.
Definition: ApiQueryImageInfo.php:652
UploadBase\HOOK_ABORTED
const HOOK_ABORTED
Definition: UploadBase.php:61
UploadBase\OK
const OK
Definition: UploadBase.php:50
UploadBase\stripXmlNamespace
stripXmlNamespace( $name)
Definition: UploadBase.php:1384
UploadBase\validateName
validateName()
Verify that the name is valid and, if necessary, that we can overwrite.
Definition: UploadBase.php:339
ApiQueryImageInfo\getInfo
static getInfo( $file, $prop, $result, $thumbParams=null, $opts=false)
Get result information for an image revision.
Definition: ApiQueryImageInfo.php:330
UploadBase\isValidRequest
static isValidRequest( $request)
Check whether a request if valid for this handler.
Definition: UploadBase.php:178
UploadBase\getSessionStatus
static getSessionStatus( $statusKey)
Get the current status of a chunked upload (used for polling).
Definition: UploadBase.php:1739
UploadBase\$mFinalExtension
$mFinalExtension
Definition: UploadBase.php:42
UploadBase\EMPTY_FILE
const EMPTY_FILE
Definition: UploadBase.php:51
UploadBase\performUpload
performUpload( $comment, $pageText, $watch, $user)
Really perform the upload.
Definition: UploadBase.php:683
UploadBase\verifyPermissions
verifyPermissions( $user)
Alias for verifyTitlePermissions.
Definition: UploadBase.php:546
AV_SCAN_ABORTED
const AV_SCAN_ABORTED
Definition: Defines.php:150
UploadBase\$mFileSize
$mFileSize
Definition: UploadBase.php:43
UploadBase\$mSVGNSError
$mSVGNSError
Definition: UploadBase.php:45
file
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
UploadBase\$mLocalFile
$mLocalFile
Definition: UploadBase.php:43
MWException
MediaWiki exception.
Definition: MWException.php:26
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with - Additional characters can be defined in $wgIllegalFileChars (se...
Definition: GlobalFunctions.php:3844
wfRestoreWarnings
wfRestoreWarnings()
Restore error level to previous value.
Definition: GlobalFunctions.php:2417
UploadBase\verifyExtension
static verifyExtension( $mime, $extension)
Checks if the mime type of the uploaded file matches the file extension.
Definition: UploadBase.php:939
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1330
UploadBase\$mBlackListedExtensions
$mBlackListedExtensions
Definition: UploadBase.php:44
UploadBase\WINDOWS_NONASCII_FILENAME
const WINDOWS_NONASCII_FILENAME
Definition: UploadBase.php:63
UploadBase\verifyMimeType
verifyMimeType( $mime)
Verify the mime type.
Definition: UploadBase.php:367
there
has been added to your &Future changes to this page and its associated Talk page will be listed there
Definition: All_system_messages.txt:357
UploadBase\verifyFile
verifyFile()
Verifies that it's ok to include the uploaded file.
Definition: UploadBase.php:403
UploadBase\$mRemoveTempFile
$mRemoveTempFile
Definition: UploadBase.php:40
WatchedItem\IGNORE_USER_RIGHTS
const IGNORE_USER_RIGHTS
Constant to specify that user rights 'editmywatchlist' and 'viewmywatchlist' should not be checked.
Definition: WatchedItem.php:35
FSFile\getSha1Base36FromPath
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
Definition: FSFile.php:259
UploadBase\getVerificationErrorCode
getVerificationErrorCode( $error)
Definition: UploadBase.php:72
UploadBase\getImageInfo
getImageInfo( $result)
Gets image info about the file just uploaded.
Definition: UploadBase.php:1691
wfProfileOut
wfProfileOut( $functionname='missing')
Stop profiling of a function.
Definition: Profiler.php:46
$wgOut
$wgOut
Definition: Setup.php:562
wfMessage
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 unset offset - wrap String Wrap the message in html(usually something like "&lt
wfRunHooks
wfRunHooks( $event, array $args=array(), $deprecatedVersion=null)
Call hook functions defined in $wgHooks.
Definition: GlobalFunctions.php:4001
UploadBase\zipEntryCallback
zipEntryCallback( $entry)
Callback for ZipDirectoryReader to detect Java class files.
Definition: UploadBase.php:519
UploadBase\$mFilteredName
$mFilteredName
Definition: UploadBase.php:42
$lines
$lines
Definition: router.php:65
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
UploadBase\detectVirus
static detectVirus( $file)
Generic wrapper function for a virus scanner program.
Definition: UploadBase.php:1400
UploadBase\getTempPath
getTempPath()
Definition: UploadBase.php:889
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
form
null means default in associative array form
Definition: hooks.txt:1530
UploadBase\$safeXmlEncodings
static $safeXmlEncodings
Definition: UploadBase.php:47
$comment
$comment
Definition: importImages.php:107
$wgFileExtensions
if(! $wgHtml5Version && $wgAllowRdfaAttributes) $wgFileExtensions
Definition: Setup.php:362
list
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
UploadBase\SUCCESS
const SUCCESS
Definition: UploadBase.php:49
UploadBase\checkFileExtension
static checkFileExtension( $ext, $list)
Perform case-insensitive match against a list of file extensions.
Definition: UploadBase.php:916
UploadBase\$mTitleError
$mTitleError
Definition: UploadBase.php:41
UploadBase\$mTempPath
$mTempPath
Definition: UploadBase.php:39
$command
$command
Definition: cdb.php:63
$line
$line
Definition: cdb.php:57
wfDebug
wfDebug( $text, $dest='all')
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:933
UploadBase\detectScript
static detectScript( $file, $mime, $extension)
Heuristic for detecting files that could contain JavaScript instructions or things that may look like...
Definition: UploadBase.php:987
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:422
$title
presenting them properly to the user as errors is done by the caller $title
Definition: hooks.txt:1324
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:336
$matches
if(!defined( 'MEDIAWIKI')) if(!isset( $wgVersion)) $matches
Definition: NoLocalSettings.php:33
UploadBase\splitXmlNamespace
static splitXmlNamespace( $element)
Divide the element name passed by the xml parser to the callback into URI and prifix.
Definition: UploadBase.php:1372
UploadBase\__construct
__construct()
Definition: UploadBase.php:182
$value
$value
Definition: styleTest.css.php:45
UploadBase\isEmptyFile
isEmptyFile()
Return true if the file is empty.
Definition: UploadBase.php:229
ArchivedFile
Class representing a row of the 'filearchive' table.
Definition: ArchivedFile.php:29
UploadBase\isAllowed
static isAllowed( $user)
Returns true if the user can use this upload module or else a string identifying the missing permissi...
Definition: UploadBase.php:117
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:2524
wfEscapeShellArg
wfEscapeShellArg()
Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell,...
Definition: GlobalFunctions.php:2705
UploadBase\checkOverwrite
checkOverwrite( $user)
Check if there's an overwrite conflict and, if so, if restrictions forbid this user from performing t...
Definition: UploadBase.php:1497
UploadBase\UPLOAD_VERIFICATION_ERROR
const UPLOAD_VERIFICATION_ERROR
Definition: UploadBase.php:60
UploadBase\getExistsWarning
static getExistsWarning( $file)
Helper function that does various existence checks for a file.
Definition: UploadBase.php:1554
XmlTypeCheck
Definition: XmlTypeCheck.php:23
UploadBase\FILENAME_TOO_LONG
const FILENAME_TOO_LONG
Definition: UploadBase.php:64
UploadBase\$mSourceType
$mSourceType
Definition: UploadBase.php:40
UploadBase\verifyPartialFile
verifyPartialFile()
A verification routine suitable for partial files.
Definition: UploadBase.php:453
$user
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 account $user
Definition: hooks.txt:237
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:2685
File\DELETE_SOURCE
const DELETE_SOURCE
Definition: File.php:65
UploadBase\OVERWRITE_EXISTING_FILE
const OVERWRITE_EXISTING_FILE
Definition: UploadBase.php:54
UploadBase\ILLEGAL_FILENAME
const ILLEGAL_FILENAME
Definition: UploadBase.php:53
$hash
return false to override stock group addition can be modified try getUserPermissionsErrors userCan checks are continued by internal code can override on output return false to not delete it return false to override the default password checks & $hash
Definition: hooks.txt:2697
UploadBase\getMaxUploadSize
static getMaxUploadSize( $forType=null)
Definition: UploadBase.php:1719
$file
if(PHP_SAPI !='cli') $file
Definition: UtfNormalTest2.php:30
UploadBase\createFromRequest
static createFromRequest(&$request, $type=null)
Create a form of UploadBase depending on wpSourceType and initializes it.
Definition: UploadBase.php:136
UploadBase\setSessionStatus
static setSessionStatus( $statusKey, $value)
Set the current status of a chunked upload (used for polling).
Definition: UploadBase.php:1752
UploadBase\convertVerifyErrorToStatus
convertVerifyErrorToStatus( $error)
Definition: UploadBase.php:1709
UploadBase\initializePathInfo
initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile=false)
Initialize the path information.
Definition: UploadBase.php:202
$wgLang
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
UploadBase\splitExtensions
static splitExtensions( $filename)
Split a file into a base name and all dot-delimited 'extensions' on the end.
Definition: UploadBase.php:902
UploadBase\getTempFileSha1Base36
getTempFileSha1Base36()
Get the base 36 SHA1 of the file.
Definition: UploadBase.php:245
$ext
$ext
Definition: NoLocalSettings.php:34
in
Prior to maintenance scripts were a hodgepodge of code that had no cohesion or formal method of action Beginning in
Definition: maintenance.txt:1
UploadBase\$mDestName
$mDestName
Definition: UploadBase.php:40
Title\capitalize
static capitalize( $text, $ns=NS_MAIN)
Capitalize a text string for a title if it belongs to a namespace that capitalizes.
Definition: Title.php:3269
used
you don t have to do a grep find to see where the $wgReverseTitle variable is used
Definition: hooks.txt:117
UploadBase\$mTitle
$mTitle
Definition: UploadBase.php:41
$output
& $output
Definition: hooks.txt:375
UploadBase\detectScriptInSvg
detectScriptInSvg( $filename)
Definition: UploadBase.php:1172
UploadBase\checkSvgPICallback
static checkSvgPICallback( $target, $data)
Callback to filter SVG Processing Instructions.
Definition: UploadBase.php:1198
$path
$path
Definition: NoLocalSettings.php:35
MediaHandler\getHandler
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
Definition: MediaHandler.php:48
as
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
UploadBase\fetchFile
fetchFile()
Fetch the file.
Definition: UploadBase.php:221
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:52
UploadBase\stashFileGetKey
stashFileGetKey()
Stash a file in a temporary directory, returning a key which can be used to find the file again.
Definition: UploadBase.php:865
UploadBase\$mDesiredDestName
$mDesiredDestName
Definition: UploadBase.php:40
Sanitizer\decodeCharReferences
static decodeCharReferences( $text)
Decode any character references, numeric or named entities, in the text and return a UTF-8 string.
Definition: Sanitizer.php:1396
$error
usually copyright or history_copyright This message must be in HTML not wikitext $subpages will be ignored and the rest of subPageSubtitle() will run. 'SkinTemplateBuildNavUrlsNav_urlsAfterPermalink' whether MediaWiki currently thinks this is a CSS JS page Hooks may change this value to override the return value of Title::isCssOrJsPage(). 'TitleIsAlwaysKnown' whether MediaWiki currently thinks this page is known isMovable() always returns false. $title whether MediaWiki currently thinks this page is movable Hooks may change this value to override the return value of Title::isMovable(). 'TitleIsWikitextPage' whether MediaWiki currently thinks this is a wikitext page Hooks may change this value to override the return value of Title::isWikitextPage() 'TitleMove' use UploadVerification and UploadVerifyFile instead where the first element is the message key and the remaining elements are used as parameters to the message based on mime etc Preferred in most cases over UploadVerification object with all info about the upload string as detected by MediaWiki Handlers will typically only apply for specific mime types object & $error
Definition: hooks.txt:2573
WatchAction\doWatch
static doWatch(Title $title, User $user, $checkRights=WatchedItem::CHECK_USER_RIGHTS)
Watch a page.
Definition: WatchAction.php:130
wfIsHHVM
wfIsHHVM()
Check if we are running under HHVM.
Definition: GlobalFunctions.php:2537
$attribs
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:1530
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:59
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:3704
UploadBase\$mFileProps
$mFileProps
Definition: UploadBase.php:43
ZipDirectoryReader\read
static read( $fileName, $callback, $options=array())
Read a ZIP file and call a function for each file discovered in it.
Definition: ZipDirectoryReader.php:89
UploadBase\getFileSize
getFileSize()
Return the file size.
Definition: UploadBase.php:237
Status\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: Status.php:63
page
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 my talk page
Definition: hooks.txt:1956
UploadBase\checkXMLEncodingMissmatch
static checkXMLEncodingMissmatch( $file)
Check a whitelist of xml encodings that are known not to be interpreted differently by the server's x...
Definition: UploadBase.php:1120
UploadBase\FILETYPE_MISSING
const FILETYPE_MISSING
Definition: UploadBase.php:55
$type
$type
Definition: testCompression.php:46
UploadBase\FILETYPE_BADTYPE
const FILETYPE_BADTYPE
Definition: UploadBase.php:56