3 * Backend for uploading files from a HTTP resource.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Implements uploading from a HTTP resource.
28 * @author Bryan Tong Minh
29 * @author Michael Dale
31 class UploadFromUrl
extends UploadBase
{
34 protected $mTempPath, $mTmpHandle;
36 protected static $allowedUrls = [];
39 * Checks if the user is allowed to use the upload-by-URL feature. If the
40 * user is not allowed, return the name of the user right as a string. If
41 * the user is allowed, have the parent do further permissions checking.
47 public static function isAllowed( $user ) {
48 if ( !$user->isAllowed( 'upload_by_url' ) ) {
49 return 'upload_by_url';
52 return parent
::isAllowed( $user );
56 * Checks if the upload from URL feature is enabled
59 public static function isEnabled() {
60 global $wgAllowCopyUploads;
62 return $wgAllowCopyUploads && parent
::isEnabled();
66 * Checks whether the URL is for an allowed host
67 * The domains in the whitelist can include wildcard characters (*) in place
68 * of any of the domain levels, e.g. '*.flickr.com' or 'upload.*.gov.uk'.
73 public static function isAllowedHost( $url ) {
74 global $wgCopyUploadsDomains;
75 if ( !count( $wgCopyUploadsDomains ) ) {
78 $parsedUrl = wfParseUrl( $url );
83 foreach ( $wgCopyUploadsDomains as $domain ) {
84 // See if the domain for the upload matches this whitelisted domain
85 $whitelistedDomainPieces = explode( '.', $domain );
86 $uploadDomainPieces = explode( '.', $parsedUrl['host'] );
87 if ( count( $whitelistedDomainPieces ) === count( $uploadDomainPieces ) ) {
89 // See if all the pieces match or not (excluding wildcards)
90 foreach ( $whitelistedDomainPieces as $index => $piece ) {
91 if ( $piece !== '*' && $piece !== $uploadDomainPieces[$index] ) {
96 // We found a match, so quit comparing against the list
101 if ( $parsedUrl['host'] === $domain ) {
112 * Checks whether the URL is not allowed.
117 public static function isAllowedUrl( $url ) {
118 if ( !isset( self
::$allowedUrls[$url] ) ) {
120 Hooks
::run( 'IsUploadAllowedFromUrl', [ $url, &$allowed ] );
121 self
::$allowedUrls[$url] = $allowed;
124 return self
::$allowedUrls[$url];
128 * Entry point for API upload
130 * @param string $name
132 * @throws MWException
134 public function initialize( $name, $url ) {
137 $tempPath = $this->makeTemporaryFile();
138 # File size and removeTempFile will be filled in later
139 $this->initializePathInfo( $name, $tempPath, 0, false );
143 * Entry point for SpecialUpload
144 * @param WebRequest &$request
146 public function initializeFromRequest( &$request ) {
147 $desiredDestName = $request->getText( 'wpDestFile' );
148 if ( !$desiredDestName ) {
149 $desiredDestName = $request->getText( 'wpUploadFileURL' );
153 trim( $request->getVal( 'wpUploadFileURL' ) )
158 * @param WebRequest $request
161 public static function isValidRequest( $request ) {
164 $url = $request->getVal( 'wpUploadFileURL' );
166 return !empty( $url )
167 && $wgUser->isAllowed( 'upload_by_url' );
173 public function getSourceType() {
180 * @param array $httpOptions Array of options for MWHttpRequest.
181 * This could be used to override the timeout on the http request.
184 public function fetchFile( $httpOptions = [] ) {
185 if ( !Http
::isValidURI( $this->mUrl
) ) {
186 return Status
::newFatal( 'http-invalid-url', $this->mUrl
);
189 if ( !self
::isAllowedHost( $this->mUrl
) ) {
190 return Status
::newFatal( 'upload-copy-upload-invalid-domain' );
192 if ( !self
::isAllowedUrl( $this->mUrl
) ) {
193 return Status
::newFatal( 'upload-copy-upload-invalid-url' );
195 return $this->reallyFetchFile( $httpOptions );
199 * Create a new temporary file in the URL subdirectory of wfTempDir().
201 * @return string Path to the file
203 protected function makeTemporaryFile() {
204 $tmpFile = TempFSFile
::factory( 'URL', 'urlupload_', wfTempDir() );
205 $tmpFile->bind( $this );
207 return $tmpFile->getPath();
211 * Callback: save a chunk of the result of a HTTP request to the temporary file
214 * @param string $buffer
215 * @return int Number of bytes handled
217 public function saveTempFileChunk( $req, $buffer ) {
218 wfDebugLog( 'fileupload', 'Received chunk of ' . strlen( $buffer ) . ' bytes' );
219 $nbytes = fwrite( $this->mTmpHandle
, $buffer );
221 if ( $nbytes == strlen( $buffer ) ) {
222 $this->mFileSize +
= $nbytes;
224 // Well... that's not good!
227 'Short write ' . $nbytes . '/' . strlen( $buffer ) .
228 ' bytes, aborting with ' . $this->mFileSize
. ' uploaded so far'
230 fclose( $this->mTmpHandle
);
231 $this->mTmpHandle
= false;
238 * Download the file, save it to the temporary file and update the file
239 * size and set $mRemoveTempFile to true.
241 * @param array $httpOptions Array of options for MWHttpRequest
244 protected function reallyFetchFile( $httpOptions = [] ) {
245 global $wgCopyUploadProxy, $wgCopyUploadTimeout;
246 if ( $this->mTempPath
=== false ) {
247 return Status
::newFatal( 'tmp-create-error' );
250 // Note the temporary file should already be created by makeTemporaryFile()
251 $this->mTmpHandle
= fopen( $this->mTempPath
, 'wb' );
252 if ( !$this->mTmpHandle
) {
253 return Status
::newFatal( 'tmp-create-error' );
255 wfDebugLog( 'fileupload', 'Temporary file created "' . $this->mTempPath
. '"' );
257 $this->mRemoveTempFile
= true;
258 $this->mFileSize
= 0;
260 $options = $httpOptions +
[ 'followRedirects' => true ];
262 if ( $wgCopyUploadProxy !== false ) {
263 $options['proxy'] = $wgCopyUploadProxy;
266 if ( $wgCopyUploadTimeout && !isset( $options['timeout'] ) ) {
267 $options['timeout'] = $wgCopyUploadTimeout;
271 'Starting download from "' . $this->mUrl
. '" ' .
272 '<' . implode( ',', array_keys( array_filter( $options ) ) ) . '>'
274 $req = MWHttpRequest
::factory( $this->mUrl
, $options, __METHOD__
);
275 $req->setCallback( [ $this, 'saveTempFileChunk' ] );
276 $status = $req->execute();
278 if ( $this->mTmpHandle
) {
279 // File got written ok...
280 fclose( $this->mTmpHandle
);
281 $this->mTmpHandle
= null;
283 // We encountered a write error during the download...
284 return Status
::newFatal( 'tmp-write-error' );
287 wfDebugLog( 'fileupload', $status );
288 if ( $status->isOK() ) {
289 wfDebugLog( 'fileupload', 'Download by URL completed successfully.' );
293 'Download by URL completed with HTTP status ' . $req->getStatus()