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' ) ),
159 * @param WebRequest $request
162 public static function isValidRequest( $request ) {
165 $url = $request->getVal( 'wpUploadFileURL' );
167 return !empty( $url )
168 && $wgUser->isAllowed( 'upload_by_url' );
174 public function getSourceType() {
181 * @param array $httpOptions Array of options for MWHttpRequest.
182 * This could be used to override the timeout on the http request.
185 public function fetchFile( $httpOptions = [] ) {
186 if ( !Http
::isValidURI( $this->mUrl
) ) {
187 return Status
::newFatal( 'http-invalid-url', $this->mUrl
);
190 if ( !self
::isAllowedHost( $this->mUrl
) ) {
191 return Status
::newFatal( 'upload-copy-upload-invalid-domain' );
193 if ( !self
::isAllowedUrl( $this->mUrl
) ) {
194 return Status
::newFatal( 'upload-copy-upload-invalid-url' );
196 return $this->reallyFetchFile( $httpOptions );
200 * Create a new temporary file in the URL subdirectory of wfTempDir().
202 * @return string Path to the file
204 protected function makeTemporaryFile() {
205 $tmpFile = TempFSFile
::factory( 'URL', 'urlupload_', wfTempDir() );
206 $tmpFile->bind( $this );
208 return $tmpFile->getPath();
212 * Callback: save a chunk of the result of a HTTP request to the temporary file
215 * @param string $buffer
216 * @return int Number of bytes handled
218 public function saveTempFileChunk( $req, $buffer ) {
219 wfDebugLog( 'fileupload', 'Received chunk of ' . strlen( $buffer ) . ' bytes' );
220 $nbytes = fwrite( $this->mTmpHandle
, $buffer );
222 if ( $nbytes == strlen( $buffer ) ) {
223 $this->mFileSize +
= $nbytes;
225 // Well... that's not good!
228 'Short write ' . $this->nbytes
. '/' . strlen( $buffer ) .
229 ' bytes, aborting with ' . $this->mFileSize
. ' uploaded so far'
231 fclose( $this->mTmpHandle
);
232 $this->mTmpHandle
= false;
239 * Download the file, save it to the temporary file and update the file
240 * size and set $mRemoveTempFile to true.
242 * @param array $httpOptions Array of options for MWHttpRequest
245 protected function reallyFetchFile( $httpOptions = [] ) {
246 global $wgCopyUploadProxy, $wgCopyUploadTimeout;
247 if ( $this->mTempPath
=== false ) {
248 return Status
::newFatal( 'tmp-create-error' );
251 // Note the temporary file should already be created by makeTemporaryFile()
252 $this->mTmpHandle
= fopen( $this->mTempPath
, 'wb' );
253 if ( !$this->mTmpHandle
) {
254 return Status
::newFatal( 'tmp-create-error' );
256 wfDebugLog( 'fileupload', 'Temporary file created "' . $this->mTempPath
. '"' );
258 $this->mRemoveTempFile
= true;
259 $this->mFileSize
= 0;
261 $options = $httpOptions +
[ 'followRedirects' => true ];
263 if ( $wgCopyUploadProxy !== false ) {
264 $options['proxy'] = $wgCopyUploadProxy;
267 if ( $wgCopyUploadTimeout && !isset( $options['timeout'] ) ) {
268 $options['timeout'] = $wgCopyUploadTimeout;
272 'Starting download from "' . $this->mUrl
. '" ' .
273 '<' . implode( ',', array_keys( array_filter( $options ) ) ) . '>'
275 $req = MWHttpRequest
::factory( $this->mUrl
, $options, __METHOD__
);
276 $req->setCallback( [ $this, 'saveTempFileChunk' ] );
277 $status = $req->execute();
279 if ( $this->mTmpHandle
) {
280 // File got written ok...
281 fclose( $this->mTmpHandle
);
282 $this->mTmpHandle
= null;
284 // We encountered a write error during the download...
285 return Status
::newFatal( 'tmp-write-error' );
288 wfDebugLog( 'fileupload', $status );
289 if ( $status->isOK() ) {
290 wfDebugLog( 'fileupload', 'Download by URL completed successfuly.' );
294 'Download by URL completed with HTTP status ' . $req->getStatus()