Merge "Make line breaks in <blockquote> behave like <div> (bug 6200)."
[mediawiki.git] / includes / upload / UploadFromUrl.php
bloba4374f3f682959a345b20255b58836a8e947e4b4
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';
52 return parent::isAllowed( $user );
55 /**
56 * Checks if the upload from URL feature is enabled
57 * @return bool
59 public static function isEnabled() {
60 global $wgAllowCopyUploads;
61 return $wgAllowCopyUploads && parent::isEnabled();
64 /**
65 * Checks whether the URL is for an allowed host
66 * The domains in the whitelist can include wildcard characters (*) in place
67 * of any of the domain levels, e.g. '*.flickr.com' or 'upload.*.gov.uk'.
69 * @param $url string
70 * @return bool
72 public static function isAllowedHost( $url ) {
73 global $wgCopyUploadsDomains;
74 if ( !count( $wgCopyUploadsDomains ) ) {
75 return true;
77 $parsedUrl = wfParseUrl( $url );
78 if ( !$parsedUrl ) {
79 return false;
81 $valid = false;
82 foreach ( $wgCopyUploadsDomains as $domain ) {
83 // See if the domain for the upload matches this whitelisted domain
84 $whitelistedDomainPieces = explode( '.', $domain );
85 $uploadDomainPieces = explode( '.', $parsedUrl['host'] );
86 if ( count( $whitelistedDomainPieces ) === count( $uploadDomainPieces ) ) {
87 $valid = true;
88 // See if all the pieces match or not (excluding wildcards)
89 foreach ( $whitelistedDomainPieces as $index => $piece ) {
90 if ( $piece !== '*' && $piece !== $uploadDomainPieces[$index] ) {
91 $valid = false;
94 if ( $valid ) {
95 // We found a match, so quit comparing against the list
96 break;
99 /* Non-wildcard test
100 if ( $parsedUrl['host'] === $domain ) {
101 $valid = true;
102 break;
106 return $valid;
110 * Checks whether the URL is not allowed.
112 * @param $url string
113 * @return bool
115 public static function isAllowedUrl( $url ) {
116 if ( !isset( self::$allowedUrls[$url] ) ) {
117 $allowed = true;
118 wfRunHooks( 'IsUploadAllowedFromUrl', array( $url, &$allowed ) );
119 self::$allowedUrls[$url] = $allowed;
121 return self::$allowedUrls[$url];
125 * Entry point for API upload
127 * @param $name string
128 * @param $url string
129 * @param $async mixed Whether the download should be performed
130 * asynchronous. False for synchronous, async or async-leavemessage for
131 * asynchronous download.
132 * @throws MWException
134 public function initialize( $name, $url, $async = false ) {
135 global $wgAllowAsyncCopyUploads;
137 $this->mUrl = $url;
138 $this->mAsync = $wgAllowAsyncCopyUploads ? $async : false;
139 if ( $async ) {
140 throw new MWException( 'Asynchronous copy uploads are no longer possible as of r81612.' );
143 $tempPath = $this->mAsync ? null : $this->makeTemporaryFile();
144 # File size and removeTempFile will be filled in later
145 $this->initializePathInfo( $name, $tempPath, 0, false );
149 * Entry point for SpecialUpload
150 * @param $request WebRequest object
152 public function initializeFromRequest( &$request ) {
153 $desiredDestName = $request->getText( 'wpDestFile' );
154 if ( !$desiredDestName ) {
155 $desiredDestName = $request->getText( 'wpUploadFileURL' );
157 $this->initialize(
158 $desiredDestName,
159 trim( $request->getVal( 'wpUploadFileURL' ) ),
160 false
165 * @param $request WebRequest object
166 * @return bool
168 public static function isValidRequest( $request ) {
169 global $wgUser;
171 $url = $request->getVal( 'wpUploadFileURL' );
172 return !empty( $url )
173 && Http::isValidURI( $url )
174 && $wgUser->isAllowed( 'upload_by_url' );
178 * @return string
180 public function getSourceType() {
181 return 'url';
185 * @return Status
187 public function fetchFile() {
188 if ( !Http::isValidURI( $this->mUrl ) ) {
189 return Status::newFatal( 'http-invalid-url' );
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 if ( !$this->mAsync ) {
199 return $this->reallyFetchFile();
201 return Status::newGood();
204 * Create a new temporary file in the URL subdirectory of wfTempDir().
206 * @return string Path to the file
208 protected function makeTemporaryFile() {
209 return tempnam( wfTempDir(), 'URL' );
213 * Callback: save a chunk of the result of a HTTP request to the temporary file
215 * @param $req mixed
216 * @param $buffer string
217 * @return int number of bytes handled
219 public function saveTempFileChunk( $req, $buffer ) {
220 $nbytes = fwrite( $this->mTmpHandle, $buffer );
222 if ( $nbytes == strlen( $buffer ) ) {
223 $this->mFileSize += $nbytes;
224 } else {
225 // Well... that's not good!
226 fclose( $this->mTmpHandle );
227 $this->mTmpHandle = false;
230 return $nbytes;
234 * Download the file, save it to the temporary file and update the file
235 * size and set $mRemoveTempFile to true.
236 * @return Status
238 protected function reallyFetchFile() {
239 if ( $this->mTempPath === false ) {
240 return Status::newFatal( 'tmp-create-error' );
243 // Note the temporary file should already be created by makeTemporaryFile()
244 $this->mTmpHandle = fopen( $this->mTempPath, 'wb' );
245 if ( !$this->mTmpHandle ) {
246 return Status::newFatal( 'tmp-create-error' );
249 $this->mRemoveTempFile = true;
250 $this->mFileSize = 0;
252 $options = array(
253 'followRedirects' => true
255 global $wgCopyUploadProxy;
256 if ( $wgCopyUploadProxy !== false ) {
257 $options['proxy'] = $wgCopyUploadProxy;
259 $req = MWHttpRequest::factory( $this->mUrl, $options );
260 $req->setCallback( array( $this, 'saveTempFileChunk' ) );
261 $status = $req->execute();
263 if ( $this->mTmpHandle ) {
264 // File got written ok...
265 fclose( $this->mTmpHandle );
266 $this->mTmpHandle = null;
267 } else {
268 // We encountered a write error during the download...
269 return Status::newFatal( 'tmp-write-error' );
272 if ( !$status->isOk() ) {
273 return $status;
276 return $status;
280 * Wrapper around the parent function in order to defer verifying the
281 * upload until the file really has been fetched.
282 * @return array|mixed
284 public function verifyUpload() {
285 if ( $this->mAsync ) {
286 return array( 'status' => UploadBase::OK );
288 return parent::verifyUpload();
292 * Wrapper around the parent function in order to defer checking warnings
293 * until the file really has been fetched.
294 * @return Array
296 public function checkWarnings() {
297 if ( $this->mAsync ) {
298 $this->mIgnoreWarnings = false;
299 return array();
301 return parent::checkWarnings();
305 * Wrapper around the parent function in order to defer checking protection
306 * until we are sure that the file can actually be uploaded
307 * @param $user User
308 * @return bool|mixed
310 public function verifyTitlePermissions( $user ) {
311 if ( $this->mAsync ) {
312 return true;
314 return parent::verifyTitlePermissions( $user );
318 * Wrapper around the parent function in order to defer uploading to the
319 * job queue for asynchronous uploads
320 * @param $comment string
321 * @param $pageText string
322 * @param $watch bool
323 * @param $user User
324 * @return Status
326 public function performUpload( $comment, $pageText, $watch, $user ) {
327 if ( $this->mAsync ) {
328 $sessionKey = $this->insertJob( $comment, $pageText, $watch, $user );
330 return Status::newFatal( 'async', $sessionKey );
333 return parent::performUpload( $comment, $pageText, $watch, $user );
337 * @param $comment
338 * @param $pageText
339 * @param $watch
340 * @param $user User
341 * @return String
343 protected function insertJob( $comment, $pageText, $watch, $user ) {
344 $sessionKey = $this->stashSession();
345 $job = new UploadFromUrlJob( $this->getTitle(), array(
346 'url' => $this->mUrl,
347 'comment' => $comment,
348 'pageText' => $pageText,
349 'watch' => $watch,
350 'userName' => $user->getName(),
351 'leaveMessage' => $this->mAsync == 'async-leavemessage',
352 'ignoreWarnings' => $this->mIgnoreWarnings,
353 'sessionId' => session_id(),
354 'sessionKey' => $sessionKey,
355 ) );
356 $job->initializeSessionData();
357 JobQueueGroup::singleton()->push( $job );
358 return $sessionKey;