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