MediaWiki 1.41.2
UploadFromUrl.php
Go to the documentation of this file.
1<?php
30
39 protected $mUrl;
40
42
43 protected static $allowedUrls = [];
44
54 public static function isAllowed( Authority $performer ) {
55 if ( !$performer->isAllowed( 'upload_by_url' ) ) {
56 return 'upload_by_url';
57 }
58
59 return parent::isAllowed( $performer );
60 }
61
66 public static function isEnabled() {
67 $allowCopyUploads = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::AllowCopyUploads );
68
69 return $allowCopyUploads && parent::isEnabled();
70 }
71
80 public static function isAllowedHost( $url ) {
81 $domains = self::getAllowedHosts();
82 if ( !count( $domains ) ) {
83 return true;
84 }
85 $parsedUrl = wfParseUrl( $url );
86 if ( !$parsedUrl ) {
87 return false;
88 }
89 $valid = false;
90 foreach ( $domains as $domain ) {
91 // See if the domain for the upload matches this allowed domain
92 $domainPieces = explode( '.', $domain );
93 $uploadDomainPieces = explode( '.', $parsedUrl['host'] );
94 if ( count( $domainPieces ) === count( $uploadDomainPieces ) ) {
95 $valid = true;
96 // See if all the pieces match or not (excluding wildcards)
97 foreach ( $domainPieces as $index => $piece ) {
98 if ( $piece !== '*' && $piece !== $uploadDomainPieces[$index] ) {
99 $valid = false;
100 }
101 }
102 if ( $valid ) {
103 // We found a match, so quit comparing against the list
104 break;
105 }
106 }
107 /* Non-wildcard test
108 if ( $parsedUrl['host'] === $domain ) {
109 $valid = true;
110 break;
111 }
112 */
113 }
114
115 return $valid;
116 }
117
121 private static function getAllowedHosts(): array {
122 $config = MediaWikiServices::getInstance()->getMainConfig();
123 $domains = $config->get( MainConfigNames::CopyUploadsDomains );
124
125 if ( $config->get( MainConfigNames::CopyUploadAllowOnWikiDomainConfig ) ) {
126 $page = wfMessage( 'copyupload-allowed-domains' )->inContentLanguage()->plain();
127
128 foreach ( explode( "\n", $page ) as $line ) {
129 // Strip comments
130 $line = preg_replace( "/^\\s*([^#]*)\\s*((.*)?)$/", "\\1", $line );
131 // Trim whitespace
132 $line = trim( $line );
133
134 if ( $line !== '' ) {
135 $domains[] = $line;
136 }
137 }
138 }
139
140 return $domains;
141 }
142
149 public static function isAllowedUrl( $url ) {
150 if ( !isset( self::$allowedUrls[$url] ) ) {
151 $allowed = true;
152 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
153 ->onIsUploadAllowedFromUrl( $url, $allowed );
154 self::$allowedUrls[$url] = $allowed;
155 }
156
157 return self::$allowedUrls[$url];
158 }
159
167 public function initialize( $name, $url ) {
168 $this->mUrl = $url;
169
170 $tempPath = $this->makeTemporaryFile();
171 # File size and removeTempFile will be filled in later
172 $this->initializePathInfo( $name, $tempPath, 0, false );
173 }
174
179 public function initializeFromRequest( &$request ) {
180 $desiredDestName = $request->getText( 'wpDestFile' );
181 if ( !$desiredDestName ) {
182 $desiredDestName = $request->getText( 'wpUploadFileURL' );
183 }
184 $this->initialize(
185 $desiredDestName,
186 trim( $request->getVal( 'wpUploadFileURL' ) )
187 );
188 }
189
194 public static function isValidRequest( $request ) {
195 $user = RequestContext::getMain()->getUser();
196
197 $url = $request->getVal( 'wpUploadFileURL' );
198
199 return $url
200 && MediaWikiServices::getInstance()
201 ->getPermissionManager()
202 ->userHasRight( $user, 'upload_by_url' );
203 }
204
208 public function getSourceType() {
209 return 'url';
210 }
211
219 public function fetchFile( $httpOptions = [] ) {
220 if ( !MWHttpRequest::isValidURI( $this->mUrl ) ) {
221 return Status::newFatal( 'http-invalid-url', $this->mUrl );
222 }
223
224 if ( !self::isAllowedHost( $this->mUrl ) ) {
225 return Status::newFatal( 'upload-copy-upload-invalid-domain' );
226 }
227 if ( !self::isAllowedUrl( $this->mUrl ) ) {
228 return Status::newFatal( 'upload-copy-upload-invalid-url' );
229 }
230 return $this->reallyFetchFile( $httpOptions );
231 }
232
238 protected function makeTemporaryFile() {
239 $tmpFile = MediaWikiServices::getInstance()->getTempFSFileFactory()
240 ->newTempFSFile( 'URL', 'urlupload_' );
241 $tmpFile->bind( $this );
242
243 return $tmpFile->getPath();
244 }
245
253 public function saveTempFileChunk( $req, $buffer ) {
254 wfDebugLog( 'fileupload', 'Received chunk of ' . strlen( $buffer ) . ' bytes' );
255 $nbytes = fwrite( $this->mTmpHandle, $buffer );
256
257 if ( $nbytes == strlen( $buffer ) ) {
258 $this->mFileSize += $nbytes;
259 } else {
260 // Well... that's not good!
262 'fileupload',
263 'Short write ' . $nbytes . '/' . strlen( $buffer ) .
264 ' bytes, aborting with ' . $this->mFileSize . ' uploaded so far'
265 );
266 fclose( $this->mTmpHandle );
267 $this->mTmpHandle = false;
268 }
269
270 return $nbytes;
271 }
272
280 protected function reallyFetchFile( $httpOptions = [] ) {
281 $copyUploadProxy = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::CopyUploadProxy );
282 $copyUploadTimeout = MediaWikiServices::getInstance()->getMainConfig()
283 ->get( MainConfigNames::CopyUploadTimeout );
284 if ( $this->mTempPath === false ) {
285 return Status::newFatal( 'tmp-create-error' );
286 }
287
288 // Note the temporary file should already be created by makeTemporaryFile()
289 $this->mTmpHandle = fopen( $this->mTempPath, 'wb' );
290 if ( !$this->mTmpHandle ) {
291 return Status::newFatal( 'tmp-create-error' );
292 }
293 wfDebugLog( 'fileupload', 'Temporary file created "' . $this->mTempPath . '"' );
294
295 $this->mRemoveTempFile = true;
296 $this->mFileSize = 0;
297
298 $options = $httpOptions + [ 'followRedirects' => false ];
299
300 if ( $copyUploadProxy !== false ) {
301 $options['proxy'] = $copyUploadProxy;
302 }
303
304 if ( $copyUploadTimeout && !isset( $options['timeout'] ) ) {
305 $options['timeout'] = $copyUploadTimeout;
306 }
308 'fileupload',
309 'Starting download from "' . $this->mUrl . '" ' .
310 '<' . implode( ',', array_keys( array_filter( $options ) ) ) . '>'
311 );
312
313 // Manually follow any redirects up to the limit and reset the output file before each new request to prevent
314 // capturing the redirect response as part of the file.
315 $attemptsLeft = $options['maxRedirects'] ?? 5;
316 $targetUrl = $this->mUrl;
317 $requestFactory = MediaWikiServices::getInstance()->getHttpRequestFactory();
318 while ( $attemptsLeft > 0 ) {
319 $req = $requestFactory->create( $targetUrl, $options, __METHOD__ );
320 $req->setCallback( [ $this, 'saveTempFileChunk' ] );
321 $status = $req->execute();
322 if ( !$req->isRedirect() ) {
323 break;
324 }
325 $targetUrl = $req->getFinalUrl();
326 // Remove redirect response content from file.
327 ftruncate( $this->mTmpHandle, 0 );
328 rewind( $this->mTmpHandle );
329 $attemptsLeft--;
330 }
331
332 if ( $attemptsLeft == 0 ) {
333 return Status::newFatal( 'upload-too-many-redirects' );
334 }
335
336 if ( $this->mTmpHandle ) {
337 // File got written ok...
338 fclose( $this->mTmpHandle );
339 $this->mTmpHandle = null;
340 } else {
341 // We encountered a write error during the download...
342 return Status::newFatal( 'tmp-write-error' );
343 }
344
345 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable Always set after loop
346 if ( $status->isOK() ) {
347 wfDebugLog( 'fileupload', 'Download by URL completed successfully.' );
348 } else {
349 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable Always set after loop
350 wfDebugLog( 'fileupload', $status->getWikiText( false, false, 'en' ) );
352 'fileupload',
353 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable Always set after loop
354 'Download by URL completed with HTTP status ' . $req->getStatus()
355 );
356 }
357
358 // @phan-suppress-next-line PhanTypeMismatchReturnNullable,PhanPossiblyUndeclaredVariable Always set after loop
359 return $status;
360 }
361}
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:58
UploadBase and subclasses are the backend of MediaWiki's file uploads.
Implements uploading from a HTTP resource.
makeTemporaryFile()
Create a new temporary file in the URL subdirectory of wfTempDir().
static isValidRequest( $request)
static isAllowed(Authority $performer)
Checks if the user is allowed to use the upload-by-URL feature.
initializeFromRequest(&$request)
Entry point for SpecialUpload.
reallyFetchFile( $httpOptions=[])
Download the file, save it to the temporary file and update the file size and set $mRemoveTempFile to...
initialize( $name, $url)
Entry point for API upload.
fetchFile( $httpOptions=[])
Download the file.
saveTempFileChunk( $req, $buffer)
Callback: save a chunk of the result of a HTTP request to the temporary file.
static isAllowedHost( $url)
Checks whether the URL is for an allowed host The domains in the allowlist can include wildcard chara...
static isAllowedUrl( $url)
Checks whether the URL is not allowed.
static isEnabled()
Checks if the upload from URL feature is enabled.
This interface represents the authority associated the current execution context, such as a web reque...
Definition Authority.php:37
isAllowed(string $permission, PermissionStatus $status=null)
Checks whether this authority has the given permission in general.