merging latest master
[lhc/web/wiklou.git] / includes / upload / UploadFromUrl.php
1 <?php
2 /**
3 * Backend for uploading files from a HTTP resource.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Upload
22 */
23
24 /**
25 * Implements uploading from a HTTP resource.
26 *
27 * @ingroup Upload
28 * @author Bryan Tong Minh
29 * @author Michael Dale
30 */
31 class UploadFromUrl extends UploadBase {
32 protected $mAsync, $mUrl;
33 protected $mIgnoreWarnings = true;
34
35 protected $mTempPath, $mTmpHandle;
36
37 /**
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.
41 *
42 * @param $user User
43 *
44 * @return bool|string
45 */
46 public static function isAllowed( $user ) {
47 if ( !$user->isAllowed( 'upload_by_url' ) ) {
48 return 'upload_by_url';
49 }
50 return parent::isAllowed( $user );
51 }
52
53 /**
54 * Checks if the upload from URL feature is enabled
55 * @return bool
56 */
57 public static function isEnabled() {
58 global $wgAllowCopyUploads;
59 return $wgAllowCopyUploads && parent::isEnabled();
60 }
61
62 /**
63 * Checks whether the URL is for an allowed host
64 *
65 * @param $url string
66 * @return bool
67 */
68 public static function isAllowedHost( $url ) {
69 global $wgCopyUploadsDomains;
70 if ( !count( $wgCopyUploadsDomains ) ) {
71 return true;
72 }
73 $uri = new Uri( $url );
74 $parsedDomain = $uri->getHost();
75 if ( $parsedDomain === null ) {
76 return false;
77 }
78 $valid = false;
79 foreach( $wgCopyUploadsDomains as $domain ) {
80 if ( $parsedDomain === $domain ) {
81 $valid = true;
82 break;
83 }
84 }
85 return $valid;
86 }
87
88 /**
89 * Entry point for API upload
90 *
91 * @param $name string
92 * @param $url string
93 * @param $async mixed Whether the download should be performed
94 * asynchronous. False for synchronous, async or async-leavemessage for
95 * asynchronous download.
96 * @throws MWException
97 */
98 public function initialize( $name, $url, $async = false ) {
99 global $wgAllowAsyncCopyUploads;
100
101 $this->mUrl = $url;
102 $this->mAsync = $wgAllowAsyncCopyUploads ? $async : false;
103 if ( $async ) {
104 throw new MWException( 'Asynchronous copy uploads are no longer possible as of r81612.' );
105 }
106
107 $tempPath = $this->mAsync ? null : $this->makeTemporaryFile();
108 # File size and removeTempFile will be filled in later
109 $this->initializePathInfo( $name, $tempPath, 0, false );
110 }
111
112 /**
113 * Entry point for SpecialUpload
114 * @param $request WebRequest object
115 */
116 public function initializeFromRequest( &$request ) {
117 $desiredDestName = $request->getText( 'wpDestFile' );
118 if ( !$desiredDestName ) {
119 $desiredDestName = $request->getText( 'wpUploadFileURL' );
120 }
121 $this->initialize(
122 $desiredDestName,
123 trim( $request->getVal( 'wpUploadFileURL' ) ),
124 false
125 );
126 }
127
128 /**
129 * @param $request WebRequest object
130 * @return bool
131 */
132 public static function isValidRequest( $request ) {
133 global $wgUser;
134
135 $url = $request->getVal( 'wpUploadFileURL' );
136 return !empty( $url )
137 && Http::isValidURI( $url )
138 && $wgUser->isAllowed( 'upload_by_url' );
139 }
140
141 /**
142 * @return string
143 */
144 public function getSourceType() { return 'url'; }
145
146 /**
147 * @return Status
148 */
149 public function fetchFile() {
150 if ( !Http::isValidURI( $this->mUrl ) ) {
151 return Status::newFatal( 'http-invalid-url' );
152 }
153
154 if( !self::isAllowedHost( $this->mUrl ) ) {
155 return Status::newFatal( 'upload-copy-upload-invalid-domain' );
156 }
157 if ( !$this->mAsync ) {
158 return $this->reallyFetchFile();
159 }
160 return Status::newGood();
161 }
162 /**
163 * Create a new temporary file in the URL subdirectory of wfTempDir().
164 *
165 * @return string Path to the file
166 */
167 protected function makeTemporaryFile() {
168 return tempnam( wfTempDir(), 'URL' );
169 }
170
171 /**
172 * Callback: save a chunk of the result of a HTTP request to the temporary file
173 *
174 * @param $req mixed
175 * @param $buffer string
176 * @return int number of bytes handled
177 */
178 public function saveTempFileChunk( $req, $buffer ) {
179 $nbytes = fwrite( $this->mTmpHandle, $buffer );
180
181 if ( $nbytes == strlen( $buffer ) ) {
182 $this->mFileSize += $nbytes;
183 } else {
184 // Well... that's not good!
185 fclose( $this->mTmpHandle );
186 $this->mTmpHandle = false;
187 }
188
189 return $nbytes;
190 }
191
192 /**
193 * Download the file, save it to the temporary file and update the file
194 * size and set $mRemoveTempFile to true.
195 * @return Status
196 */
197 protected function reallyFetchFile() {
198 if ( $this->mTempPath === false ) {
199 return Status::newFatal( 'tmp-create-error' );
200 }
201
202 // Note the temporary file should already be created by makeTemporaryFile()
203 $this->mTmpHandle = fopen( $this->mTempPath, 'wb' );
204 if ( !$this->mTmpHandle ) {
205 return Status::newFatal( 'tmp-create-error' );
206 }
207
208 $this->mRemoveTempFile = true;
209 $this->mFileSize = 0;
210
211 $req = MWHttpRequest::factory( $this->mUrl, array(
212 'followRedirects' => true
213 ) );
214 $req->setCallback( array( $this, 'saveTempFileChunk' ) );
215 $status = $req->execute();
216
217 if ( $this->mTmpHandle ) {
218 // File got written ok...
219 fclose( $this->mTmpHandle );
220 $this->mTmpHandle = null;
221 } else {
222 // We encountered a write error during the download...
223 return Status::newFatal( 'tmp-write-error' );
224 }
225
226 if ( !$status->isOk() ) {
227 return $status;
228 }
229
230 return $status;
231 }
232
233 /**
234 * Wrapper around the parent function in order to defer verifying the
235 * upload until the file really has been fetched.
236 * @return array|mixed
237 */
238 public function verifyUpload() {
239 if ( $this->mAsync ) {
240 return array( 'status' => UploadBase::OK );
241 }
242 return parent::verifyUpload();
243 }
244
245 /**
246 * Wrapper around the parent function in order to defer checking warnings
247 * until the file really has been fetched.
248 * @return Array
249 */
250 public function checkWarnings() {
251 if ( $this->mAsync ) {
252 $this->mIgnoreWarnings = false;
253 return array();
254 }
255 return parent::checkWarnings();
256 }
257
258 /**
259 * Wrapper around the parent function in order to defer checking protection
260 * until we are sure that the file can actually be uploaded
261 * @param $user User
262 * @return bool|mixed
263 */
264 public function verifyTitlePermissions( $user ) {
265 if ( $this->mAsync ) {
266 return true;
267 }
268 return parent::verifyTitlePermissions( $user );
269 }
270
271 /**
272 * Wrapper around the parent function in order to defer uploading to the
273 * job queue for asynchronous uploads
274 * @param $comment string
275 * @param $pageText string
276 * @param $watch bool
277 * @param $user User
278 * @return Status
279 */
280 public function performUpload( $comment, $pageText, $watch, $user ) {
281 if ( $this->mAsync ) {
282 $sessionKey = $this->insertJob( $comment, $pageText, $watch, $user );
283
284 return Status::newFatal( 'async', $sessionKey );
285 }
286
287 return parent::performUpload( $comment, $pageText, $watch, $user );
288 }
289
290 /**
291 * @param $comment
292 * @param $pageText
293 * @param $watch
294 * @param $user User
295 * @return String
296 */
297 protected function insertJob( $comment, $pageText, $watch, $user ) {
298 $sessionKey = $this->stashSession();
299 $job = new UploadFromUrlJob( $this->getTitle(), array(
300 'url' => $this->mUrl,
301 'comment' => $comment,
302 'pageText' => $pageText,
303 'watch' => $watch,
304 'userName' => $user->getName(),
305 'leaveMessage' => $this->mAsync == 'async-leavemessage',
306 'ignoreWarnings' => $this->mIgnoreWarnings,
307 'sessionId' => session_id(),
308 'sessionKey' => $sessionKey,
309 ) );
310 $job->initializeSessionData();
311 $job->insert();
312 return $sessionKey;
313 }
314
315 }