File: transfer.php

package info (click to toggle)
extplorer 2.1.0b6%2Bdfsg.2-1%2Bsqueeze2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 2,124 kB
  • ctags: 2,046
  • sloc: php: 14,873; xml: 884; makefile: 122; sh: 35
file content (427 lines) | stat: -rw-r--r-- 11,083 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
<?php
// ensure this file is being included by a parent file
if( !defined( '_JEXEC' ) && !defined( '_VALID_MOS' ) ) die( 'Restricted access' );
/**
 * @version $Id: transfer.php 143 2009-04-01 18:48:16Z soeren $
 * @package eXtplorer
 * @copyright soeren 2007-2009
 * @author The eXtplorer project (http://sourceforge.net/projects/extplorer)
 * @license
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU General Public License Version 2 or later (the "GPL"), in
 * which case the provisions of the GPL are applicable instead of
 * those above. If you wish to allow use of your version of this file only
 * under the terms of the GPL and not to allow others to use
 * your version of this file under the MPL, indicate your decision by
 * deleting  the provisions above and replace  them with the notice and
 * other provisions required by the GPL.  If you do not delete
 * the provisions above, a recipient may use your version of this file
 * under either the MPL or the GPL."
 * 
*/
/**
 * Transfer file(s) from another server to this one
 *
 */

class ext_Transfer extends ext_Action {
	var $_downloadMethods;

	function execAction( $dir ) {

		if(($GLOBALS["permissions"]&01)!=01) {
			ext_Result::sendResult('upload', false, $GLOBALS["error_msg"]["accessfunc"]);
		}
		$this->_downloadMethods = array(
			new CurlDownloader(),
			new WgetDownloader(),
			new FopenDownloader(),
			new FsockopenDownloader()
		);
		//DEBUG ext_Result::sendResult('transfer', false, $dir );
		// Execute
		if(isset($GLOBALS['__POST']["confirm"]) && $GLOBALS['__POST']["confirm"]=="true") {

			$cnt=count($GLOBALS['__POST']['userfile']);
			$err=false;
			foreach($this->_downloadMethods as $method ) {
				if( $method->isSupported()) {
					$downloader =& $method;
					break;
				}
			}
			// upload files & check for errors
			for($i=0;$i<$cnt;$i++) {
				$errors[$i]=NULL;

				$items[$i] = stripslashes(basename($GLOBALS['__POST']['userfile'][$i]));

				$abs = get_abs_item($dir,$items[$i]);

				if($items[$i]=="") continue;
				if(@file_exists($abs) && empty( $_REQUEST['overwrite_files'])) {
					$errors[$i]=$GLOBALS["error_msg"]["itemdoesexist"];
					$err=true;	continue;
				}

				// Upload
				$ok = $downloader->download($GLOBALS['__POST']['userfile'][$i], $abs);
				if($ok===true ) {
					$mode = ext_isFTPMode() ? 644 : 0644;
					@$GLOBALS['ext_File']->chmod( $abs, $mode );
				}
				else {
					$errors[$i]=$ok;
					$err=true;	continue;
				}
			}

			if($err) {			// there were errors
				$err_msg="";
				for($i=0;$i<$cnt;$i++) {
					if($errors[$i]==NULL) continue;
					$err_msg .= $items[$i]." : ".$errors[$i]."\n";
				}
				ext_Result::sendResult('transfer', false, $err_msg);
			}

			ext_Result::sendResult('transfer', true, ext_Lang::msg('transfer_completed'));
			return;
		}
	}
}
/**
 * Abstract DownloadMethod Class for implementing special types
 * @abstract 
 *
 */
class DownloadMethod {
	function download($url, $outputFile) {
		return false;
	}

	function isSupported() {
		return false;
	}

	function getName() {
		return '';
	}
}

class WgetDownloader extends DownloadMethod {
	function download($url, $outputFile) {
		$status = 0;
		$output = array();
		$wget = getBinaryPath('wget');
		exec("$wget -O$outputFile $url ", $output, $status);
		if ($status) {
			$msg = 'exec returned an error status ';
			$msg .= is_array($output) ? implode('<br>', $output) : '';
			return $msg;
		}
		return true;
	}

	function isSupported() {
		return isBinaryAvailable('wget');
	}

	function getName() {
		return 'Download with Wget';
	}
}

class FopenDownloader extends DownloadMethod {
	function download($url, $outputFile) {
		if (!is_writable( dirname( $outputFile ))) {
			return 'Unable to write to current working directory';
		}
		$start =time();

		@set_time_limit( 900 );

		$fh = @fopen($url, 'rb');
		if (empty($fh)) {
			return 'Unable to open url';
		}
		$ofh = @fopen($outputFile, 'wb');
		if (!$ofh) {
			fclose($fh);
			return 'Unable to open output file in writing mode';
		}

		$failed = $results = false;
		while (!feof($fh) && !$failed) {
			$buf = fread($fh, 4096);
			if (!$buf) {
				$results = 'Error during download';
				$failed = true;
				break;
			}
			if (fwrite($ofh, $buf) != strlen($buf)) {
				$failed = true;
				$results = 'Error during writing';
				break;
			}
			if (time() - $start > 55) {

				$start = time();
			}
		}
		fclose($ofh);
		fclose($fh);
		if ($failed) {
			return $results;
		}

		return true;
	}

	function isSupported() {
		$actual = ini_get('allow_url_fopen');
		if (in_array($actual, array(1, 'On', 'on')) && isPhpFunctionSupported('fopen')) {
			return true;
		}

		return false;
	}

	function getName() {
		return 'Download with PHP fopen()';
	}
}

