3 use MediaWiki\MediaWikiServices
;
6 * Backend for uploading files from a HTTP resource.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
28 * Implements uploading from a HTTP resource.
31 * @author Bryan Tong Minh
32 * @author Michael Dale
34 class UploadFromUrl
extends UploadBase
{
37 protected $mTempPath, $mTmpHandle;
39 protected static $allowedUrls = [];
42 * Checks if the user is allowed to use the upload-by-URL feature. If the
43 * user is not allowed, return the name of the user right as a string. If
44 * the user is allowed, have the parent do further permissions checking.
50 public static function isAllowed( $user ) {
51 if ( !$user->isAllowed( 'upload_by_url' ) ) {
52 return 'upload_by_url';
55 return parent
::isAllowed( $user );
59 * Checks if the upload from URL feature is enabled
62 public static function isEnabled() {
63 global $wgAllowCopyUploads;
65 return $wgAllowCopyUploads && parent
::isEnabled();
69 * Checks whether the URL is for an allowed host
70 * The domains in the whitelist can include wildcard characters (*) in place
71 * of any of the domain levels, e.g. '*.flickr.com' or 'upload.*.gov.uk'.
76 public static function isAllowedHost( $url ) {
77 global $wgCopyUploadsDomains;
78 if ( !count( $wgCopyUploadsDomains ) ) {
81 $parsedUrl = wfParseUrl( $url );
86 foreach ( $wgCopyUploadsDomains as $domain ) {
87 // See if the domain for the upload matches this whitelisted domain
88 $whitelistedDomainPieces = explode( '.', $domain );
89 $uploadDomainPieces = explode( '.', $parsedUrl['host'] );
90 if ( count( $whitelistedDomainPieces ) === count( $uploadDomainPieces ) ) {
92 // See if all the pieces match or not (excluding wildcards)
93 foreach ( $whitelistedDomainPieces as $index => $piece ) {
94 if ( $piece !== '*' && $piece !== $uploadDomainPieces[$index] ) {
99 // We found a match, so quit comparing against the list
104 if ( $parsedUrl['host'] === $domain ) {
115 * Checks whether the URL is not allowed.
120 public static function isAllowedUrl( $url ) {
121 if ( !isset( self
::$allowedUrls[$url] ) ) {
123 Hooks
::run( 'IsUploadAllowedFromUrl', [ $url, &$allowed ] );
124 self
::$allowedUrls[$url] = $allowed;
127 return self
::$allowedUrls[$url];
131 * Entry point for API upload
133 * @param string $name
135 * @throws MWException
137 public function initialize( $name, $url ) {
140 $tempPath = $this->makeTemporaryFile();
141 # File size and removeTempFile will be filled in later
142 $this->initializePathInfo( $name, $tempPath, 0, false );
146 * Entry point for SpecialUpload
147 * @param WebRequest &$request
149 public function initializeFromRequest( &$request ) {
150 $desiredDestName = $request->getText( 'wpDestFile' );
151 if ( !$desiredDestName ) {
152 $desiredDestName = $request->getText( 'wpUploadFileURL' );
156 trim( $request->getVal( 'wpUploadFileURL' ) )
161 * @param WebRequest $request
164 public static function isValidRequest( $request ) {
167 $url = $request->getVal( 'wpUploadFileURL' );
169 return !empty( $url )
170 && $wgUser->isAllowed( 'upload_by_url' );
176 public function getSourceType() {
183 * @param array $httpOptions Array of options for MWHttpRequest.
184 * This could be used to override the timeout on the http request.
187 public function fetchFile( $httpOptions = [] ) {
188 if ( !Http
::isValidURI( $this->mUrl
) ) {
189 return Status
::newFatal( 'http-invalid-url', $this->mUrl
);
192 if ( !self
::isAllowedHost( $this->mUrl
) ) {
193 return Status
::newFatal( 'upload-copy-upload-invalid-domain' );
195 if ( !self
::isAllowedUrl( $this->mUrl
) ) {
196 return Status
::newFatal( 'upload-copy-upload-invalid-url' );
198 return $this->reallyFetchFile( $httpOptions );
202 * Create a new temporary file in the URL subdirectory of wfTempDir().
204 * @return string Path to the file
206 protected function makeTemporaryFile() {
207 $tmpFile = MediaWikiServices
::getInstance()->getTempFSFileFactory()
208 ->newTempFSFile( 'URL', 'urlupload_' );
209 $tmpFile->bind( $this );
211 return $tmpFile->getPath();
215 * Callback: save a chunk of the result of a HTTP request to the temporary file
218 * @param string $buffer
219 * @return int Number of bytes handled
221 public function saveTempFileChunk( $req, $buffer ) {
222 wfDebugLog( 'fileupload', 'Received chunk of ' . strlen( $buffer ) . ' bytes' );
223 $nbytes = fwrite( $this->mTmpHandle
, $buffer );
225 if ( $nbytes == strlen( $buffer ) ) {
226 $this->mFileSize +
= $nbytes;
228 // Well... that's not good!
231 'Short write ' . $nbytes . '/' . strlen( $buffer ) .
232 ' bytes, aborting with ' . $this->mFileSize
. ' uploaded so far'
234 fclose( $this->mTmpHandle
);
235 $this->mTmpHandle
= false;
242 * Download the file, save it to the temporary file and update the file
243 * size and set $mRemoveTempFile to true.
245 * @param array $httpOptions Array of options for MWHttpRequest
248 protected function reallyFetchFile( $httpOptions = [] ) {
249 global $wgCopyUploadProxy, $wgCopyUploadTimeout;
250 if ( $this->mTempPath
=== false ) {
251 return Status
::newFatal( 'tmp-create-error' );
254 // Note the temporary file should already be created by makeTemporaryFile()
255 $this->mTmpHandle
= fopen( $this->mTempPath
, 'wb' );
256 if ( !$this->mTmpHandle
) {
257 return Status
::newFatal( 'tmp-create-error' );
259 wfDebugLog( 'fileupload', 'Temporary file created "' . $this->mTempPath
. '"' );
261 $this->mRemoveTempFile
= true;
262 $this->mFileSize
= 0;
264 $options = $httpOptions +
[ 'followRedirects' => true ];
266 if ( $wgCopyUploadProxy !== false ) {
267 $options['proxy'] = $wgCopyUploadProxy;
270 if ( $wgCopyUploadTimeout && !isset( $options['timeout'] ) ) {
271 $options['timeout'] = $wgCopyUploadTimeout;
275 'Starting download from "' . $this->mUrl
. '" ' .
276 '<' . implode( ',', array_keys( array_filter( $options ) ) ) . '>'
278 $req = MWHttpRequest
::factory( $this->mUrl
, $options, __METHOD__
);
279 $req->setCallback( [ $this, 'saveTempFileChunk' ] );
280 $status = $req->execute();
282 if ( $this->mTmpHandle
) {
283 // File got written ok...
284 fclose( $this->mTmpHandle
);
285 $this->mTmpHandle
= null;
287 // We encountered a write error during the download...
288 return Status
::newFatal( 'tmp-write-error' );
291 wfDebugLog( 'fileupload', $status );
292 if ( $status->isOK() ) {
293 wfDebugLog( 'fileupload', 'Download by URL completed successfully.' );
297 'Download by URL completed with HTTP status ' . $req->getStatus()