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