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
{
32 protected $mAsync, $mUrl;
33 protected $mIgnoreWarnings = true;
35 protected $mTempPath, $mTmpHandle;
38 * Checks if the user is allowed to use the upload-by-URL feature. If the
39 * user is not allowed, return the name of the user right as a string. If
40 * the user is allowed, have the parent do further permissions checking.
46 public static function isAllowed( $user ) {
47 if ( !$user->isAllowed( 'upload_by_url' ) ) {
48 return 'upload_by_url';
50 return parent
::isAllowed( $user );
54 * Checks if the upload from URL feature is enabled
57 public static function isEnabled() {
58 global $wgAllowCopyUploads;
59 return $wgAllowCopyUploads && parent
::isEnabled();
63 * Checks whether the URL is for an allowed host
64 * The domains in the whitelist can include wildcard characters (*) in place
65 * of any of the domain levels, e.g. '*.flickr.com' or 'upload.*.gov.uk'.
70 public static function isAllowedHost( $url ) {
71 global $wgCopyUploadsDomains;
72 if ( !count( $wgCopyUploadsDomains ) ) {
75 $parsedUrl = wfParseUrl( $url );
80 foreach( $wgCopyUploadsDomains as $domain ) {
81 // See if the domain for the upload matches this whitelisted domain
82 $whitelistedDomainPieces = explode( '.', $domain );
83 $uploadDomainPieces = explode( '.', $parsedUrl['host'] );
84 if ( count( $whitelistedDomainPieces ) === count( $uploadDomainPieces ) ) {
86 // See if all the pieces match or not (excluding wildcards)
87 foreach ( $whitelistedDomainPieces as $index => $piece ) {
88 if ( $piece !== '*' && $piece !== $uploadDomainPieces[$index] ) {
93 // We found a match, so quit comparing against the list
98 if ( $parsedUrl['host'] === $domain ) {
108 * Entry point for API upload
110 * @param $name string
112 * @param $async mixed Whether the download should be performed
113 * asynchronous. False for synchronous, async or async-leavemessage for
114 * asynchronous download.
115 * @throws MWException
117 public function initialize( $name, $url, $async = false ) {
118 global $wgAllowAsyncCopyUploads;
121 $this->mAsync
= $wgAllowAsyncCopyUploads ?
$async : false;
123 throw new MWException( 'Asynchronous copy uploads are no longer possible as of r81612.' );
126 $tempPath = $this->mAsync ?
null : $this->makeTemporaryFile();
127 # File size and removeTempFile will be filled in later
128 $this->initializePathInfo( $name, $tempPath, 0, false );
132 * Entry point for SpecialUpload
133 * @param $request WebRequest object
135 public function initializeFromRequest( &$request ) {
136 $desiredDestName = $request->getText( 'wpDestFile' );
137 if ( !$desiredDestName ) {
138 $desiredDestName = $request->getText( 'wpUploadFileURL' );
142 trim( $request->getVal( 'wpUploadFileURL' ) ),
148 * @param $request WebRequest object
151 public static function isValidRequest( $request ) {
154 $url = $request->getVal( 'wpUploadFileURL' );
155 return !empty( $url )
156 && Http
::isValidURI( $url )
157 && $wgUser->isAllowed( 'upload_by_url' );
163 public function getSourceType() { return 'url'; }
168 public function fetchFile() {
169 if ( !Http
::isValidURI( $this->mUrl
) ) {
170 return Status
::newFatal( 'http-invalid-url' );
173 if( !self
::isAllowedHost( $this->mUrl
) ) {
174 return Status
::newFatal( 'upload-copy-upload-invalid-domain' );
176 if ( !$this->mAsync
) {
177 return $this->reallyFetchFile();
179 return Status
::newGood();
182 * Create a new temporary file in the URL subdirectory of wfTempDir().
184 * @return string Path to the file
186 protected function makeTemporaryFile() {
187 return tempnam( wfTempDir(), 'URL' );
191 * Callback: save a chunk of the result of a HTTP request to the temporary file
194 * @param $buffer string
195 * @return int number of bytes handled
197 public function saveTempFileChunk( $req, $buffer ) {
198 $nbytes = fwrite( $this->mTmpHandle
, $buffer );
200 if ( $nbytes == strlen( $buffer ) ) {
201 $this->mFileSize +
= $nbytes;
203 // Well... that's not good!
204 fclose( $this->mTmpHandle
);
205 $this->mTmpHandle
= false;
212 * Download the file, save it to the temporary file and update the file
213 * size and set $mRemoveTempFile to true.
216 protected function reallyFetchFile() {
217 if ( $this->mTempPath
=== false ) {
218 return Status
::newFatal( 'tmp-create-error' );
221 // Note the temporary file should already be created by makeTemporaryFile()
222 $this->mTmpHandle
= fopen( $this->mTempPath
, 'wb' );
223 if ( !$this->mTmpHandle
) {
224 return Status
::newFatal( 'tmp-create-error' );
227 $this->mRemoveTempFile
= true;
228 $this->mFileSize
= 0;
231 'followRedirects' => true
233 global $wgCopyUploadProxy;
234 if ( $wgCopyUploadProxy !== false ) {
235 $options['proxy'] = $wgCopyUploadProxy;
237 $req = MWHttpRequest
::factory( $this->mUrl
, $options );
238 $req->setCallback( array( $this, 'saveTempFileChunk' ) );
239 $status = $req->execute();
241 if ( $this->mTmpHandle
) {
242 // File got written ok...
243 fclose( $this->mTmpHandle
);
244 $this->mTmpHandle
= null;
246 // We encountered a write error during the download...
247 return Status
::newFatal( 'tmp-write-error' );
250 if ( !$status->isOk() ) {
258 * Wrapper around the parent function in order to defer verifying the
259 * upload until the file really has been fetched.
260 * @return array|mixed
262 public function verifyUpload() {
263 if ( $this->mAsync
) {
264 return array( 'status' => UploadBase
::OK
);
266 return parent
::verifyUpload();
270 * Wrapper around the parent function in order to defer checking warnings
271 * until the file really has been fetched.
274 public function checkWarnings() {
275 if ( $this->mAsync
) {
276 $this->mIgnoreWarnings
= false;
279 return parent
::checkWarnings();
283 * Wrapper around the parent function in order to defer checking protection
284 * until we are sure that the file can actually be uploaded
288 public function verifyTitlePermissions( $user ) {
289 if ( $this->mAsync
) {
292 return parent
::verifyTitlePermissions( $user );
296 * Wrapper around the parent function in order to defer uploading to the
297 * job queue for asynchronous uploads
298 * @param $comment string
299 * @param $pageText string
304 public function performUpload( $comment, $pageText, $watch, $user ) {
305 if ( $this->mAsync
) {
306 $sessionKey = $this->insertJob( $comment, $pageText, $watch, $user );
308 return Status
::newFatal( 'async', $sessionKey );
311 return parent
::performUpload( $comment, $pageText, $watch, $user );
321 protected function insertJob( $comment, $pageText, $watch, $user ) {
322 $sessionKey = $this->stashSession();
323 $job = new UploadFromUrlJob( $this->getTitle(), array(
324 'url' => $this->mUrl
,
325 'comment' => $comment,
326 'pageText' => $pageText,
328 'userName' => $user->getName(),
329 'leaveMessage' => $this->mAsync
== 'async-leavemessage',
330 'ignoreWarnings' => $this->mIgnoreWarnings
,
331 'sessionId' => session_id(),
332 'sessionKey' => $sessionKey,
334 $job->initializeSessionData();