6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
20 * Transfer class, wrapper for ftp/sftp/ssh
37 * Constructor - init some basic values
41 global $phpbb_root_path;
43 $this->file_perms = 0644;
44 $this->dir_perms = 0777;
46 // We use the store directory as temporary path to circumvent open basedir restrictions
47 $this->tmp_path = $phpbb_root_path . 'store/';
51 * Write file to location
53 function write_file($destination_file = '', $contents = '')
55 global $phpbb_root_path;
57 $destination_file = $this->root_path . str_replace($phpbb_root_path, '', $destination_file);
59 // need to create a temp file and then move that temp file.
60 // ftp functions can only move files around and can't create.
61 // This means that the users will need to have access to write
62 // temporary files or have write access on a folder within phpBB
63 // like the cache folder. If the user can't do either, then
64 // he/she needs to use the fsock ftp method
65 $temp_name = tempnam($this->tmp_path, 'transfer_');
68 $fp = @fopen($temp_name, 'w');
72 trigger_error('Unable to create temporary file ' . $temp_name, E_USER_ERROR);
75 @fwrite($fp, $contents);
78 $result = $this->overwrite_file($temp_name, $destination_file);
80 // remove temporary file now
87 * Moving file into location. If the destination file already exists it gets overwritten
89 function overwrite_file($source_file, $destination_file)
92 * @todo generally think about overwriting files in another way, by creating a temporary file and then renaming it
93 * @todo check for the destination file existance too
95 $this->_delete($destination_file);
96 $result = $this->_put($source_file, $destination_file);
97 $this->_chmod($destination_file, $this->file_perms);
103 * Create directory structure
105 function make_dir($dir)
107 global $phpbb_root_path;
109 $dir = str_replace($phpbb_root_path, '', $dir);
110 $dir = explode('/', $dir);
113 for ($i = 0, $total = sizeof($dir); $i < $total; $i++)
117 if (strpos($dir[$i], '.') === 0)
121 $cur_dir = $dir[$i] . '/';
123 if (!file_exists($phpbb_root_path . $dirs . $cur_dir))
125 // create the directory
126 $result = $this->_mkdir($dir[$i]);
127 $this->_chmod($dir[$i], $this->dir_perms);
130 $this->_chdir($this->root_path . $dirs . $dir[$i]);
134 $this->_chdir($this->root_path);
137 * @todo stack result into array to make sure every path creation has been taken care of
143 * Copy file from source location to destination location
145 function copy_file($from_loc, $to_loc)
147 global $phpbb_root_path;
149 $from_loc = ((strpos($from_loc, $phpbb_root_path) !== 0) ? $phpbb_root_path : '') . $from_loc;
150 $to_loc = $this->root_path . str_replace($phpbb_root_path, '', $to_loc);
152 if (!file_exists($from_loc))
157 $result = $this->overwrite_file($from_loc, $to_loc);
165 function delete_file($file)
167 global $phpbb_root_path;
169 $file = $this->root_path . str_replace($phpbb_root_path, '', $file);
171 return $this->_delete($file);
176 * @todo remove child directories?
178 function remove_dir($dir)
180 global $phpbb_root_path;
182 $dir = $this->root_path . str_replace($phpbb_root_path, '', $dir);
184 return $this->_rmdir($dir);
188 * Rename a file or folder
190 function rename($old_handle, $new_handle)
192 global $phpbb_root_path;
194 $old_handle = $this->root_path . str_replace($phpbb_root_path, '', $old_handle);
196 return $this->_rename($old_handle, $new_handle);
200 * Check if a specified file exist...
202 function file_exists($directory, $filename)
204 global $phpbb_root_path;
206 $directory = $this->root_path . str_replace($phpbb_root_path, '', $directory);
208 $this->_chdir($directory);
209 $result = $this->_ls();
211 if ($result !== false && is_array($result))
213 return (in_array($filename, $result)) ? true : false;
222 function open_session()
224 return $this->_init();
228 * Close current session
230 function close_session()
232 return $this->_close();
236 * Determine methods able to be used
241 $disabled_functions = explode(',', @ini_get('disable_functions'));
243 if (@extension_loaded('ftp'))
248 if (!in_array('fsockopen', $disabled_functions))
250 $methods[] = 'ftp_fsock';
261 class ftp extends transfer
264 * Standard parameters for FTP session
266 function ftp($host, $username, $password, $root_path, $port = 21, $timeout = 10)
270 $this->username = $username;
271 $this->password = $password;
272 $this->timeout = $timeout;
274 // Make sure $this->root_path is layed out the same way as the $user->page['root_script_path'] value (/ at the end)
275 $this->root_path = str_replace('\\', '/', $this->root_path);
277 if (!empty($root_path))
279 $this->root_path = (($root_path[0] != '/' ) ? '/' : '') . $root_path . ((substr($root_path, -1, 1) == '/') ? '' : '/');
282 // Init some needed values
283 transfer::transfer();
296 'host' => 'localhost',
297 'username' => 'anonymous',
299 'root_path' => $user->page['root_script_path'],
311 // connect to the server
312 $this->connection = @ftp_connect($this->host, $this->port, $this->timeout);
314 if (!$this->connection)
316 return 'ERR_CONNECTING_SERVER';
319 // login to the server
320 if (!@ftp_login($this->connection, $this->username, $this->password))
322 return 'ERR_UNABLE_TO_LOGIN';
325 // attempt to turn pasv mode on
326 @ftp_pasv($this->connection, true);
328 // change to the root directory
329 if (!$this->_chdir($this->root_path))
331 return 'ERR_CHANGING_DIRECTORY';
338 * Create Directory (MKDIR)
341 function _mkdir($dir)
343 return @ftp_mkdir($this->connection, $dir);
347 * Remove directory (RMDIR)
350 function _rmdir($dir)
352 return @ftp_rmdir($this->connection, $dir);
359 function _rename($old_handle, $new_handle)
361 return @ftp_rename($this->connection, $old_handle, $new_handle);
365 * Change current working directory (CHDIR)
368 function _chdir($dir = '')
370 if ($dir && $dir !== '/')
372 if (substr($dir, -1, 1) == '/')
374 $dir = substr($dir, 0, -1);
378 return @ftp_chdir($this->connection, $dir);
382 * change file permissions (CHMOD)
385 function _chmod($file, $perms)
387 if (function_exists('ftp_chmod'))
389 $err = @ftp_chmod($this->connection, $perms, $file);
393 // Unfortunatly CHMOD is not expecting an octal value...
394 // We need to transform the integer (which was an octal) to an octal representation (to get the int) and then pass as is. ;)
395 $chmod_cmd = 'CHMOD ' . base_convert($perms, 10, 8) . ' ' . $file;
396 $err = $this->_site($chmod_cmd);
403 * Upload file to location (PUT)
406 function _put($from_file, $to_file)
408 // get the file extension
409 $file_extension = strtolower(substr(strrchr($to_file, '.'), 1));
411 // We only use the BINARY file mode to cicumvent rewrite actions from ftp server (mostly linefeeds being replaced)
414 $to_dir = dirname($to_file);
415 $to_file = basename($to_file);
416 $this->_chdir($to_dir);
418 $result = @ftp_put($this->connection, $to_file, $from_file, $mode);
419 $this->_chdir($this->root_path);
425 * Delete file (DELETE)
428 function _delete($file)
430 return @ftp_delete($this->connection, $file);
434 * Close ftp session (CLOSE)
439 if (!$this->connection)
444 return @ftp_quit($this->connection);
448 * Return current working directory (CWD)
449 * At the moment not used by parent class
454 return @ftp_pwd($this->connection);
458 * Return list of files in a given directory (LS)
461 function _ls($dir = './')
463 $list = @ftp_nlist($this->connection, $dir);
465 // See bug #46295 - Some FTP daemons don't like './'
468 // Let's try some alternatives
469 $list = (empty($list)) ? @ftp_nlist($this->connection, '.') : $list;
470 $list = (empty($list)) ? @ftp_nlist($this->connection, '') : $list;
479 // Remove path if prepended
480 foreach ($list as $key => $item)
482 // Use same separator for item and dir
483 $item = str_replace('\\', '/', $item);
484 $dir = str_replace('\\', '/', $dir);
486 if (!empty($dir) && strpos($item, $dir) === 0)
488 $item = substr($item, strlen($dir));
498 * FTP SITE command (ftp-only function)
501 function _site($command)
503 return @ftp_site($this->connection, $command);
508 * FTP fsock transfer class
513 class ftp_fsock extends transfer
515 var $data_connection;
518 * Standard parameters for FTP session
520 function ftp_fsock($host, $username, $password, $root_path, $port = 21, $timeout = 10)
524 $this->username = $username;
525 $this->password = $password;
526 $this->timeout = $timeout;
528 // Make sure $this->root_path is layed out the same way as the $user->page['root_script_path'] value (/ at the end)
529 $this->root_path = str_replace('\\', '/', $this->root_path);
531 if (!empty($root_path))
533 $this->root_path = (($root_path[0] != '/' ) ? '/' : '') . $root_path . ((substr($root_path, -1, 1) == '/') ? '' : '/');
536 // Init some needed values
537 transfer::transfer();
550 'host' => 'localhost',
551 'username' => 'anonymous',
553 'root_path' => $user->page['root_script_path'],
568 // connect to the server
569 $this->connection = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
571 if (!$this->connection || !$this->_check_command())
573 return 'ERR_CONNECTING_SERVER';
576 @stream_set_timeout($this->connection, $this->timeout);
579 if (!$this->_send_command('USER', $this->username))
581 return 'ERR_UNABLE_TO_LOGIN';
584 if (!$this->_send_command('PASS', $this->password))
586 return 'ERR_UNABLE_TO_LOGIN';
589 // change to the root directory
590 if (!$this->_chdir($this->root_path))
592 return 'ERR_CHANGING_DIRECTORY';
599 * Create Directory (MKDIR)
602 function _mkdir($dir)
604 return $this->_send_command('MKD', $dir);
608 * Remove directory (RMDIR)
611 function _rmdir($dir)
613 return $this->_send_command('RMD', $dir);
620 function _rename($old_handle, $new_handle)
622 $this->_send_command('RNFR', $old_handle);
623 return $this->_send_command('RNTO', $new_handle);
627 * Change current working directory (CHDIR)
630 function _chdir($dir = '')
632 if ($dir && $dir !== '/')
634 if (substr($dir, -1, 1) == '/')
636 $dir = substr($dir, 0, -1);
640 return $this->_send_command('CWD', $dir);
644 * change file permissions (CHMOD)
647 function _chmod($file, $perms)
649 // Unfortunatly CHMOD is not expecting an octal value...
650 // We need to transform the integer (which was an octal) to an octal representation (to get the int) and then pass as is. ;)
651 return $this->_send_command('SITE CHMOD', base_convert($perms, 10, 8) . ' ' . $file);
655 * Upload file to location (PUT)
658 function _put($from_file, $to_file)
660 // We only use the BINARY file mode to cicumvent rewrite actions from ftp server (mostly linefeeds being replaced)
663 if (!$this->_send_command('TYPE', 'I'))
668 // open the connection to send file over
669 if (!$this->_open_data_connection())
674 $this->_send_command('STOR', $to_file, false);
677 $fp = @fopen($from_file, 'rb');
680 @fwrite($this->data_connection, @fread($fp, 4096));
685 $this->_close_data_connection();
687 return $this->_check_command();
691 * Delete file (DELETE)
694 function _delete($file)
696 return $this->_send_command('DELE', $file);
700 * Close ftp session (CLOSE)
705 if (!$this->connection)
710 return $this->_send_command('QUIT');
714 * Return current working directory (CWD)
715 * At the moment not used by parent class
720 $this->_send_command('PWD', '', false);
721 return preg_replace('#^[0-9]{3} "(.+)" .+\r\n#', '\\1', $this->_check_command(true));
725 * Return list of files in a given directory (LS)
728 function _ls($dir = './')
730 if (!$this->_open_data_connection())
735 $this->_send_command('NLST', $dir);
738 while (!@feof($this->data_connection))
740 $filename = preg_replace('#[\r\n]#', '', @fgets($this->data_connection, 512));
742 if ($filename !== '')
747 $this->_close_data_connection();
750 $this->_check_command();
752 // See bug #46295 - Some FTP daemons don't like './'
753 if ($dir === './' && empty($list))
755 // Let's try some alternatives
756 $list = $this->_ls('.');
760 $list = $this->_ls('');
766 // Remove path if prepended
767 foreach ($list as $key => $item)
769 // Use same separator for item and dir
770 $item = str_replace('\\', '/', $item);
771 $dir = str_replace('\\', '/', $dir);
773 if (!empty($dir) && strpos($item, $dir) === 0)
775 $item = substr($item, strlen($dir));
785 * Send a command to server (FTP fsock only function)
788 function _send_command($command, $args = '', $check = true)
792 $command = "$command $args";
795 fwrite($this->connection, $command . "\r\n");
797 if ($check === true && !$this->_check_command())
806 * Opens a connection to send data (FTP fosck only function)
809 function _open_data_connection()
811 // Try to find out whether we have a IPv4 or IPv6 (control) connection
812 if (function_exists('stream_socket_get_name'))
814 $socket_name = stream_socket_get_name($this->connection, true);
815 $server_ip = substr($socket_name, 0, strrpos($socket_name, ':'));
818 if (!isset($server_ip) || preg_match(get_preg_expression('ipv4'), $server_ip))
821 $this->_send_command('PASV', '', false);
823 if (!$ip_port = $this->_check_command(true))
828 // open the connection to start sending the file
829 if (!preg_match('#[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+#', $ip_port, $temp))
835 $temp = explode(',', $temp[0]);
836 $server_ip = $temp[0] . '.' . $temp[1] . '.' . $temp[2] . '.' . $temp[3];
837 $server_port = $temp[4] * 256 + $temp[5];
841 // Extended Passive Mode - RFC2428
842 $this->_send_command('EPSV', '', false);
844 if (!$epsv_response = $this->_check_command(true))
849 // Response looks like "229 Entering Extended Passive Mode (|||12345|)"
850 // where 12345 is the tcp port for the data connection
851 if (!preg_match('#\(\|\|\|([0-9]+)\|\)#', $epsv_response, $match))
855 $server_port = (int) $match[1];
857 // fsockopen expects IPv6 address in square brackets
858 $server_ip = "[$server_ip]";
864 if (!$this->data_connection = @fsockopen($server_ip, $server_port, $errno, $errstr, $this->timeout))
868 @stream_set_timeout($this->data_connection, $this->timeout);
874 * Closes a connection used to send data
877 function _close_data_connection()
879 return @fclose($this->data_connection);
883 * Check to make sure command was successful (FTP fsock only function)
886 function _check_command($return = false)
892 $result = @fgets($this->connection, 512);
893 $response .= $result;
895 while (substr($result, 3, 1) !== ' ');
897 if (!preg_match('#^[123]#', $response))
902 return ($return) ? $response : true;