wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / upload / UploadFromUrl.php
blobf897a796b9db8d77661e7076ea1f0ea15ef0d045
1 <?php
2 /**
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
20 * @file
21 * @ingroup Upload
24 /**
25 * Implements uploading from a HTTP resource.
27 * @ingroup Upload
28 * @author Bryan Tong Minh
29 * @author Michael Dale
31 class UploadFromUrl extends UploadBase {
32 protected $mAsync, $mUrl;
33 protected $mIgnoreWarnings = true;
35 protected $mTempPath, $mTmpHandle;
37 protected static $allowedUrls = array();
39 /**
40 * Checks if the user is allowed to use the upload-by-URL feature. If the
41 * user is not allowed, return the name of the user right as a string. If
42 * the user is allowed, have the parent do further permissions checking.
44 * @param User $user
46 * @return bool|string
48 public static function isAllowed( $user ) {
49 if ( !$user->isAllowed( 'upload_by_url' ) ) {
50 return 'upload_by_url';
53 return parent::isAllowed( $user );
56 /**
57 * Checks if the upload from URL feature is enabled
58 * @return bool
60 public static function isEnabled() {
61 global $wgAllowCopyUploads;
63 return $wgAllowCopyUploads && parent::isEnabled();
66 /**
67 * Checks whether the URL is for an allowed host
68 * The domains in the whitelist can include wildcard characters (*) in place
69 * of any of the domain levels, e.g. '*.flickr.com' or 'upload.*.gov.uk'.
71 * @param string $url
72 * @return bool
74 public static function isAllowedHost( $url ) {
75 global $wgCopyUploadsDomains;
76 if ( !count( $wgCopyUploadsDomains ) ) {
77 return true;
79 $parsedUrl = wfParseUrl( $url );
80 if ( !$parsedUrl ) {
81 return false;
83 $valid = false;
84 foreach ( $wgCopyUploadsDomains as $domain ) {
85 // See if the domain for the upload matches this whitelisted domain
86 $whitelistedDomainPieces = explode( '.', $domain );
87 $uploadDomainPieces = explode( '.', $parsedUrl['host'] );
88 if ( count( $whitelistedDomainPieces ) === count( $uploadDomainPieces ) ) {
89 $valid = true;
90 // See if all the pieces match or not (excluding wildcards)
91 foreach ( $whitelistedDomainPieces as $index => $piece ) {
92 if ( $piece !== '*' && $piece !== $uploadDomainPieces[$index] ) {
93 $valid = false;
96 if ( $valid ) {
97 // We found a match, so quit comparing against the list
98 break;
101 /* Non-wildcard test
102 if ( $parsedUrl['host'] === $domain ) {
103 $valid = true;
104 break;
109 return $valid;
113 * Checks whether the URL is not allowed.
115 * @param string $url
116 * @return bool
118 public static function isAllowedUrl( $url ) {
119 if ( !isset( self::$allowedUrls[$url] ) ) {
120 $allowed = true;
121 Hooks::run( 'IsUploadAllowedFromUrl', array( $url, &$allowed ) );
122 self::$allowedUrls[$url] = $allowed;
125 return self::$allowedUrls[$url];
129 * Entry point for API upload
131 * @param string $name
132 * @param string $url
133 * @param bool|string $async Whether the download should be performed
134 * asynchronous. False for synchronous, async or async-leavemessage for
135 * asynchronous download.
136 * @throws MWException
138 public function initialize( $name, $url, $async = false ) {
139 global $wgAllowAsyncCopyUploads;
141 $this->mUrl = $url;
142 $this->mAsync = $wgAllowAsyncCopyUploads ? $async : false;
143 if ( $async ) {
144 throw new MWException( 'Asynchronous copy uploads are no longer possible as of r81612.' );
147 $tempPath = $this->mAsync ? null : $this->makeTemporaryFile();
148 # File size and removeTempFile will be filled in later
149 $this->initializePathInfo( $name, $tempPath, 0, false );
153 * Entry point for SpecialUpload
154 * @param WebRequest $request
156 public function initializeFromRequest( &$request ) {
157 $desiredDestName = $request->getText( 'wpDestFile' );
158 if ( !$desiredDestName ) {
159 $desiredDestName = $request->getText( 'wpUploadFileURL' );
161 $this->initialize(
162 $desiredDestName,
163 trim( $request->getVal( 'wpUploadFileURL' ) ),
164 false
169 * @param WebRequest $request
170 * @return bool
172 public static function isValidRequest( $request ) {
173 global $wgUser;
175 $url = $request->getVal( 'wpUploadFileURL' );
177 return !empty( $url )
178 && $wgUser->isAllowed( 'upload_by_url' );
182 * @return string
184 public function getSourceType() {
185 return 'url';
189 * Download the file (if not async)
191 * @param array $httpOptions Array of options for MWHttpRequest. Ignored if async.
192 * This could be used to override the timeout on the http request.
193 * @return Status
195 public function fetchFile( $httpOptions = array() ) {
196 if ( !Http::isValidURI( $this->mUrl ) ) {
197 return Status::newFatal( 'http-invalid-url', $this->mUrl );
200 if ( !self::isAllowedHost( $this->mUrl ) ) {
201 return Status::newFatal( 'upload-copy-upload-invalid-domain' );
203 if ( !self::isAllowedUrl( $this->mUrl ) ) {
204 return Status::newFatal( 'upload-copy-upload-invalid-url' );
206 if ( !$this->mAsync ) {
207 return $this->reallyFetchFile( $httpOptions );
210 return Status::newGood();
214 * Create a new temporary file in the URL subdirectory of wfTempDir().
216 * @return string Path to the file
218 protected function makeTemporaryFile() {
219 $tmpFile = TempFSFile::factory( 'URL' );
220 $tmpFile->bind( $this );
222 return $tmpFile->getPath();
226 * Callback: save a chunk of the result of a HTTP request to the temporary file
228 * @param mixed $req
229 * @param string $buffer
230 * @return int Number of bytes handled
232 public function saveTempFileChunk( $req, $buffer ) {
233 wfDebugLog( 'fileupload', 'Received chunk of ' . strlen( $buffer ) . ' bytes' );
234 $nbytes = fwrite( $this->mTmpHandle, $buffer );
236 if ( $nbytes == strlen( $buffer ) ) {
237 $this->mFileSize += $nbytes;
238 } else {
239 // Well... that's not good!
240 wfDebugLog(
241 'fileupload',
242 'Short write ' . $this->nbytes . '/' . strlen( $buffer ) .
243 ' bytes, aborting with ' . $this->mFileSize . ' uploaded so far'
245 fclose( $this->mTmpHandle );
246 $this->mTmpHandle = false;
249 return $nbytes;
253 * Download the file, save it to the temporary file and update the file
254 * size and set $mRemoveTempFile to true.
256 * @param array $httpOptions Array of options for MWHttpRequest
257 * @return Status
259 protected function reallyFetchFile( $httpOptions = array() ) {
260 global $wgCopyUploadProxy, $wgCopyUploadTimeout;
261 if ( $this->mTempPath === false ) {
262 return Status::newFatal( 'tmp-create-error' );
265 // Note the temporary file should already be created by makeTemporaryFile()
266 $this->mTmpHandle = fopen( $this->mTempPath, 'wb' );
267 if ( !$this->mTmpHandle ) {
268 return Status::newFatal( 'tmp-create-error' );
270 wfDebugLog( 'fileupload', 'Temporary file created "' . $this->mTempPath . '"' );
272 $this->mRemoveTempFile = true;
273 $this->mFileSize = 0;
275 $options = $httpOptions + array( 'followRedirects' => true );
277 if ( $wgCopyUploadProxy !== false ) {
278 $options['proxy'] = $wgCopyUploadProxy;
281 if ( $wgCopyUploadTimeout && !isset( $options['timeout'] ) ) {
282 $options['timeout'] = $wgCopyUploadTimeout;
284 wfDebugLog(
285 'fileupload',
286 'Starting download from "' . $this->mUrl . '" ' .
287 '<' . implode( ',', array_keys( array_filter( $options ) ) ) . '>'
289 $req = MWHttpRequest::factory( $this->mUrl, $options, __METHOD__ );
290 $req->setCallback( array( $this, 'saveTempFileChunk' ) );
291 $status = $req->execute();
293 if ( $this->mTmpHandle ) {
294 // File got written ok...
295 fclose( $this->mTmpHandle );
296 $this->mTmpHandle = null;
297 } else {
298 // We encountered a write error during the download...
299 return Status::newFatal( 'tmp-write-error' );
302 wfDebugLog( 'fileupload', $status );
303 if ( $status->isOk() ) {
304 wfDebugLog( 'fileupload', 'Download by URL completed successfuly.' );
305 } else {
306 wfDebugLog(
307 'fileupload',
308 'Download by URL completed with HTTP status ' . $req->getStatus()
312 return $status;
316 * Wrapper around the parent function in order to defer verifying the
317 * upload until the file really has been fetched.
318 * @return array|mixed
320 public function verifyUpload() {
321 if ( $this->mAsync ) {
322 return array( 'status' => UploadBase::OK );
325 return parent::verifyUpload();
329 * Wrapper around the parent function in order to defer checking warnings
330 * until the file really has been fetched.
331 * @return array
333 public function checkWarnings() {
334 if ( $this->mAsync ) {
335 $this->mIgnoreWarnings = false;
337 return array();
340 return parent::checkWarnings();
344 * Wrapper around the parent function in order to defer checking protection
345 * until we are sure that the file can actually be uploaded
346 * @param User $user
347 * @return bool|mixed
349 public function verifyTitlePermissions( $user ) {
350 if ( $this->mAsync ) {
351 return true;
354 return parent::verifyTitlePermissions( $user );
358 * Wrapper around the parent function in order to defer uploading to the
359 * job queue for asynchronous uploads
360 * @param string $comment
361 * @param string $pageText
362 * @param bool $watch
363 * @param User $user
364 * @return Status
366 public function performUpload( $comment, $pageText, $watch, $user ) {
367 if ( $this->mAsync ) {
368 $sessionKey = $this->insertJob( $comment, $pageText, $watch, $user );
370 return Status::newFatal( 'async', $sessionKey );
373 return parent::performUpload( $comment, $pageText, $watch, $user );
377 * @param string $comment
378 * @param string $pageText
379 * @param bool $watch
380 * @param User $user
381 * @return string
383 protected function insertJob( $comment, $pageText, $watch, $user ) {
384 $sessionKey = $this->stashSession();
385 $job = new UploadFromUrlJob( $this->getTitle(), array(
386 'url' => $this->mUrl,
387 'comment' => $comment,
388 'pageText' => $pageText,
389 'watch' => $watch,
390 'userName' => $user->getName(),
391 'leaveMessage' => $this->mAsync == 'async-leavemessage',
392 'ignoreWarnings' => $this->mIgnoreWarnings,
393 'sessionId' => session_id(),
394 'sessionKey' => $sessionKey,
395 ) );
396 $job->initializeSessionData();
397 JobQueueGroup::singleton()->push( $job );
399 return $sessionKey;