MediaWiki  1.23.16
UploadBase.php
Go to the documentation of this file.
1 <?php
38 abstract class UploadBase {
39  protected $mTempPath;
40  protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
41  protected $mTitle = false, $mTitleError = 0;
42  protected $mFilteredName, $mFinalExtension;
43  protected $mLocalFile, $mFileSize, $mFileProps;
44  protected $mBlackListedExtensions;
45  protected $mJavaDetected, $mSVGNSError;
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;
52  const MIN_LENGTH_PARTNAME = 4;
53  const ILLEGAL_FILENAME = 5;
54  const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
55  const FILETYPE_MISSING = 8;
56  const FILETYPE_BADTYPE = 9;
57  const VERIFICATION_ERROR = 10;
58 
59  # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
60  const UPLOAD_VERIFICATION_ERROR = 11;
61  const HOOK_ABORTED = 11;
62  const FILE_TOO_LARGE = 12;
63  const WINDOWS_NONASCII_FILENAME = 13;
64  const FILENAME_TOO_LONG = 14;
65 
66  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 
132  public static function isThrottled( $user ) {
133  return $user->pingLimiter( 'upload' );
134  }
135 
136  // Upload handlers. Should probably just be a global.
137  static $uploadHandlers = array( 'Stash', 'File', 'Url' );
138 
146  public static function createFromRequest( &$request, $type = null ) {
147  $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
148 
149  if ( !$type ) {
150  return null;
151  }
152 
153  // Get the upload class
154  $type = ucfirst( $type );
155 
156  // Give hooks the chance to handle this request
157  $className = null;
158  wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
159  if ( is_null( $className ) ) {
160  $className = 'UploadFrom' . $type;
161  wfDebug( __METHOD__ . ": class name: $className\n" );
162  if ( !in_array( $type, self::$uploadHandlers ) ) {
163  return null;
164  }
165  }
166 
167  // Check whether this upload class is enabled
168  if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
169  return null;
170  }
171 
172  // Check whether the request is valid
173  if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
174  return null;
175  }
176 
177  $handler = new $className;
178 
179  $handler->initializeFromRequest( $request );
180  return $handler;
181  }
182 
188  public static function isValidRequest( $request ) {
189  return false;
190  }
191 
192  public function __construct() {}
193 
200  public function getSourceType() {
201  return null;
202  }
203 
212  public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
213  $this->mDesiredDestName = $name;
214  if ( FileBackend::isStoragePath( $tempPath ) ) {
215  throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
216  }
217  $this->mTempPath = $tempPath;
218  $this->mFileSize = $fileSize;
219  $this->mRemoveTempFile = $removeTempFile;
220  }
221 
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  wfProfileIn( __METHOD__ );
265  $repo = RepoGroup::singleton()->getLocalRepo();
266  if ( $repo->isVirtualUrl( $srcPath ) ) {
267  // @todo just make uploads work with storage paths
268  // UploadFromStash loads files via virtual URLs
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  wfProfileOut( __METHOD__ );
278  return $path;
279  }
280 
285  public function verifyUpload() {
286  wfProfileIn( __METHOD__ );
287 
291  if ( $this->isEmptyFile() ) {
292  wfProfileOut( __METHOD__ );
293  return array( 'status' => self::EMPTY_FILE );
294  }
295 
299  $maxSize = self::getMaxUploadSize( $this->getSourceType() );
300  if ( $this->mFileSize > $maxSize ) {
301  wfProfileOut( __METHOD__ );
302  return array(
303  'status' => self::FILE_TOO_LARGE,
304  'max' => $maxSize,
305  );
306  }
307 
313  $verification = $this->verifyFile();
314  if ( $verification !== true ) {
315  wfProfileOut( __METHOD__ );
316  return array(
317  'status' => self::VERIFICATION_ERROR,
318  'details' => $verification
319  );
320  }
321 
325  $result = $this->validateName();
326  if ( $result !== true ) {
327  wfProfileOut( __METHOD__ );
328  return $result;
329  }
330 
331  $error = '';
332  if ( !wfRunHooks( 'UploadVerification',
333  array( $this->mDestName, $this->mTempPath, &$error ) )
334  ) {
335  wfProfileOut( __METHOD__ );
336  return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
337  }
338 
339  wfProfileOut( __METHOD__ );
340  return array( 'status' => self::OK );
341  }
342 
349  public function validateName() {
350  $nt = $this->getTitle();
351  if ( is_null( $nt ) ) {
352  $result = array( 'status' => $this->mTitleError );
353  if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
354  $result['filtered'] = $this->mFilteredName;
355  }
356  if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
357  $result['finalExt'] = $this->mFinalExtension;
358  if ( count( $this->mBlackListedExtensions ) ) {
359  $result['blacklistedExt'] = $this->mBlackListedExtensions;
360  }
361  }
362  return $result;
363  }
364  $this->mDestName = $this->getLocalFile()->getName();
365 
366  return true;
367  }
368 
377  protected function verifyMimeType( $mime ) {
378  global $wgVerifyMimeType;
379  wfProfileIn( __METHOD__ );
380  if ( $wgVerifyMimeType ) {
381  wfDebug( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" );
382  global $wgMimeTypeBlacklist;
383  if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
384  wfProfileOut( __METHOD__ );
385  return array( 'filetype-badmime', $mime );
386  }
387 
388  # Check IE type
389  $fp = fopen( $this->mTempPath, 'rb' );
390  $chunk = fread( $fp, 256 );
391  fclose( $fp );
392 
393  $magic = MimeMagic::singleton();
394  $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
395  $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
396  foreach ( $ieTypes as $ieType ) {
397  if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
398  wfProfileOut( __METHOD__ );
399  return array( 'filetype-bad-ie-mime', $ieType );
400  }
401  }
402  }
403 
404  wfProfileOut( __METHOD__ );
405  return true;
406  }
407 
413  protected function verifyFile() {
414  global $wgVerifyMimeType;
415  wfProfileIn( __METHOD__ );
416 
417  $status = $this->verifyPartialFile();
418  if ( $status !== true ) {
419  wfProfileOut( __METHOD__ );
420  return $status;
421  }
422 
423  $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
424  $mime = $this->mFileProps['file-mime'];
425 
426  if ( $wgVerifyMimeType ) {
427  # XXX: Missing extension will be caught by validateName() via getTitle()
428  if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
429  wfProfileOut( __METHOD__ );
430  return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
431  }
432  }
433 
434  $handler = MediaHandler::getHandler( $mime );
435  if ( $handler ) {
436  $handlerStatus = $handler->verifyUpload( $this->mTempPath );
437  if ( !$handlerStatus->isOK() ) {
438  $errors = $handlerStatus->getErrorsArray();
439  wfProfileOut( __METHOD__ );
440  return reset( $errors );
441  }
442  }
443 
444  wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
445  if ( $status !== true ) {
446  wfProfileOut( __METHOD__ );
447  return $status;
448  }
449 
450  wfDebug( __METHOD__ . ": all clear; passing.\n" );
451  wfProfileOut( __METHOD__ );
452  return true;
453  }
454 
463  protected function verifyPartialFile() {
464  global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
465  wfProfileIn( __METHOD__ );
466 
467  # getTitle() sets some internal parameters like $this->mFinalExtension
468  $this->getTitle();
469 
470  $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
471 
472  # check mime type, if desired
473  $mime = $this->mFileProps['file-mime'];
474  $status = $this->verifyMimeType( $mime );
475  if ( $status !== true ) {
476  wfProfileOut( __METHOD__ );
477  return $status;
478  }
479 
480  # check for htmlish code and javascript
481  if ( !$wgDisableUploadScriptChecks ) {
482  if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
483  wfProfileOut( __METHOD__ );
484  return array( 'uploadscripted' );
485  }
486  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
487  $svgStatus = $this->detectScriptInSvg( $this->mTempPath );
488  if ( $svgStatus !== false ) {
489  wfProfileOut( __METHOD__ );
490  return $svgStatus;
491  }
492  }
493  }
494 
495  # Check for Java applets, which if uploaded can bypass cross-site
496  # restrictions.
497  if ( !$wgAllowJavaUploads ) {
498  $this->mJavaDetected = false;
499  $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
500  array( $this, 'zipEntryCallback' ) );
501  if ( !$zipStatus->isOK() ) {
502  $errors = $zipStatus->getErrorsArray();
503  $error = reset( $errors );
504  if ( $error[0] !== 'zip-wrong-format' ) {
505  wfProfileOut( __METHOD__ );
506  return $error;
507  }
508  }
509  if ( $this->mJavaDetected ) {
510  wfProfileOut( __METHOD__ );
511  return array( 'uploadjava' );
512  }
513  }
514 
515  # Scan the uploaded file for viruses
516  $virus = $this->detectVirus( $this->mTempPath );
517  if ( $virus ) {
518  wfProfileOut( __METHOD__ );
519  return array( 'uploadvirus', $virus );
520  }
521 
522  wfProfileOut( __METHOD__ );
523  return true;
524  }
525 
529  function zipEntryCallback( $entry ) {
530  $names = array( $entry['name'] );
531 
532  // If there is a null character, cut off the name at it, because JDK's
533  // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
534  // were constructed which had ".class\0" followed by a string chosen to
535  // make the hash collide with the truncated name, that file could be
536  // returned in response to a request for the .class file.
537  $nullPos = strpos( $entry['name'], "\000" );
538  if ( $nullPos !== false ) {
539  $names[] = substr( $entry['name'], 0, $nullPos );
540  }
541 
542  // If there is a trailing slash in the file name, we have to strip it,
543  // because that's what ZIP_GetEntry() does.
544  if ( preg_grep( '!\.class/?$!', $names ) ) {
545  $this->mJavaDetected = true;
546  }
547  }
548 
556  public function verifyPermissions( $user ) {
557  return $this->verifyTitlePermissions( $user );
558  }
559 
571  public function verifyTitlePermissions( $user ) {
576  $nt = $this->getTitle();
577  if ( is_null( $nt ) ) {
578  return true;
579  }
580  $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
581  $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
582  if ( !$nt->exists() ) {
583  $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
584  } else {
585  $permErrorsCreate = array();
586  }
587  if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
588  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
589  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
590  return $permErrors;
591  }
592 
593  $overwriteError = $this->checkOverwrite( $user );
594  if ( $overwriteError !== true ) {
595  return array( $overwriteError );
596  }
597 
598  return true;
599  }
600 
608  public function checkWarnings() {
609  global $wgLang;
610  wfProfileIn( __METHOD__ );
611 
612  $warnings = array();
613 
614  $localFile = $this->getLocalFile();
615  $filename = $localFile->getName();
616 
621  $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
622  $comparableName = Title::capitalize( $comparableName, NS_FILE );
623 
624  if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
625  $warnings['badfilename'] = $filename;
626  // Debugging for bug 62241
627  wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: '$this->mDesiredDestName', comparableName: '$comparableName'" );
628  }
629 
630  // Check whether the file extension is on the unwanted list
631  global $wgCheckFileExtensions, $wgFileExtensions;
632  if ( $wgCheckFileExtensions ) {
633  $extensions = array_unique( $wgFileExtensions );
634  if ( !$this->checkFileExtension( $this->mFinalExtension, $extensions ) ) {
635  $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension,
636  $wgLang->commaList( $extensions ), count( $extensions ) );
637  }
638  }
639 
640  global $wgUploadSizeWarning;
641  if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
642  $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize );
643  }
644 
645  if ( $this->mFileSize == 0 ) {
646  $warnings['emptyfile'] = true;
647  }
648 
649  $exists = self::getExistsWarning( $localFile );
650  if ( $exists !== false ) {
651  $warnings['exists'] = $exists;
652  }
653 
654  // Check dupes against existing files
655  $hash = $this->getTempFileSha1Base36();
656  $dupes = RepoGroup::singleton()->findBySha1( $hash );
657  $title = $this->getTitle();
658  // Remove all matches against self
659  foreach ( $dupes as $key => $dupe ) {
660  if ( $title->equals( $dupe->getTitle() ) ) {
661  unset( $dupes[$key] );
662  }
663  }
664  if ( $dupes ) {
665  $warnings['duplicate'] = $dupes;
666  }
667 
668  // Check dupes against archives
669  $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
670  if ( $archivedImage->getID() > 0 ) {
671  if ( $archivedImage->userCan( File::DELETED_FILE ) ) {
672  $warnings['duplicate-archive'] = $archivedImage->getName();
673  } else {
674  $warnings['duplicate-archive'] = '';
675  }
676  }
677 
678  wfProfileOut( __METHOD__ );
679  return $warnings;
680  }
681 
693  public function performUpload( $comment, $pageText, $watch, $user ) {
694  wfProfileIn( __METHOD__ );
695 
696  $status = $this->getLocalFile()->upload(
697  $this->mTempPath,
698  $comment,
699  $pageText,
701  $this->mFileProps,
702  false,
703  $user
704  );
705 
706  if ( $status->isGood() ) {
707  if ( $watch ) {
708  WatchAction::doWatch( $this->getLocalFile()->getTitle(), $user, WatchedItem::IGNORE_USER_RIGHTS );
709  }
710  wfRunHooks( 'UploadComplete', array( &$this ) );
711  }
712 
713  wfProfileOut( __METHOD__ );
714  return $status;
715  }
716 
723  public function getTitle() {
724  if ( $this->mTitle !== false ) {
725  return $this->mTitle;
726  }
727  /* Assume that if a user specified File:Something.jpg, this is an error
728  * and that the namespace prefix needs to be stripped of.
729  */
730  $title = Title::newFromText( $this->mDesiredDestName );
731  if ( $title && $title->getNamespace() == NS_FILE ) {
732  $this->mFilteredName = $title->getDBkey();
733  } else {
734  $this->mFilteredName = $this->mDesiredDestName;
735  }
736 
737  # oi_archive_name is max 255 bytes, which include a timestamp and an
738  # exclamation mark, so restrict file name to 240 bytes.
739  if ( strlen( $this->mFilteredName ) > 240 ) {
740  $this->mTitleError = self::FILENAME_TOO_LONG;
741  $this->mTitle = null;
742  return $this->mTitle;
743  }
744 
750  $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
751  /* Normalize to title form before we do any further processing */
752  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
753  if ( is_null( $nt ) ) {
754  $this->mTitleError = self::ILLEGAL_FILENAME;
755  $this->mTitle = null;
756  return $this->mTitle;
757  }
758  $this->mFilteredName = $nt->getDBkey();
759 
764  list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
765 
766  if ( count( $ext ) ) {
767  $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
768  } else {
769  $this->mFinalExtension = '';
770 
771  # No extension, try guessing one
772  $magic = MimeMagic::singleton();
773  $mime = $magic->guessMimeType( $this->mTempPath );
774  if ( $mime !== 'unknown/unknown' ) {
775  # Get a space separated list of extensions
776  $extList = $magic->getExtensionsForType( $mime );
777  if ( $extList ) {
778  # Set the extension to the canonical extension
779  $this->mFinalExtension = strtok( $extList, ' ' );
780 
781  # Fix up the other variables
782  $this->mFilteredName .= ".{$this->mFinalExtension}";
783  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
784  $ext = array( $this->mFinalExtension );
785  }
786  }
787  }
788 
789  /* Don't allow users to override the blacklist (check file extension) */
790  global $wgCheckFileExtensions, $wgStrictFileExtensions;
791  global $wgFileExtensions, $wgFileBlacklist;
792 
793  $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
794 
795  if ( $this->mFinalExtension == '' ) {
796  $this->mTitleError = self::FILETYPE_MISSING;
797  $this->mTitle = null;
798  return $this->mTitle;
799  } elseif ( $blackListedExtensions ||
800  ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
801  !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
802  $this->mBlackListedExtensions = $blackListedExtensions;
803  $this->mTitleError = self::FILETYPE_BADTYPE;
804  $this->mTitle = null;
805  return $this->mTitle;
806  }
807 
808  // Windows may be broken with special characters, see bug XXX
809  if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
810  $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
811  $this->mTitle = null;
812  return $this->mTitle;
813  }
814 
815  # If there was more than one "extension", reassemble the base
816  # filename to prevent bogus complaints about length
817  if ( count( $ext ) > 1 ) {
818  for ( $i = 0; $i < count( $ext ) - 1; $i++ ) {
819  $partname .= '.' . $ext[$i];
820  }
821  }
822 
823  if ( strlen( $partname ) < 1 ) {
824  $this->mTitleError = self::MIN_LENGTH_PARTNAME;
825  $this->mTitle = null;
826  return $this->mTitle;
827  }
828 
829  $this->mTitle = $nt;
830  return $this->mTitle;
831  }
832 
838  public function getLocalFile() {
839  if ( is_null( $this->mLocalFile ) ) {
840  $nt = $this->getTitle();
841  $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
842  }
843  return $this->mLocalFile;
844  }
845 
858  public function stashFile( User $user = null ) {
859  // was stashSessionFile
860  wfProfileIn( __METHOD__ );
861 
862  $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user );
863  $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
864  $this->mLocalFile = $file;
865 
866  wfProfileOut( __METHOD__ );
867  return $file;
868  }
869 
875  public function stashFileGetKey() {
876  return $this->stashFile()->getFileKey();
877  }
878 
884  public function stashSession() {
885  return $this->stashFileGetKey();
886  }
887 
892  public function cleanupTempFile() {
893  if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
894  wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
895  unlink( $this->mTempPath );
896  }
897  }
898 
899  public function getTempPath() {
900  return $this->mTempPath;
901  }
902 
912  public static function splitExtensions( $filename ) {
913  $bits = explode( '.', $filename );
914  $basename = array_shift( $bits );
915  return array( $basename, $bits );
916  }
917 
926  public static function checkFileExtension( $ext, $list ) {
927  return in_array( strtolower( $ext ), $list );
928  }
929 
938  public static function checkFileExtensionList( $ext, $list ) {
939  return array_intersect( array_map( 'strtolower', $ext ), $list );
940  }
941 
949  public static function verifyExtension( $mime, $extension ) {
950  $magic = MimeMagic::singleton();
951 
952  if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) {
953  if ( !$magic->isRecognizableExtension( $extension ) ) {
954  wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
955  "unrecognized extension '$extension', can't verify\n" );
956  return true;
957  } else {
958  wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
959  "recognized extension '$extension', so probably invalid file\n" );
960  return false;
961  }
962  }
963 
964  $match = $magic->isMatchingExtension( $extension, $mime );
965 
966  if ( $match === null ) {
967  if ( $magic->getTypesForExtension( $extension ) !== null ) {
968  wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension\n" );
969  return false;
970  } else {
971  wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
972  return true;
973  }
974  } elseif ( $match === true ) {
975  wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
976 
977  #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
978  return true;
979 
980  } else {
981  wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
982  return false;
983  }
984  }
985 
997  public static function detectScript( $file, $mime, $extension ) {
998  global $wgAllowTitlesInSVG;
999  wfProfileIn( __METHOD__ );
1000 
1001  # ugly hack: for text files, always look at the entire file.
1002  # For binary field, just check the first K.
1003 
1004  if ( strpos( $mime, 'text/' ) === 0 ) {
1005  $chunk = file_get_contents( $file );
1006  } else {
1007  $fp = fopen( $file, 'rb' );
1008  $chunk = fread( $fp, 1024 );
1009  fclose( $fp );
1010  }
1011 
1012  $chunk = strtolower( $chunk );
1013 
1014  if ( !$chunk ) {
1015  wfProfileOut( __METHOD__ );
1016  return false;
1017  }
1018 
1019  # decode from UTF-16 if needed (could be used for obfuscation).
1020  if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1021  $enc = 'UTF-16BE';
1022  } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1023  $enc = 'UTF-16LE';
1024  } else {
1025  $enc = null;
1026  }
1027 
1028  if ( $enc ) {
1029  $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1030  }
1031 
1032  $chunk = trim( $chunk );
1033 
1034  # @todo FIXME: Convert from UTF-16 if necessary!
1035  wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
1036 
1037  # check for HTML doctype
1038  if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1039  wfProfileOut( __METHOD__ );
1040  return true;
1041  }
1042 
1043  // Some browsers will interpret obscure xml encodings as UTF-8, while
1044  // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1045  if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
1046  if ( self::checkXMLEncodingMissmatch( $file ) ) {
1047  wfProfileOut( __METHOD__ );
1048  return true;
1049  }
1050  }
1051 
1067  $tags = array(
1068  '<a href',
1069  '<body',
1070  '<head',
1071  '<html', #also in safari
1072  '<img',
1073  '<pre',
1074  '<script', #also in safari
1075  '<table'
1076  );
1077 
1078  if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1079  $tags[] = '<title';
1080  }
1081 
1082  foreach ( $tags as $tag ) {
1083  if ( false !== strpos( $chunk, $tag ) ) {
1084  wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
1085  wfProfileOut( __METHOD__ );
1086  return true;
1087  }
1088  }
1089 
1090  /*
1091  * look for JavaScript
1092  */
1093 
1094  # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1095  $chunk = Sanitizer::decodeCharReferences( $chunk );
1096 
1097  # look for script-types
1098  if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1099  wfDebug( __METHOD__ . ": found script types\n" );
1100  wfProfileOut( __METHOD__ );
1101  return true;
1102  }
1103 
1104  # look for html-style script-urls
1105  if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1106  wfDebug( __METHOD__ . ": found html-style script urls\n" );
1107  wfProfileOut( __METHOD__ );
1108  return true;
1109  }
1110 
1111  # look for css-style script-urls
1112  if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1113  wfDebug( __METHOD__ . ": found css-style script urls\n" );
1114  wfProfileOut( __METHOD__ );
1115  return true;
1116  }
1117 
1118  wfDebug( __METHOD__ . ": no scripts found\n" );
1119  wfProfileOut( __METHOD__ );
1120  return false;
1121  }
1122 
1130  public static function checkXMLEncodingMissmatch( $file ) {
1131  global $wgSVGMetadataCutoff;
1132  $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1133  $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1134 
1135  if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1136  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1137  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1138  ) {
1139  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1140  return true;
1141  }
1142  } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1143  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1144  // bytes. There shouldn't be a legitimate reason for this to happen.
1145  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1146  return true;
1147  } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1148  // EBCDIC encoded XML
1149  wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" );
1150  return true;
1151  }
1152 
1153  // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1154  // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1155  $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1156  foreach ( $attemptEncodings as $encoding ) {
1158  $str = iconv( $encoding, 'UTF-8', $contents );
1160  if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1161  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1162  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1163  ) {
1164  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1165  return true;
1166  }
1167  } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1168  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1169  // bytes. There shouldn't be a legitimate reason for this to happen.
1170  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1171  return true;
1172  }
1173  }
1174 
1175  return false;
1176  }
1177 
1182  protected function detectScriptInSvg( $filename ) {
1183  $this->mSVGNSError = false;
1184  $check = new XmlTypeCheck(
1185  $filename,
1186  array( $this, 'checkSvgScriptCallback' ),
1187  true,
1188  array(
1189  'processing_instruction_handler' => 'UploadBase::checkSvgPICallback',
1190  'external_dtd_handler' => 'UploadBase::checkSvgExternalDTD',
1191  )
1192  );
1193  if ( $check->wellFormed !== true ) {
1194  // Invalid xml (bug 58553)
1195  return array( 'uploadinvalidxml' );
1196  } elseif ( $check->filterMatch ) {
1197  if ( $this->mSVGNSError ) {
1198  return array( 'uploadscriptednamespace', $this->mSVGNSError );
1199  }
1200  return array( 'uploadscripted' );
1201  }
1202  return false;
1203  }
1204 
1211  public static function checkSvgPICallback( $target, $data ) {
1212  // Don't allow external stylesheets (bug 57550)
1213  if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1214  return true;
1215  }
1216  return false;
1217  }
1218 
1229  public static function checkSvgExternalDTD( $type, $publicId, $systemId ) {
1230  // This doesn't include the XHTML+MathML+SVG doctype since we don't
1231  // allow XHTML anyways.
1232  $allowedDTDs = array(
1233  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1234  'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1235  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1236  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd'
1237  );
1238  if ( $type !== 'PUBLIC'
1239  || !in_array( $systemId, $allowedDTDs )
1240  || strpos( $publicId, "-//W3C//" ) !== 0
1241  ) {
1242  return array( 'upload-scripted-dtd' );
1243  }
1244  return false;
1245  }
1246 
1253  public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1254 
1255  list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1256 
1257  static $validNamespaces = array(
1258  '',
1259  'adobe:ns:meta/',
1260  'http://creativecommons.org/ns#',
1261  'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1262  'http://ns.adobe.com/adobeillustrator/10.0/',
1263  'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1264  'http://ns.adobe.com/extensibility/1.0/',
1265  'http://ns.adobe.com/flows/1.0/',
1266  'http://ns.adobe.com/illustrator/1.0/',
1267  'http://ns.adobe.com/imagereplacement/1.0/',
1268  'http://ns.adobe.com/pdf/1.3/',
1269  'http://ns.adobe.com/photoshop/1.0/',
1270  'http://ns.adobe.com/saveforweb/1.0/',
1271  'http://ns.adobe.com/variables/1.0/',
1272  'http://ns.adobe.com/xap/1.0/',
1273  'http://ns.adobe.com/xap/1.0/g/',
1274  'http://ns.adobe.com/xap/1.0/g/img/',
1275  'http://ns.adobe.com/xap/1.0/mm/',
1276  'http://ns.adobe.com/xap/1.0/rights/',
1277  'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1278  'http://ns.adobe.com/xap/1.0/stype/font#',
1279  'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1280  'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1281  'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1282  'http://ns.adobe.com/xap/1.0/t/pg/',
1283  'http://purl.org/dc/elements/1.1/',
1284  'http://purl.org/dc/elements/1.1',
1285  'http://schemas.microsoft.com/visio/2003/svgextensions/',
1286  'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1287  'http://web.resource.org/cc/',
1288  'http://www.freesoftware.fsf.org/bkchem/cdml',
1289  'http://www.inkscape.org/namespaces/inkscape',
1290  'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1291  'http://www.w3.org/2000/svg',
1292  );
1293 
1294  if ( !in_array( $namespace, $validNamespaces ) ) {
1295  wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" );
1296  // @TODO return a status object to a closure in XmlTypeCheck, for MW1.21+
1297  $this->mSVGNSError = $namespace;
1298  return true;
1299  }
1300 
1301  /*
1302  * check for elements that can contain javascript
1303  */
1304  if ( $strippedElement == 'script' ) {
1305  wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1306  return true;
1307  }
1308 
1309  # 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>
1310  if ( $strippedElement == 'handler' ) {
1311  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1312  return true;
1313  }
1314 
1315  # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1316  if ( $strippedElement == 'stylesheet' ) {
1317  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1318  return true;
1319  }
1320 
1321  # Block iframes, in case they pass the namespace check
1322  if ( $strippedElement == 'iframe' ) {
1323  wfDebug( __METHOD__ . ": iframe in uploaded file.\n" );
1324  return true;
1325  }
1326 
1327  # Check <style> css
1328  if ( $strippedElement == 'style'
1329  && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1330  ) {
1331  wfDebug( __METHOD__ . ": hostile css in style element.\n" );
1332  return true;
1333  }
1334 
1335  foreach ( $attribs as $attrib => $value ) {
1336  $stripped = $this->stripXmlNamespace( $attrib );
1337  $value = strtolower( $value );
1338 
1339  if ( substr( $stripped, 0, 2 ) == 'on' ) {
1340  wfDebug( __METHOD__ . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1341  return true;
1342  }
1343 
1344  # href with non-local target (don't allow http://, javascript:, etc)
1345  if ( $stripped == 'href'
1346  && strpos( $value, 'data:' ) !== 0
1347  && strpos( $value, '#' ) !== 0
1348  ) {
1349  if ( !( $strippedElement === 'a'
1350  && preg_match( '!^https?://!i', $value ) )
1351  ) {
1352  wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1353  . "'$attrib'='$value' in uploaded file.\n" );
1354 
1355  return true;
1356  }
1357  }
1358 
1359  # only allow data: targets that should be safe. This prevents vectors like,
1360  # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1361  if ( $stripped == 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1362  // rfc2397 parameters. This is only slightly slower than (;[\w;]+)*.
1363  $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1364  if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1365  wfDebug( __METHOD__ . ": Found href to unwhitelisted data: uri "
1366  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1367  return true;
1368  }
1369  }
1370 
1371  # Change href with animate from (http://html5sec.org/#137).
1372  if ( $stripped === 'attributename'
1373  && $strippedElement === 'animate'
1374  && $this->stripXmlNamespace( $value ) == 'href'
1375  ) {
1376  wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1377  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1378 
1379  return true;
1380  }
1381 
1382  # use set/animate to add event-handler attribute to parent
1383  if ( ( $strippedElement == 'set' || $strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
1384  wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1385  return true;
1386  }
1387 
1388  # use set to add href attribute to parent element
1389  if ( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
1390  wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" );
1391  return true;
1392  }
1393 
1394  # use set to add a remote / data / script target to an element
1395  if ( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1396  wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" );
1397  return true;
1398  }
1399 
1400  # use handler attribute with remote / data / script
1401  if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1402  wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1403  return true;
1404  }
1405 
1406  # use CSS styles to bring in remote code
1407  if ( $stripped == 'style'
1408  && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1409  ) {
1410  wfDebug( __METHOD__ . ": Found svg setting a style with "
1411  . "remote url '$attrib'='$value' in uploaded file.\n" );
1412  return true;
1413  }
1414 
1415  # Several attributes can include css, css character escaping isn't allowed
1416  $cssAttrs = array( 'font', 'clip-path', 'fill', 'filter', 'marker',
1417  'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' );
1418  if ( in_array( $stripped, $cssAttrs )
1419  && self::checkCssFragment( $value )
1420  ) {
1421  wfDebug( __METHOD__ . ": Found svg setting a style with "
1422  . "remote url '$attrib'='$value' in uploaded file.\n" );
1423  return true;
1424  }
1425 
1426  # image filters can pull in url, which could be svg that executes scripts
1427  if ( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1428  wfDebug( __METHOD__ . ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1429  return true;
1430  }
1431 
1432  }
1433 
1434  return false; //No scripts detected
1435  }
1436 
1444  private static function checkCssFragment( $value ) {
1445 
1446  # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1447  if ( stripos( $value, '@import' ) !== false ) {
1448  return true;
1449  }
1450 
1451  # We allow @font-face to embed fonts with data: urls, so we snip the string
1452  # 'url' out so this case won't match when we check for urls below
1453  $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1454  $value = preg_replace( $pattern, '$1$2', $value );
1455 
1456  # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1457  # properties filter and accelerator don't seem to be useful for xss in SVG files.
1458  # Expression and -o-link don't seem to work either, but filtering them here in case.
1459  # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1460  # but not local ones such as url("#..., url('#..., url(#....
1461  if ( preg_match( '!expression
1462  | -o-link\s*:
1463  | -o-link-source\s*:
1464  | -o-replace\s*:!imx', $value ) ) {
1465  return true;
1466  }
1467 
1468  if ( preg_match_all(
1469  "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1470  $value,
1471  $matches
1472  ) !== 0
1473  ) {
1474  # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1475  foreach ( $matches[1] as $match ) {
1476  if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1477  return true;
1478  }
1479  }
1480  }
1481 
1482  if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1483  return true;
1484  }
1485 
1486  return false;
1487  }
1488 
1494  private static function splitXmlNamespace( $element ) {
1495  // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1496  $parts = explode( ':', strtolower( $element ) );
1497  $name = array_pop( $parts );
1498  $ns = implode( ':', $parts );
1499  return array( $ns, $name );
1500  }
1501 
1506  private function stripXmlNamespace( $name ) {
1507  // 'http://www.w3.org/2000/svg:script' -> 'script'
1508  $parts = explode( ':', strtolower( $name ) );
1509  return array_pop( $parts );
1510  }
1511 
1522  public static function detectVirus( $file ) {
1523  global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1524  wfProfileIn( __METHOD__ );
1525 
1526  if ( !$wgAntivirus ) {
1527  wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1528  wfProfileOut( __METHOD__ );
1529  return null;
1530  }
1531 
1532  if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1533  wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1534  $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1535  array( 'virus-badscanner', $wgAntivirus ) );
1536  wfProfileOut( __METHOD__ );
1537  return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1538  }
1539 
1540  # look up scanner configuration
1541  $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1542  $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1543  $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1544  $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1545 
1546  if ( strpos( $command, "%f" ) === false ) {
1547  # simple pattern: append file to scan
1548  $command .= " " . wfEscapeShellArg( $file );
1549  } else {
1550  # complex pattern: replace "%f" with file to scan
1551  $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1552  }
1553 
1554  wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1555 
1556  # execute virus scanner
1557  $exitCode = false;
1558 
1559  # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1560  # that does not seem to be worth the pain.
1561  # Ask me (Duesentrieb) about it if it's ever needed.
1562  $output = wfShellExecWithStderr( $command, $exitCode );
1563 
1564  # map exit code to AV_xxx constants.
1565  $mappedCode = $exitCode;
1566  if ( $exitCodeMap ) {
1567  if ( isset( $exitCodeMap[$exitCode] ) ) {
1568  $mappedCode = $exitCodeMap[$exitCode];
1569  } elseif ( isset( $exitCodeMap["*"] ) ) {
1570  $mappedCode = $exitCodeMap["*"];
1571  }
1572  }
1573 
1574  /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1575  * so we need the strict equalities === and thus can't use a switch here
1576  */
1577  if ( $mappedCode === AV_SCAN_FAILED ) {
1578  # scan failed (code was mapped to false by $exitCodeMap)
1579  wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1580 
1581  $output = $wgAntivirusRequired ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text() : null;
1582  } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1583  # scan failed because filetype is unknown (probably imune)
1584  wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1585  $output = null;
1586  } elseif ( $mappedCode === AV_NO_VIRUS ) {
1587  # no virus found
1588  wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1589  $output = false;
1590  } else {
1591  $output = trim( $output );
1592 
1593  if ( !$output ) {
1594  $output = true; #if there's no output, return true
1595  } elseif ( $msgPattern ) {
1596  $groups = array();
1597  if ( preg_match( $msgPattern, $output, $groups ) ) {
1598  if ( $groups[1] ) {
1599  $output = $groups[1];
1600  }
1601  }
1602  }
1603 
1604  wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1605  }
1606 
1607  wfProfileOut( __METHOD__ );
1608  return $output;
1609  }
1610 
1619  private function checkOverwrite( $user ) {
1620  // First check whether the local file can be overwritten
1621  $file = $this->getLocalFile();
1622  if ( $file->exists() ) {
1623  if ( !self::userCanReUpload( $user, $file ) ) {
1624  return array( 'fileexists-forbidden', $file->getName() );
1625  } else {
1626  return true;
1627  }
1628  }
1629 
1630  /* Check shared conflicts: if the local file does not exist, but
1631  * wfFindFile finds a file, it exists in a shared repository.
1632  */
1633  $file = wfFindFile( $this->getTitle() );
1634  if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1635  return array( 'fileexists-shared-forbidden', $file->getName() );
1636  }
1637 
1638  return true;
1639  }
1640 
1648  public static function userCanReUpload( User $user, $img ) {
1649  if ( $user->isAllowed( 'reupload' ) ) {
1650  return true; // non-conditional
1651  }
1652  if ( !$user->isAllowed( 'reupload-own' ) ) {
1653  return false;
1654  }
1655  if ( is_string( $img ) ) {
1656  $img = wfLocalFile( $img );
1657  }
1658  if ( !( $img instanceof LocalFile ) ) {
1659  return false;
1660  }
1661 
1662  return $user->getId() == $img->getUser( 'id' );
1663  }
1664 
1676  public static function getExistsWarning( $file ) {
1677  if ( $file->exists() ) {
1678  return array( 'warning' => 'exists', 'file' => $file );
1679  }
1680 
1681  if ( $file->getTitle()->getArticleID() ) {
1682  return array( 'warning' => 'page-exists', 'file' => $file );
1683  }
1684 
1685  if ( $file->wasDeleted() && !$file->exists() ) {
1686  return array( 'warning' => 'was-deleted', 'file' => $file );
1687  }
1688 
1689  if ( strpos( $file->getName(), '.' ) == false ) {
1690  $partname = $file->getName();
1691  $extension = '';
1692  } else {
1693  $n = strrpos( $file->getName(), '.' );
1694  $extension = substr( $file->getName(), $n + 1 );
1695  $partname = substr( $file->getName(), 0, $n );
1696  }
1697  $normalizedExtension = File::normalizeExtension( $extension );
1698 
1699  if ( $normalizedExtension != $extension ) {
1700  // We're not using the normalized form of the extension.
1701  // Normal form is lowercase, using most common of alternate
1702  // extensions (eg 'jpg' rather than 'JPEG').
1703  //
1704  // Check for another file using the normalized form...
1705  $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1706  $file_lc = wfLocalFile( $nt_lc );
1707 
1708  if ( $file_lc->exists() ) {
1709  return array(
1710  'warning' => 'exists-normalized',
1711  'file' => $file,
1712  'normalizedFile' => $file_lc
1713  );
1714  }
1715  }
1716 
1717  // Check for files with the same name but a different extension
1718  $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix(
1719  "{$partname}.", 1 );
1720  if ( count( $similarFiles ) ) {
1721  return array(
1722  'warning' => 'exists-normalized',
1723  'file' => $file,
1724  'normalizedFile' => $similarFiles[0],
1725  );
1726  }
1727 
1728  if ( self::isThumbName( $file->getName() ) ) {
1729  # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1730  $nt_thb = Title::newFromText( substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension, NS_FILE );
1731  $file_thb = wfLocalFile( $nt_thb );
1732  if ( $file_thb->exists() ) {
1733  return array(
1734  'warning' => 'thumb',
1735  'file' => $file,
1736  'thumbFile' => $file_thb
1737  );
1738  } else {
1739  // File does not exist, but we just don't like the name
1740  return array(
1741  'warning' => 'thumb-name',
1742  'file' => $file,
1743  'thumbFile' => $file_thb
1744  );
1745  }
1746  }
1747 
1748  foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
1749  if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1750  return array(
1751  'warning' => 'bad-prefix',
1752  'file' => $file,
1753  'prefix' => $prefix
1754  );
1755  }
1756  }
1757 
1758  return false;
1759  }
1760 
1766  public static function isThumbName( $filename ) {
1767  $n = strrpos( $filename, '.' );
1768  $partname = $n ? substr( $filename, 0, $n ) : $filename;
1769  return (
1770  substr( $partname, 3, 3 ) == 'px-' ||
1771  substr( $partname, 2, 3 ) == 'px-'
1772  ) &&
1773  preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1774  }
1775 
1781  public static function getFilenamePrefixBlacklist() {
1782  $blacklist = array();
1783  $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1784  if ( !$message->isDisabled() ) {
1785  $lines = explode( "\n", $message->plain() );
1786  foreach ( $lines as $line ) {
1787  // Remove comment lines
1788  $comment = substr( trim( $line ), 0, 1 );
1789  if ( $comment == '#' || $comment == '' ) {
1790  continue;
1791  }
1792  // Remove additional comments after a prefix
1793  $comment = strpos( $line, '#' );
1794  if ( $comment > 0 ) {
1795  $line = substr( $line, 0, $comment - 1 );
1796  }
1797  $blacklist[] = trim( $line );
1798  }
1799  }
1800  return $blacklist;
1801  }
1802 
1813  public function getImageInfo( $result ) {
1814  $file = $this->getLocalFile();
1815  // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1816  // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1817  if ( $file instanceof UploadStashFile ) {
1819  $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1820  } else {
1822  $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1823  }
1824  return $info;
1825  }
1826 
1831  public function convertVerifyErrorToStatus( $error ) {
1832  $code = $error['status'];
1833  unset( $code['status'] );
1834  return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1835  }
1836 
1841  public static function getMaxUploadSize( $forType = null ) {
1842  global $wgMaxUploadSize;
1843 
1844  if ( is_array( $wgMaxUploadSize ) ) {
1845  if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1846  return $wgMaxUploadSize[$forType];
1847  } else {
1848  return $wgMaxUploadSize['*'];
1849  }
1850  } else {
1851  return intval( $wgMaxUploadSize );
1852  }
1853  }
1854 
1861  public static function getSessionStatus( $statusKey ) {
1862  return isset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] )
1863  ? $_SESSION[self::SESSION_STATUS_KEY][$statusKey]
1864  : false;
1865  }
1866 
1874  public static function setSessionStatus( $statusKey, $value ) {
1875  if ( $value === false ) {
1876  unset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] );
1877  } else {
1878  $_SESSION[self::SESSION_STATUS_KEY][$statusKey] = $value;
1879  }
1880  }
1881 }
AV_NO_VIRUS
const AV_NO_VIRUS
Definition: Defines.php:148
Title\makeTitle
static & makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:398
$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
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
$request
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 my contributions etc etc otherwise the built in rate limiting checks are if enabled also a ContextSource error or success you ll probably need to make sure the header is varied on WebRequest $request
Definition: hooks.txt:1961
RepoGroup\singleton
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:53
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:2584
AV_SCAN_FAILED
const AV_SCAN_FAILED
Definition: Defines.php:151
$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
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:1087
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:2434
wfArrayDiff2
if(!defined( 'MEDIAWIKI')) wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
Definition: GlobalFunctions.php:160
Status\newGood
static newGood( $value=null)
Factory function for good results.
Definition: Status.php:77
NS_FILE
const NS_FILE
Definition: Defines.php:85
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:3084
ApiQueryImageInfo\getPropertyNames
static getPropertyNames( $filter=array())
Returns all possible parameters to iiprop.
Definition: ApiQueryImageInfo.php:652
ApiQueryImageInfo\getInfo
static getInfo( $file, $prop, $result, $thumbParams=null, $opts=false)
Get result information for an image revision.
Definition: ApiQueryImageInfo.php:330
InfoAction\getName
getName()
Returns the name of the action this object responds to.
Definition: InfoAction.php:38
AV_SCAN_ABORTED
const AV_SCAN_ABORTED
Definition: Defines.php:150
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
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:3908
wfRestoreWarnings
wfRestoreWarnings()
Restore error level to previous value.
Definition: GlobalFunctions.php:2464
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1330
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
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
wfProfileOut
wfProfileOut( $functionname='missing')
Stop profiling of a function.
Definition: Profiler.php:46
$wgOut
$wgOut
Definition: Setup.php:582
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:4066
$lines
$lines
Definition: router.php:65
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
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
$comment
$comment
Definition: importImages.php:107
$wgFileExtensions
if(! $wgHtml5Version && $wgAllowRdfaAttributes) $wgFileExtensions
Definition: Setup.php:369
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
$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:980
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
$value
$value
Definition: styleTest.css.php:45
ArchivedFile
Class representing a row of the 'filearchive' table.
Definition: ArchivedFile.php:29
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:2571
wfEscapeShellArg
wfEscapeShellArg()
Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell,...
Definition: GlobalFunctions.php:2752
XmlTypeCheck
Definition: XmlTypeCheck.php:28
$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:2732
File\DELETE_SOURCE
const DELETE_SOURCE
Definition: File.php:65
$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:2708
$file
if(PHP_SAPI !='cli') $file
Definition: UtfNormalTest2.php:30
$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
Sanitizer\normalizeCss
static normalizeCss( $value)
Normalize CSS into a format we can easily search for hostile input.
Definition: Sanitizer.php:829
$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
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:3313
used
you don t have to do a grep find to see where the $wgReverseTitle variable is used
Definition: hooks.txt:117
$output
& $output
Definition: hooks.txt:375
$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
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:52
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:1414
$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:2584
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:2584
$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:3768
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
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:1961
$type
$type
Definition: testCompression.php:46