class FsockopenDownloader extends DownloadMethod {
	function download($url, $outputFile, $maxRedirects=10) {
		/* Code from WebHelper_simple.class */

		if ($maxRedirects < 0) {
			return "Error too many redirects. Last URL: $url";
		}

		$components = parse_url($url);
		$port = empty($components['port']) ? 80 : $components['port'];

		$errno = $errstr = null;
		$fd = @fsockopen($components['host'], $port, $errno, $errstr, 2);
		if (empty($fd)) {
			return "Error $errno: '$errstr' retrieving $url";
		}

		$get = $components['path'];
		if (!empty($components['query'])) {
			$get .= '?' . $components['query'];
		}

		$start = time();

		/* Read the web file into a buffer */
		$ok = fwrite($fd, sprintf("GET %s HTTP/1.0\r\n" .
		"Host: %s\r\n" .
		"\r\n",
		$get,
		$components['host']));
		if (!$ok) {
			return 'Download request failed (fwrite)';
		}
		$ok = fflush($fd);
		if (!$ok) {
			return 'Download request failed (fflush)';
		}

		/*
		* Read the response code. fgets stops after newlines.
		* The first line contains only the status code (200, 404, etc.).
		*/
		$headers = array();
		$response = trim(fgets($fd, 4096));

		/* Jump over the headers but follow redirects */
		while (!feof($fd)) {
			$line = trim(fgets($fd, 4096));
			if (empty($line)) {
				break;
			}

			/* Normalize the line endings */
			$line = str_replace("\r", '', $line);
			list ($key, $value) = explode(':', $line, 2);
			if (trim($key) == 'Location') {
				fclose($fd);
				return $this->download(trim($value), $outputFile, --$maxRedirects);
			}
		}

		$success = false;
		$ofd = fopen($outputFile, 'wb');
		if ($ofd) {
			/* Read the body */
			$failed = false;
			while (!feof($fd) && !$failed) {
				$buf = fread($fd, 4096);
				if (fwrite($ofd, $buf) != strlen($buf)) {
					$failed = true;
					break;
				}
				if (time() - $start > 55) {
					set_time_limit(600);
					$start = time();
				}
			}
			fclose($ofd);
			if (!$failed) {
				$success = true;
			}
		} else {
			return "Could not open $outputFile in write mode";
		}
		fclose($fd);

		/* if the HTTP response code did not begin with a 2 this request was not successful */
		if (!preg_match("/^HTTP\/\d+\.\d+\s2\d{2}/", $response)) {
			return "Download failed with HTTP status: $response";
		}

		return true;
	}

	function isSupported() {
		return isPhpFunctionSupported('fsockopen');
	}

	function getName() {
		return 'Download with PHP fsockopen()';
	}
}

class CurlDownloader extends DownloadMethod {
	function download($url, $outputFile) {
		$ch = curl_init();
		$ofh = fopen($outputFile, 'wb');
		if (!$ofh) {
			fclose($ch);
			return 'Unable to open output file in writing mode';
		}

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FILE, $ofh);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

		curl_exec($ch);

		$errorString = curl_error($ch);
		$errorNumber = curl_errno($ch);
		curl_close($ch);

		if ($errorNumber != 0) {
			if (!empty($errorString)) {
				return $errorString;
			} else {
				return 'CURL download failed';
			}
		}

		return true;
	}

	function isSupported() {
		foreach (array('curl_init', 'curl_setopt', 'curl_exec', 'curl_close', 'curl_error') as $functionName) {
			if (!isPhpFunctionSupported($functionName)) {
				return false;
			}
		}
		if( ini_get('open_basedir') != '' || strtolower(ini_get('safe_mode')) == 'on') {
			return false;
		}
		return true;
	}

	function getName() {
		return 'Download with PHP cURL()';
	}
}
function isPhpFunctionSupported($functionName) {
	if (in_array($functionName, split(',\s*', ini_get('disable_functions'))) || !function_exists($functionName)) {
		return false;
	} else {
		return true;
	}
}
/* Check if a specific command line tool is available */
function isBinaryAvailable($binaryName) {
	$binaryPath = getBinaryPath($binaryName);
	return !empty($binaryPath);
}

/* Return the path to a binary or false if it's not available */
function getBinaryPath($binaryName) {
	if (!isPhpFunctionSupported('exec')) {
		return false;
	}

	/* First try 'which' */
	$ret = array();
	exec('which ' . $binaryName, $ret);
	if (strpos(join(' ',$ret), $binaryName) !== false && @is_executable(join('',$ret))) {
		return $binaryName; // it's in the path
	}

	/* Try a bunch of likely seeming paths to see if any of them work. */
	$paths = array();
	if (!strncasecmp(PHP_OS, 'win', 3)) {
		$separator = ';';
		$slash = "\\";
		$extension = '.exe';
		$paths[] = "C:\\Program Files\\$binaryName\\";
		$paths[] = "C:\\apps\$binaryName\\";
		$paths[] = "C:\\$binaryName\\";
	} else {
		$separator = ':';
		$slash = "/";
		$extension = '';
		$paths[] = '/usr/bin/';
		$paths[] = '/usr/local/bin/';
		$paths[] = '/bin/';
		$paths[] = '/sw/bin/';
	}
	$paths[] = './';

	foreach (explode($separator, getenv('PATH')) as $path) {
		$path = trim($path);
		if (empty($path)) {
			continue;
		}
		if ($path{strlen($path)-1} != $slash) {
			$path .= $slash;
		}
		$paths[] = $path;
	}

	/* Now try each path in turn to see which ones work */
	foreach ($paths as $path) {
		$execPath = $path . $binaryName . $extension;
		if (@file_exists($execPath) && @is_executable($execPath)) {
			/* We have a winner */
			return $execPath;
		}
	}

	return false;
}
?>