* Disable this entirely unless curl is available so we don't blow up. Needs a-fixin
[lhc/web/wiklou.git] / includes / UploadFromUrl.php
1 <?php
2
3
4 class UploadFromUrl extends UploadBase {
5 static function isAllowed( $user ) {
6 if( !$user->isAllowed( 'upload_by_url' ) )
7 return 'upload_by_url';
8 return parent::isAllowed( $user );
9 }
10 static function isEnabled() {
11 global $wgAllowCopyUploads;
12 return $wgAllowCopyUploads && parent::isEnabled() && function_exists( 'curl_init' );
13 }
14
15 function initialize( $name, $url ) {
16 global $wgTmpDirectory;
17 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
18 $this-initialize( $name, $local_file, 0, true );
19
20 $this->mUrl = trim( $url );
21 }
22
23 /**
24 * Do the real fetching stuff
25 */
26 function fetchFile() {
27 if( stripos($this->mUrl, 'http://') !== 0 && stripos($this->mUrl, 'ftp://') !== 0 ) {
28 return array(
29 'status' => self::BEFORE_PROCESSING,
30 'error' => 'upload-proto-error',
31 );
32 }
33 $res = $this->curlCopy();
34 if( $res !== true ) {
35 return array(
36 'status' => self::BEFORE_PROCESSING,
37 'error' => $res,
38 );
39 }
40 return self::OK;
41 }
42
43 /**
44 * Safe copy from URL
45 * Returns true if there was an error, false otherwise
46 */
47 private function curlCopy() {
48 global $wgUser, $wgOut;
49
50 # Open temporary file
51 $this->mCurlDestHandle = @fopen( $this->mTempPath, "wb" );
52 if( $this->mCurlDestHandle === false ) {
53 # Could not open temporary file to write in
54 return 'upload-file-error';
55 }
56
57 $opts = array( CURLOPT_HTTP_VERSION => 1.0,
58 CURLOPT_LOW_SPEED_LIMIT => 512,
59 CURLOPT_WRITEFUNCTION => array( $this, 'uploadCurlCallback' )
60 );
61 Http::get( $this->mUrl, 10, $opts );
62
63 fclose( $this->mCurlDestHandle );
64 unset( $this->mCurlDestHandle );
65
66 if( $this->curlErrno !== CURLE_OK )
67 return "upload-curl-error" . $this->curlErrno;
68
69 return true;
70 }
71
72 /**
73 * Callback function for CURL-based web transfer
74 * Write data to file unless we've passed the length limit;
75 * if so, abort immediately.
76 * @access private
77 */
78 function uploadCurlCallback( $ch, $data ) {
79 global $wgMaxUploadSize;
80 $length = strlen( $data );
81 $this->mFileSize += $length;
82 if( $this->mFileSize > $wgMaxUploadSize ) {
83 return 0;
84 }
85 fwrite( $this->mCurlDestHandle, $data );
86 $this->curlErrno = curl_errno( $ch );
87 return $length;
88 }
89 }