summaryrefslogtreecommitdiff
path: root/includes/api/ApiUpload.php
diff options
context:
space:
mode:
Diffstat (limited to 'includes/api/ApiUpload.php')
-rw-r--r--includes/api/ApiUpload.php291
1 files changed, 175 insertions, 116 deletions
diff --git a/includes/api/ApiUpload.php b/includes/api/ApiUpload.php
index e7d7b939..1dab0310 100644
--- a/includes/api/ApiUpload.php
+++ b/includes/api/ApiUpload.php
@@ -1,6 +1,6 @@
<?php
/**
- * API for MediaWiki 1.8+
+ *
*
* Created on Aug 21, 2008
*
@@ -33,7 +33,12 @@ if ( !defined( 'MEDIAWIKI' ) ) {
* @ingroup API
*/
class ApiUpload extends ApiBase {
+
+ /**
+ * @var UploadBase
+ */
protected $mUpload = null;
+
protected $mParams;
public function __construct( $main, $action ) {
@@ -45,7 +50,7 @@ class ApiUpload extends ApiBase {
// Check whether upload is enabled
if ( !UploadBase::isEnabled() ) {
- $this->dieUsageMsg( array( 'uploaddisabled' ) );
+ $this->dieUsageMsg( 'uploaddisabled' );
}
// Parameter handling
@@ -54,6 +59,11 @@ class ApiUpload extends ApiBase {
// Add the uploaded file to the params array
$this->mParams['file'] = $request->getFileName( 'file' );
+ // Copy the session key to the file key, for backward compatibility.
+ if( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
+ $this->mParams['filekey'] = $this->mParams['sessionkey'];
+ }
+
// Select an upload module
if ( !$this->selectUploadModule() ) {
// This is not a true upload, but a status request or similar
@@ -77,34 +87,40 @@ class ApiUpload extends ApiBase {
// Check if the uploaded file is sane
$this->verifyUpload();
- // Check permission to upload this file
- $permErrors = $this->mUpload->verifyPermissions( $wgUser );
- if ( $permErrors !== true ) {
- // TODO: stash the upload and allow choosing a new name
- $this->dieUsageMsg( array( 'badaccess-groups' ) );
+
+ // Check if the user has the rights to modify or overwrite the requested title
+ // (This check is irrelevant if stashing is already requested, since the errors
+ // can always be fixed by changing the title)
+ if ( ! $this->mParams['stash'] ) {
+ $permErrors = $this->mUpload->verifyTitlePermissions( $wgUser );
+ if ( $permErrors !== true ) {
+ $this->dieRecoverableError( $permErrors[0], 'filename' );
+ }
}
// Prepare the API result
$result = array();
-
+
$warnings = $this->getApiWarnings();
- if ( $warnings ) {
+ if ( $warnings ) {
$result['result'] = 'Warning';
$result['warnings'] = $warnings;
// in case the warnings can be fixed with some further user action, let's stash this upload
// and return a key they can use to restart it
- try {
- $result['sessionkey'] = $this->performStash();
- } catch ( MWException $e ) {
+ try {
+ $result['filekey'] = $this->performStash();
+ $result['sessionkey'] = $result['filekey']; // backwards compatibility
+ } catch ( MWException $e ) {
$result['warnings']['stashfailed'] = $e->getMessage();
}
- } elseif ( $this->mParams['stash'] ) {
+ } elseif ( $this->mParams['stash'] ) {
// Some uploads can request they be stashed, so as not to publish them immediately.
// In this case, a failure to stash ought to be fatal
try {
- $result['result'] = 'Success';
- $result['sessionkey'] = $this->performStash();
- } catch ( MWException $e ) {
+ $result['result'] = 'Success';
+ $result['filekey'] = $this->performStash();
+ $result['sessionkey'] = $result['filekey']; // backwards compatibility
+ } catch ( MWException $e ) {
$this->dieUsage( $e->getMessage(), 'stashfailed' );
}
} else {
@@ -113,52 +129,76 @@ class ApiUpload extends ApiBase {
$result = $this->performUpload();
}
- if ( $result['result'] === 'Success' ) {
+ if ( $result['result'] === 'Success' ) {
$result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
}
$this->getResult()->addValue( null, $this->getModuleName(), $result );
-
+
// Cleanup any temporary mess
$this->mUpload->cleanupTempFile();
}
/**
- * Stash the file and return the session key
+ * Stash the file and return the file key
* Also re-raises exceptions with slightly more informative message strings (useful for API)
* @throws MWException
- * @return {String} session key
+ * @return String file key
*/
function performStash() {
try {
- $sessionKey = $this->mUpload->stashSessionFile()->getSessionKey();
+ $fileKey = $this->mUpload->stashFile()->getFileKey();
} catch ( MWException $e ) {
- throw new MWException( 'Stashing temporary file failed: ' . get_class($e) . ' ' . $e->getMessage() );
+ $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
+ wfDebug( __METHOD__ . ' ' . $message . "\n");
+ throw new MWException( $message );
}
- return $sessionKey;
+ return $fileKey;
}
+ /**
+ * Throw an error that the user can recover from by providing a better
+ * value for $parameter
+ *
+ * @param $error array Error array suitable for passing to dieUsageMsg()
+ * @param $parameter string Parameter that needs revising
+ * @param $data array Optional extra data to pass to the user
+ * @throws UsageException
+ */
+ function dieRecoverableError( $error, $parameter, $data = array() ) {
+ try {
+ $data['filekey'] = $this->performStash();
+ $data['sessionkey'] = $data['filekey'];
+ } catch ( MWException $e ) {
+ $data['stashfailed'] = $e->getMessage();
+ }
+ $data['invalidparameter'] = $parameter;
+
+ $parsed = $this->parseMsg( $error );
+ $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
+ }
/**
* Select an upload module and set it to mUpload. Dies on failure. If the
- * request was a status request and not a true upload, returns false;
+ * request was a status request and not a true upload, returns false;
* otherwise true
- *
+ *
* @return bool
*/
protected function selectUploadModule() {
- global $wgAllowAsyncCopyUploads;
$request = $this->getMain()->getRequest();
// One and only one of the following parameters is needed
$this->requireOnlyOneParameter( $this->mParams,
- 'sessionkey', 'file', 'url', 'statuskey' );
+ 'filekey', 'file', 'url', 'statuskey' );
+
+ if ( $this->mParams['statuskey'] ) {
+ $this->checkAsyncDownloadEnabled();
- if ( $wgAllowAsyncCopyUploads && $this->mParams['statuskey'] ) {
// Status request for an async upload
$sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
if ( !isset( $sessionData['result'] ) ) {
- $this->dieUsage( 'No result in session data', 'missingresult');
+ $this->dieUsage( 'No result in session data', 'missingresult' );
}
if ( $sessionData['result'] == 'Warning' ) {
$sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
@@ -166,28 +206,24 @@ class ApiUpload extends ApiBase {
}
$this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
return false;
-
- }
+ }
// The following modules all require the filename parameter to be set
if ( is_null( $this->mParams['filename'] ) ) {
$this->dieUsageMsg( array( 'missingparam', 'filename' ) );
}
-
- if ( $this->mParams['sessionkey'] ) {
+ if ( $this->mParams['filekey'] ) {
// Upload stashed in a previous request
- $sessionData = $request->getSessionData( UploadBase::getSessionKeyName() );
- if ( !UploadFromStash::isValidSessionKey( $this->mParams['sessionkey'], $sessionData ) ) {
- $this->dieUsageMsg( array( 'invalid-session-key' ) );
+ if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
+ $this->dieUsageMsg( 'invalid-file-key' );
}
- $this->mUpload = new UploadFromStash();
- $this->mUpload->initialize( $this->mParams['filename'],
- $this->mParams['sessionkey'],
- $sessionData[$this->mParams['sessionkey']] );
-
+ // context allows access to the current user without creating new $wgUser references
+ $context = $this->createContext();
+ $this->mUpload = new UploadFromStash( $context->getUser() );
+ $this->mUpload->initialize( $this->mParams['filekey'], $this->mParams['filename'] );
} elseif ( isset( $this->mParams['file'] ) ) {
$this->mUpload = new UploadFromFile();
@@ -198,16 +234,18 @@ class ApiUpload extends ApiBase {
} elseif ( isset( $this->mParams['url'] ) ) {
// Make sure upload by URL is enabled:
if ( !UploadFromUrl::isEnabled() ) {
- $this->dieUsageMsg( array( 'copyuploaddisabled' ) );
+ $this->dieUsageMsg( 'copyuploaddisabled' );
}
$async = false;
if ( $this->mParams['asyncdownload'] ) {
+ $this->checkAsyncDownloadEnabled();
+
if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
$this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
'missing-ignorewarnings' );
}
-
+
if ( $this->mParams['leavemessage'] ) {
$async = 'async-leavemessage';
} else {
@@ -219,7 +257,7 @@ class ApiUpload extends ApiBase {
$this->mParams['url'], $async );
}
-
+
return true;
}
@@ -236,7 +274,7 @@ class ApiUpload extends ApiBase {
if ( !$user->isLoggedIn() ) {
$this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
} else {
- $this->dieUsageMsg( array( 'badaccess-groups' ) );
+ $this->dieUsageMsg( 'badaccess-groups' );
}
}
}
@@ -254,15 +292,29 @@ class ApiUpload extends ApiBase {
// TODO: Move them to ApiBase's message map
switch( $verification['status'] ) {
+ // Recoverable errors
+ case UploadBase::MIN_LENGTH_PARTNAME:
+ $this->dieRecoverableError( 'filename-tooshort', 'filename' );
+ break;
+ case UploadBase::ILLEGAL_FILENAME:
+ $this->dieRecoverableError( 'illegal-filename', 'filename',
+ array( 'filename' => $verification['filtered'] ) );
+ break;
+ case UploadBase::FILETYPE_MISSING:
+ $this->dieRecoverableError( 'filetype-missing', 'filename' );
+ break;
+ case UploadBase::WINDOWS_NONASCII_FILENAME:
+ $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
+ break;
+
+ // Unrecoverable errors
case UploadBase::EMPTY_FILE:
$this->dieUsage( 'The file you submitted was empty', 'empty-file' );
break;
case UploadBase::FILE_TOO_LARGE:
$this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
break;
- case UploadBase::FILETYPE_MISSING:
- $this->dieUsage( 'The file is missing an extension', 'filetype-missing' );
- break;
+
case UploadBase::FILETYPE_BADTYPE:
$this->dieUsage( 'This type of file is banned', 'filetype-banned',
0, array(
@@ -270,13 +322,6 @@ class ApiUpload extends ApiBase {
'allowed' => $wgFileExtensions
) );
break;
- case UploadBase::MIN_LENGTH_PARTNAME:
- $this->dieUsage( 'The filename is too short', 'filename-tooshort' );
- break;
- case UploadBase::ILLEGAL_FILENAME:
- $this->dieUsage( 'The filename is not allowed', 'illegal-filename',
- 0, array( 'filename' => $verification['filtered'] ) );
- break;
case UploadBase::VERIFICATION_ERROR:
$this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
$this->dieUsage( 'This file did not pass file verification', 'verification-error',
@@ -306,30 +351,35 @@ class ApiUpload extends ApiBase {
if ( !$this->mParams['ignorewarnings'] ) {
$warnings = $this->mUpload->checkWarnings();
- if ( $warnings ) {
- // Add indices
- $this->getResult()->setIndexedTagName( $warnings, 'warning' );
-
- if ( isset( $warnings['duplicate'] ) ) {
- $dupes = array();
- foreach ( $warnings['duplicate'] as $dupe ) {
- $dupes[] = $dupe->getName();
- }
- $this->getResult()->setIndexedTagName( $dupes, 'duplicate' );
- $warnings['duplicate'] = $dupes;
- }
+ }
+ return $this->transformWarnings( $warnings );
+ }
+
+ protected function transformWarnings( $warnings ) {
+ if ( $warnings ) {
+ // Add indices
+ $result = $this->getResult();
+ $result->setIndexedTagName( $warnings, 'warning' );
- if ( isset( $warnings['exists'] ) ) {
- $warning = $warnings['exists'];
- unset( $warnings['exists'] );
- $warnings[$warning['warning']] = $warning['file']->getName();
+ if ( isset( $warnings['duplicate'] ) ) {
+ $dupes = array();
+ foreach ( $warnings['duplicate'] as $dupe ) {
+ $dupes[] = $dupe->getName();
}
+ $result->setIndexedTagName( $dupes, 'duplicate' );
+ $warnings['duplicate'] = $dupes;
}
- }
+ if ( isset( $warnings['exists'] ) ) {
+ $warning = $warnings['exists'];
+ unset( $warnings['exists'] );
+ $warnings[$warning['warning']] = $warning['file']->getName();
+ }
+ }
return $warnings;
}
+
/**
* Perform the actual upload. Returns a suitable result array on success;
* dies on failure.
@@ -376,10 +426,19 @@ class ApiUpload extends ApiBase {
$result['result'] = 'Success';
$result['filename'] = $file->getName();
-
return $result;
}
+ /**
+ * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
+ */
+ protected function checkAsyncDownloadEnabled() {
+ global $wgAllowAsyncCopyUploads;
+ if ( !$wgAllowAsyncCopyUploads ) {
+ $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
+ }
+ }
+
public function mustBePosted() {
return true;
}
@@ -413,18 +472,18 @@ class ApiUpload extends ApiBase {
'ignorewarnings' => false,
'file' => null,
'url' => null,
- 'sessionkey' => null,
+ 'filekey' => null,
+ 'sessionkey' => array(
+ ApiBase::PARAM_DFLT => null,
+ ApiBase::PARAM_DEPRECATED => true,
+ ),
'stash' => false,
+
+ 'asyncdownload' => false,
+ 'leavemessage' => false,
+ 'statuskey' => null,
);
- global $wgAllowAsyncCopyUploads;
- if ( $wgAllowAsyncCopyUploads ) {
- $params += array(
- 'asyncdownload' => false,
- 'leavemessage' => false,
- 'statuskey' => null,
- );
- }
return $params;
}
@@ -439,18 +498,14 @@ class ApiUpload extends ApiBase {
'ignorewarnings' => 'Ignore any warnings',
'file' => 'File contents',
'url' => 'Url to fetch the file from',
- 'sessionkey' => 'Session key that identifies a previous upload that was stashed temporarily.',
- 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.'
- );
+ 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
+ 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
+ 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
- global $wgAllowAsyncCopyUploads;
- if ( $wgAllowAsyncCopyUploads ) {
- $params += array(
- 'asyncdownload' => 'Make fetching a URL asynchronous',
- 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
- 'statuskey' => 'Fetch the upload status for this session key',
- );
- }
+ 'asyncdownload' => 'Make fetching a URL asynchronous',
+ 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
+ 'statuskey' => 'Fetch the upload status for this file key',
+ );
return $params;
@@ -461,32 +516,32 @@ class ApiUpload extends ApiBase {
'Upload a file, or get the status of pending uploads. Several methods are available:',
' * Upload file contents directly, using the "file" parameter',
' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
- ' * Complete an earlier upload that failed due to warnings, using the "sessionkey" parameter',
+ ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
- 'sending the "file". Note also that queries using session keys must be',
- 'done in the same login session as the query that originally returned the key (i.e. do not',
- 'log out and then log back in). Also you must get and send an edit token before doing any upload stuff'
+ 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
);
}
public function getPossibleErrors() {
- return array_merge( parent::getPossibleErrors(), array(
- array( 'uploaddisabled' ),
- array( 'invalid-session-key' ),
- array( 'uploaddisabled' ),
- array( 'badaccess-groups' ),
- array( 'mustbeloggedin', 'upload' ),
- array( 'badaccess-groups' ),
- array( 'badaccess-groups' ),
- array( 'code' => 'fetchfileerror', 'info' => '' ),
- array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
- array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
- array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
- array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
- array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
- array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
- array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
- ) );
+ return array_merge( parent::getPossibleErrors(),
+ $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
+ array(
+ array( 'uploaddisabled' ),
+ array( 'invalid-file-key' ),
+ array( 'uploaddisabled' ),
+ array( 'mustbeloggedin', 'upload' ),
+ array( 'badaccess-groups' ),
+ array( 'code' => 'fetchfileerror', 'info' => '' ),
+ array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
+ array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
+ array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
+ array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
+ array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
+ array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
+ array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
+ array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
+ )
+ );
}
public function needsToken() {
@@ -502,11 +557,15 @@ class ApiUpload extends ApiBase {
'Upload from a URL:',
' api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png',
'Complete an upload that failed due to warnings:',
- ' api.php?action=upload&filename=Wiki.png&sessionkey=sessionkey&ignorewarnings=1',
+ ' api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1',
);
}
+ public function getHelpUrls() {
+ return 'https://www.mediawiki.org/wiki/API:Upload';
+ }
+
public function getVersion() {
- return __CLASS__ . ': $Id: ApiUpload.php 51812 2009-06-12 23:45:20Z dale $';
+ return __CLASS__ . ': $Id: ApiUpload.php 104449 2011-11-28 15:52:04Z reedy $';
}
}