first commit

This commit is contained in:
2024-11-17 19:56:17 +01:00
commit 81b1185f8e
6599 changed files with 832395 additions and 0 deletions

View File

@@ -0,0 +1,884 @@
<?php
/*
* This file is part of the `nicolab/php-ftp-client` package.
*
* (c) Nicolas Tallefourtane <dev@nicolab.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
use \Countable;
/**
* The FTP and SSL-FTP client for PHP.
*
* @method bool alloc() alloc(int $filesize, string &$result = null) Allocates space for a file to be uploaded
* @method bool cdup() cdup() Changes to the parent directory
* @method bool chdir() chdir(string $directory) Changes the current directory on a FTP server
* @method int chmod() chmod(int $mode, string $filename) Set permissions on a file via FTP
* @method bool delete() delete(string $path) Deletes a file on the FTP server
* @method bool exec() exec(string $command) Requests execution of a command on the FTP server
* @method bool fget() fget(resource $handle, string $remote_file, int $mode, int $resumepos = 0) Downloads a file from the FTP server and saves to an open file
* @method bool fput() fput(string $remote_file, resource $handle, int $mode, int $startpos = 0) Uploads from an open file to the FTP server
* @method mixed get_option() get_option(int $option) Retrieves various runtime behaviours of the current FTP stream
* @method bool get() get(string $local_file, string $remote_file, int $mode, int $resumepos = 0) Downloads a file from the FTP server
* @method int mdtm() mdtm(string $remote_file) Returns the last modified time of the given file
* @method int nb_continue() nb_continue() Continues retrieving/sending a file (non-blocking)
* @method int nb_fget() nb_fget(resource $handle, string $remote_file, int $mode, int $resumepos = 0) Retrieves a file from the FTP server and writes it to an open file (non-blocking)
* @method int nb_fput() nb_fput(string $remote_file, resource $handle, int $mode, int $startpos = 0) Stores a file from an open file to the FTP server (non-blocking)
* @method int nb_get() nb_get(string $local_file, string $remote_file, int $mode, int $resumepos = 0) Retrieves a file from the FTP server and writes it to a local file (non-blocking)
* @method int nb_put() nb_put(string $remote_file, string $local_file, int $mode, int $startpos = 0) Stores a file on the FTP server (non-blocking)
* @method bool pasv() pasv(bool $pasv) Turns passive mode on or off
* @method bool put() put(string $remote_file, string $local_file, int $mode, int $startpos = 0) Uploads a file to the FTP server
* @method string pwd() pwd() Returns the current directory name
* @method bool quit() quit() Closes an FTP connection
* @method array raw() raw(string $command) Sends an arbitrary command to an FTP server
* @method bool rename() rename(string $oldname, string $newname) Renames a file or a directory on the FTP server
* @method bool set_option() set_option(int $option, mixed $value) Set miscellaneous runtime FTP options
* @method bool site() site(string $command) Sends a SITE command to the server
* @method int size() size(string $remote_file) Returns the size of the given file
* @method string systype() systype() Returns the system type identifier of the remote FTP server
*
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpClient implements Countable
{
/**
* The connection with the server.
*
* @var resource
*/
protected $conn;
/**
* PHP FTP functions wrapper.
*
* @var FtpWrapper
*/
private $ftp;
/**
* Constructor.
*
* @param resource|null $connection
* @throws FtpException If FTP extension is not loaded.
*/
public function __construct($connection = null)
{
if (!extension_loaded('ftp')) {
throw new FtpException('FTP extension is not loaded!');
}
if ($connection) {
$this->conn = $connection;
}
$this->setWrapper(new FtpWrapper($this->conn));
}
/**
* Close the connection when the object is destroyed.
*/
public function __destruct()
{
if ($this->conn) {
$this->ftp->close();
}
}
/**
* Call an internal method or a FTP method handled by the wrapper.
*
* Wrap the FTP PHP functions to call as method of FtpClient object.
* The connection is automaticaly passed to the FTP PHP functions.
*
* @param string $method
* @param array $arguments
* @return mixed
* @throws FtpException When the function is not valid
*/
public function __call($method, array $arguments)
{
return $this->ftp->__call($method, $arguments);
}
/**
* Overwrites the PHP limit
*
* @param string|null $memory The memory limit, if null is not modified
* @param int $time_limit The max execution time, unlimited by default
* @param bool $ignore_user_abort Ignore user abort, true by default
* @return FtpClient
*/
public function setPhpLimit($memory = null, $time_limit = 0, $ignore_user_abort = true)
{
if (null !== $memory) {
ini_set('memory_limit', $memory);
}
ignore_user_abort(true);
set_time_limit($time_limit);
return $this;
}
/**
* Get the help information of the remote FTP server.
*
* @return array
*/
public function help()
{
return $this->ftp->raw('help');
}
/**
* Open a FTP connection.
*
* @param string $host
* @param bool $ssl
* @param int $port
* @param int $timeout
*
* @return FTPClient
* @throws FtpException If unable to connect
*/
public function connect($host, $ssl = false, $port = 21, $timeout = 90)
{
if ($ssl) {
$this->conn = @$this->ftp->ssl_connect($host, $port, $timeout);
} else {
$this->conn = @$this->ftp->connect($host, $port, $timeout);
}
if (!$this->conn) {
throw new FtpException('Unable to connect');
}
return $this;
}
/**
* Closes the current FTP connection.
*
* @return bool
*/
public function close()
{
if ($this->conn) {
$this->ftp->close();
$this->conn = null;
}
}
/**
* Get the connection with the server.
*
* @return resource
*/
public function getConnection()
{
return $this->conn;
}
/**
* Get the wrapper.
*
* @return FtpWrapper
*/
public function getWrapper()
{
return $this->ftp;
}
/**
* Logs in to an FTP connection.
*
* @param string $username
* @param string $password
*
* @return FtpClient
* @throws FtpException If the login is incorrect
*/
public function login($username = 'anonymous', $password = '')
{
$result = $this->ftp->login($username, $password);
if ($result === false) {
throw new FtpException('Login incorrect');
}
return $this;
}
/**
* Returns the last modified time of the given file.
* Return -1 on error
*
* @param string $remoteFile
* @param string|null $format
*
* @return int
*/
public function modifiedTime($remoteFile, $format = null)
{
$time = $this->ftp->mdtm($remoteFile);
if ($time !== -1 && $format !== null) {
return date($format, $time);
}
return $time;
}
/**
* Changes to the parent directory.
*
* @throws FtpException
* @return FtpClient
*/
public function up()
{
$result = @$this->ftp->cdup();
if ($result === false) {
throw new FtpException('Unable to get parent folder');
}
return $this;
}
/**
* Returns a list of files in the given directory.
*
* @param string $directory The directory, by default is "." the current directory
* @param bool $recursive
* @param callable $filter A callable to filter the result, by default is asort() PHP function.
* The result is passed in array argument,
* must take the argument by reference !
* The callable should proceed with the reference array
* because is the behavior of several PHP sorting
* functions (by reference ensure directly the compatibility
* with all PHP sorting functions).
*
* @return array
* @throws FtpException If unable to list the directory
*/
public function nlist($directory = '.', $recursive = false, $filter = 'sort')
{
if (!$this->isDir($directory)) {
throw new FtpException('"'.$directory.'" is not a directory');
}
$files = $this->ftp->nlist($directory);
if ($files === false) {
throw new FtpException('Unable to list directory');
}
$result = array();
$dir_len = strlen($directory);
// if it's the current
if (false !== ($kdot = array_search('.', $files))) {
unset($files[$kdot]);
}
// if it's the parent
if(false !== ($kdot = array_search('..', $files))) {
unset($files[$kdot]);
}
if (!$recursive) {
foreach ($files as $file) {
$result[] = $directory.'/'.$file;
}
// working with the reference (behavior of several PHP sorting functions)
$filter($result);
return $result;
}
// utils for recursion
$flatten = function (array $arr) use (&$flatten) {
$flat = [];
foreach ($arr as $k => $v) {
if (is_array($v)) {
$flat = array_merge($flat, $flatten($v));
} else {
$flat[] = $v;
}
}
return $flat;
};
foreach ($files as $file) {
$file = $directory.'/'.$file;
// if contains the root path (behavior of the recursivity)
if (0 === strpos($file, $directory, $dir_len)) {
$file = substr($file, $dir_len);
}
if ($this->isDir($file)) {
$result[] = $file;
$items = $flatten($this->nlist($file, true, $filter));
foreach ($items as $item) {
$result[] = $item;
}
} else {
$result[] = $file;
}
}
$result = array_unique($result);
$filter($result);
return $result;
}
/**
* Creates a directory.
*
* @see FtpClient::rmdir()
* @see FtpClient::remove()
* @see FtpClient::put()
* @see FtpClient::putAll()
*
* @param string $directory The directory
* @param bool $recursive
* @return array
*/
public function mkdir($directory, $recursive = false)
{
if (!$recursive or $this->isDir($directory)) {
return $this->ftp->mkdir($directory);
}
$result = false;
$pwd = $this->ftp->pwd();
$parts = explode('/', $directory);
foreach ($parts as $part) {
if (!@$this->ftp->chdir($part)) {
$result = $this->ftp->mkdir($part);
$this->ftp->chdir($part);
}
}
$this->ftp->chdir($pwd);
return $result;
}
/**
* Remove a directory.
*
* @see FtpClient::mkdir()
* @see FtpClient::cleanDir()
* @see FtpClient::remove()
* @see FtpClient::delete()
* @param string $directory
* @param bool $recursive Forces deletion if the directory is not empty
* @return bool
* @throws FtpException If unable to list the directory to remove
*/
public function rmdir($directory, $recursive = true)
{
if ($recursive) {
$files = $this->nlist($directory, false, 'rsort');
// remove children
foreach ($files as $file) {
$this->remove($file, true);
}
}
// remove the directory
return $this->ftp->rmdir($directory);
}
/**
* Empty directory.
*
* @see FtpClient::remove()
* @see FtpClient::delete()
* @see FtpClient::rmdir()
*
* @param string $directory
* @return bool
*/
public function cleanDir($directory)
{
if(!$files = $this->nlist($directory)) {
return $this->isEmpty($directory);
}
// remove children
foreach ($files as $file) {
$this->remove($file, true);
}
return $this->isEmpty($directory);
}
/**
* Remove a file or a directory.
*
* @see FtpClient::rmdir()
* @see FtpClient::cleanDir()
* @see FtpClient::delete()
* @param string $path The path of the file or directory to remove
* @param bool $recursive Is effective only if $path is a directory, {@see FtpClient::rmdir()}
* @return bool
*/
public function remove($path, $recursive = false)
{
try {
if (@$this->ftp->delete($path)
or ($this->isDir($path) and @$this->rmdir($path, $recursive))) {
return true;
}
return false;
} catch (\Exception $e) {
return false;
}
}
/**
* Check if a directory exist.
*
* @param string $directory
* @return bool
* @throws FtpException
*/
public function isDir($directory)
{
$pwd = $this->ftp->pwd();
if ($pwd === false) {
throw new FtpException('Unable to resolve the current directory');
}
if (@$this->ftp->chdir($directory)) {
$this->ftp->chdir($pwd);
return true;
}
$this->ftp->chdir($pwd);
return false;
}
/**
* Check if a directory is empty.
*
* @param string $directory
* @return bool
*/
public function isEmpty($directory)
{
return $this->count($directory, null, false) === 0 ? true : false;
}
/**
* Scan a directory and returns the details of each item.
*
* @see FtpClient::nlist()
* @see FtpClient::rawlist()
* @see FtpClient::parseRawList()
* @see FtpClient::dirSize()
* @param string $directory
* @param bool $recursive
* @return array
*/
public function scanDir($directory = '.', $recursive = false)
{
return $this->parseRawList($this->rawlist($directory, $recursive));
}
/**
* Returns the total size of the given directory in bytes.
*
* @param string $directory The directory, by default is the current directory.
* @param bool $recursive true by default
* @return int The size in bytes.
*/
public function dirSize($directory = '.', $recursive = true)
{
$items = $this->scanDir($directory, $recursive);
$size = 0;
foreach ($items as $item) {
$size += (int) $item['size'];
}
return $size;
}
/**
* Count the items (file, directory, link, unknown).
*
* @param string $directory The directory, by default is the current directory.
* @param string|null $type The type of item to count (file, directory, link, unknown)
* @param bool $recursive true by default
* @return int
*/
public function count($directory = '.', $type = null, $recursive = true)
{
$items = (null === $type ? $this->nlist($directory, $recursive)
: $this->scanDir($directory, $recursive));
$count = 0;
foreach ($items as $item) {
if (null === $type or $item['type'] == $type) {
$count++;
}
}
return $count;
}
/**
* Uploads a file to the server from a string.
*
* @param string $remote_file
* @param string $content
* @return FtpClient
* @throws FtpException When the transfer fails
*/
public function putFromString($remote_file, $content)
{
$handle = fopen('php://temp', 'w');
fwrite($handle, $content);
rewind($handle);
if ($this->ftp->fput($remote_file, $handle, FTP_BINARY)) {
return $this;
}
throw new FtpException('Unable to put the file "'.$remote_file.'"');
}
/**
* Uploads a file to the server.
*
* @param string $local_file
* @return FtpClient
* @throws FtpException When the transfer fails
*/
public function putFromPath($local_file)
{
$remote_file = basename($local_file);
$handle = fopen($local_file, 'r');
if ($this->ftp->fput($remote_file, $handle, FTP_BINARY)) {
rewind($handle);
return $this;
}
throw new FtpException(
'Unable to put the remote file from the local file "'.$local_file.'"'
);
}
/**
* Upload files.
*
* @param string $source_directory
* @param string $target_directory
* @param int $mode
* @return FtpClient
*/
public function putAll($source_directory, $target_directory, $mode = FTP_BINARY)
{
$d = dir($source_directory);
// do this for each file in the directory
while ($file = $d->read()) {
// to prevent an infinite loop
if ($file != "." && $file != "..") {
// do the following if it is a directory
if (is_dir($source_directory.'/'.$file)) {
if (!$this->isDir($target_directory.'/'.$file)) {
// create directories that do not yet exist
$this->ftp->mkdir($target_directory.'/'.$file);
}
// recursive part
$this->putAll(
$source_directory.'/'.$file, $target_directory.'/'.$file,
$mode
);
} else {
// put the files
$this->ftp->put(
$target_directory.'/'.$file, $source_directory.'/'.$file,
$mode
);
}
}
}
return $this;
}
/**
* Returns a detailed list of files in the given directory.
*
* @see FtpClient::nlist()
* @see FtpClient::scanDir()
* @see FtpClient::dirSize()
* @param string $directory The directory, by default is the current directory
* @param bool $recursive
* @return array
* @throws FtpException
*/
public function rawlist($directory = '.', $recursive = false)
{
if (!$this->isDir($directory)) {
throw new FtpException('"'.$directory.'" is not a directory.');
}
$list = $this->ftp->rawlist($directory);
$items = array();
if (!$list) {
return $items;
}
if (false == $recursive) {
foreach ($list as $path => $item) {
$chunks = preg_split("/\s+/", $item);
// if not "name"
if (empty($chunks[8]) || $chunks[8] == '.' || $chunks[8] == '..') {
continue;
}
$path = $directory.'/'.$chunks[8];
if (isset($chunks[9])) {
$nbChunks = count($chunks);
for ($i = 9; $i < $nbChunks; $i++) {
$path .= ' '.$chunks[$i];
}
}
if (substr($path, 0, 2) == './') {
$path = substr($path, 2);
}
$items[ $this->rawToType($item).'#'.$path ] = $item;
}
return $items;
}
$path = '';
foreach ($list as $item) {
$len = strlen($item);
if (!$len
// "."
|| ($item[$len-1] == '.' && $item[$len-2] == ' '
// ".."
or $item[$len-1] == '.' && $item[$len-2] == '.' && $item[$len-3] == ' ')
){
continue;
}
$chunks = preg_split("/\s+/", $item);
// if not "name"
if (empty($chunks[8]) || $chunks[8] == '.' || $chunks[8] == '..') {
continue;
}
$path = $directory.'/'.$chunks[8];
if (isset($chunks[9])) {
$nbChunks = count($chunks);
for ($i = 9; $i < $nbChunks; $i++) {
$path .= ' '.$chunks[$i];
}
}
if (substr($path, 0, 2) == './') {
$path = substr($path, 2);
}
$items[$this->rawToType($item).'#'.$path] = $item;
if ($item[0] == 'd') {
$sublist = $this->rawlist($path, true);
foreach ($sublist as $subpath => $subitem) {
$items[$subpath] = $subitem;
}
}
}
return $items;
}
/**
* Parse raw list.
*
* @see FtpClient::rawlist()
* @see FtpClient::scanDir()
* @see FtpClient::dirSize()
* @param array $rawlist
* @return array
*/
public function parseRawList(array $rawlist)
{
$items = array();
$path = '';
foreach ($rawlist as $key => $child) {
$chunks = preg_split("/\s+/", $child);
if (isset($chunks[8]) && ($chunks[8] == '.' or $chunks[8] == '..')) {
continue;
}
if (count($chunks) === 1) {
$len = strlen($chunks[0]);
if ($len && $chunks[0][$len-1] == ':') {
$path = substr($chunks[0], 0, -1);
}
continue;
}
$item = [
'permissions' => $chunks[0],
'number' => $chunks[1],
'owner' => $chunks[2],
'group' => $chunks[3],
'size' => $chunks[4],
'month' => $chunks[5],
'day' => $chunks[6],
'time' => $chunks[7],
'name' => $chunks[8],
'type' => $this->rawToType($chunks[0]),
];
unset($chunks[0]);
unset($chunks[1]);
unset($chunks[2]);
unset($chunks[3]);
unset($chunks[4]);
unset($chunks[5]);
unset($chunks[6]);
unset($chunks[7]);
$item['name'] = implode(' ', $chunks);
if ($item['type'] == 'link') {
$item['target'] = $chunks[10]; // 9 is "->"
}
// if the key is not the path, behavior of ftp_rawlist() PHP function
if (is_int($key) || false === strpos($key, $item['name'])) {
array_splice($chunks, 0, 8);
$key = $item['type'].'#'
.($path ? $path.'/' : '')
.implode(" ", $chunks);
if ($item['type'] == 'link') {
// get the first part of 'link#the-link.ext -> /path/of/the/source.ext'
$exp = explode(' ->', $key);
$key = rtrim($exp[0]);
}
$items[$key] = $item;
} else {
// the key is the path, behavior of FtpClient::rawlist() method()
$items[$key] = $item;
}
}
return $items;
}
/**
* Convert raw info (drwx---r-x ...) to type (file, directory, link, unknown).
* Only the first char is used for resolving.
*
* @param string $permission Example : drwx---r-x
*
* @return string The file type (file, directory, link, unknown)
* @throws FtpException
*/
public function rawToType($permission)
{
if (!is_string($permission)) {
throw new FtpException('The "$permission" argument must be a string, "'
.gettype($permission).'" given.');
}
if (empty($permission[0])) {
return 'unknown';
}
switch ($permission[0]) {
case '-':
return 'file';
case 'd':
return 'directory';
case 'l':
return 'link';
default:
return 'unknown';
}
}
/**
* Set the wrapper which forward the PHP FTP functions to use in FtpClient instance.
*
* @param FtpWrapper $wrapper
* @return FtpClient
*/
protected function setWrapper(FtpWrapper $wrapper)
{
$this->ftp = $wrapper;
return $this;
}
}

View File

@@ -0,0 +1,20 @@
<?php
/*
* This file is part of the `nicolab/php-ftp-client` package.
*
* (c) Nicolas Tallefourtane <dev@nicolab.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
/**
* The FtpException class.
* Exception thrown if an error on runtime of the FTP client occurs.
* @inheritDoc
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpException extends \Exception {}

View File

@@ -0,0 +1,115 @@
<?php
/*
* This file is part of the `nicolab/php-ftp-client` package.
*
* (c) Nicolas Tallefourtane <dev@nicolab.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
/**
* Wrap the PHP FTP functions
*
* @method bool alloc() alloc(int $filesize, string &$result = null) Allocates space for a file to be uploaded
* @method bool cdup() cdup() Changes to the parent directory
* @method bool chdir() chdir(string $directory) Changes the current directory on a FTP server
* @method int chmod() chmod(int $mode, string $filename) Set permissions on a file via FTP
* @method bool close() close() Closes an FTP connection
* @method bool delete() delete(string $path) Deletes a file on the FTP server
* @method bool exec() exec(string $command) Requests execution of a command on the FTP server
* @method bool fget() fget(resource $handle, string $remote_file, int $mode, int $resumepos = 0) Downloads a file from the FTP server and saves to an open file
* @method bool fput() fput(string $remote_file, resource $handle, int $mode, int $startpos = 0) Uploads from an open file to the FTP server
* @method mixed get_option() get_option(int $option) Retrieves various runtime behaviours of the current FTP stream
* @method bool get() get(string $local_file, string $remote_file, int $mode, int $resumepos = 0) Downloads a file from the FTP server
* @method bool login() login(string $username, string $password) Logs in to an FTP connection
* @method int mdtm() mdtm(string $remote_file) Returns the last modified time of the given file
* @method string mkdir() mkdir(string $directory) Creates a directory
* @method int nb_continue() nb_continue() Continues retrieving/sending a file (non-blocking)
* @method int nb_fget() nb_fget(resource $handle, string $remote_file, int $mode, int $resumepos = 0) Retrieves a file from the FTP server and writes it to an open file (non-blocking)
* @method int nb_fput() nb_fput(string $remote_file, resource $handle, int $mode, int $startpos = 0) Stores a file from an open file to the FTP server (non-blocking)
* @method int nb_get() nb_get(string $local_file, string $remote_file, int $mode, int $resumepos = 0) Retrieves a file from the FTP server and writes it to a local file (non-blocking)
* @method int nb_put() nb_put(string $remote_file, string $local_file, int $mode, int $startpos = 0) Stores a file on the FTP server (non-blocking)
* @method array nlist() nlist(string $directory) Returns a list of files in the given directory
* @method bool pasv() pasv(bool $pasv) Turns passive mode on or off
* @method bool put() put(string $remote_file, string $local_file, int $mode, int $startpos = 0) Uploads a file to the FTP server
* @method string pwd() pwd() Returns the current directory name
* @method bool quit() quit() Closes an FTP connection
* @method array raw() raw(string $command) Sends an arbitrary command to an FTP server
* @method array rawlist() rawlist(string $directory, bool $recursive = false) Returns a detailed list of files in the given directory
* @method bool rename() rename(string $oldname, string $newname) Renames a file or a directory on the FTP server
* @method bool rmdir() rmdir(string $directory) Removes a directory
* @method bool set_option() set_option(int $option, mixed $value) Set miscellaneous runtime FTP options
* @method bool site() site(string $command) Sends a SITE command to the server
* @method int size() size(string $remote_file) Returns the size of the given file
* @method string systype() systype() Returns the system type identifier of the remote FTP server
*
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpWrapper
{
/**
* The connection with the server
*
* @var resource
*/
protected $conn;
/**
* Constructor.
*
* @param resource &$connection The FTP (or SSL-FTP) connection (takes by reference).
*/
public function __construct(&$connection)
{
$this->conn = &$connection;
}
/**
* Forward the method call to FTP functions
*
* @param string $function
* @param array $arguments
* @return mixed
* @throws FtpException When the function is not valid
*/
public function __call($function, array $arguments)
{
$function = 'ftp_' . $function;
if (function_exists($function)) {
array_unshift($arguments, $this->conn);
return call_user_func_array($function, $arguments);
}
throw new FtpException("{$function} is not a valid FTP function");
}
/**
* Opens a FTP connection
*
* @param string $host
* @param int $port
* @param int $timeout
* @return resource
*/
public function connect($host, $port = 21, $timeout = 90)
{
return ftp_connect($host, $port, $timeout);
}
/**
* Opens a Secure SSL-FTP connection
* @param string $host
* @param int $port
* @param int $timeout
* @return resource
*/
public function ssl_connect($host, $port = 21, $timeout = 90)
{
return ftp_ssl_connect($host, $port, $timeout);
}
}

View File

@@ -0,0 +1,365 @@
<?php
/**
* Class Response
* Simplified copy of Symfony/Http-Foundation Response
* to allow compatibility with frameworks
*
* @package Filemanager
*/
class Response {
const HTTP_CONTINUE = 100;
const HTTP_SWITCHING_PROTOCOLS = 101;
const HTTP_PROCESSING = 102; // RFC2518
const HTTP_OK = 200;
const HTTP_CREATED = 201;
const HTTP_ACCEPTED = 202;
const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
const HTTP_NO_CONTENT = 204;
const HTTP_RESET_CONTENT = 205;
const HTTP_PARTIAL_CONTENT = 206;
const HTTP_MULTI_STATUS = 207; // RFC4918
const HTTP_ALREADY_REPORTED = 208; // RFC5842
const HTTP_IM_USED = 226; // RFC3229
const HTTP_MULTIPLE_CHOICES = 300;
const HTTP_MOVED_PERMANENTLY = 301;
const HTTP_FOUND = 302;
const HTTP_SEE_OTHER = 303;
const HTTP_NOT_MODIFIED = 304;
const HTTP_USE_PROXY = 305;
const HTTP_RESERVED = 306;
const HTTP_TEMPORARY_REDIRECT = 307;
const HTTP_PERMANENTLY_REDIRECT = 308; // RFC7238
const HTTP_BAD_REQUEST = 400;
const HTTP_UNAUTHORIZED = 401;
const HTTP_PAYMENT_REQUIRED = 402;
const HTTP_FORBIDDEN = 403;
const HTTP_NOT_FOUND = 404;
const HTTP_METHOD_NOT_ALLOWED = 405;
const HTTP_NOT_ACCEPTABLE = 406;
const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
const HTTP_REQUEST_TIMEOUT = 408;
const HTTP_CONFLICT = 409;
const HTTP_GONE = 410;
const HTTP_LENGTH_REQUIRED = 411;
const HTTP_PRECONDITION_FAILED = 412;
const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
const HTTP_REQUEST_URI_TOO_LONG = 414;
const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
const HTTP_EXPECTATION_FAILED = 417;
const HTTP_I_AM_A_TEAPOT = 418; // RFC2324
const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918
const HTTP_LOCKED = 423; // RFC4918
const HTTP_FAILED_DEPENDENCY = 424; // RFC4918
const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; // RFC2817
const HTTP_UPGRADE_REQUIRED = 426; // RFC2817
const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585
const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585
const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585
const HTTP_INTERNAL_SERVER_ERROR = 500;
const HTTP_NOT_IMPLEMENTED = 501;
const HTTP_BAD_GATEWAY = 502;
const HTTP_SERVICE_UNAVAILABLE = 503;
const HTTP_GATEWAY_TIMEOUT = 504;
const HTTP_VERSION_NOT_SUPPORTED = 505;
const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295
const HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918
const HTTP_LOOP_DETECTED = 508; // RFC5842
const HTTP_NOT_EXTENDED = 510; // RFC2774
const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585
/**
* Status codes translation table.
*
* The list of codes is complete according to the
* {@link http://www.iana.org/assignments/http-status-codes/ Hypertext Transfer Protocol (HTTP) Status Code Registry}
* (last updated 2012-02-13).
*
* Unless otherwise noted, the status code is defined in RFC2616.
*
* @var array
*/
public static $statusTexts = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing', // RFC2518
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status', // RFC4918
208 => 'Already Reported', // RFC5842
226 => 'IM Used', // RFC3229
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Reserved',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect', // RFC7238
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot', // RFC2324
422 => 'Unprocessable Entity', // RFC4918
423 => 'Locked', // RFC4918
424 => 'Failed Dependency', // RFC4918
425 => 'Reserved for WebDAV advanced collections expired proposal', // RFC2817
426 => 'Upgrade Required', // RFC2817
428 => 'Precondition Required', // RFC6585
429 => 'Too Many Requests', // RFC6585
431 => 'Request Header Fields Too Large', // RFC6585
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates (Experimental)', // RFC2295
507 => 'Insufficient Storage', // RFC4918
508 => 'Loop Detected', // RFC5842
510 => 'Not Extended', // RFC2774
511 => 'Network Authentication Required', // RFC6585
);
/**
* @var string
*/
protected $content;
/**
* @var int
*/
protected $statusCode;
/**
* @var string
*/
protected $statusText;
/**
* @var array
*/
public $headers;
/**
* @var string
*/
protected $version;
/**
* Construct the response
*
* @param mixed $content
* @param int $statusCode
* @param array $headers
*/
public function __construct($content = '', $statusCode = 200, $headers = array())
{
$this->setContent($content);
$this->setStatusCode($statusCode);
$this->headers = $headers;
$this->version = '1.1';
}
/**
* Set the content on the response.
*
* @param mixed $content
* @return $this
*/
public function setContent($content)
{
if ($content instanceof ArrayObject || is_array($content))
{
$this->headers['Content-Type'] = array('application/json');
$content = json_encode($content);
}
$this->content = $content;
}
/**
* Returns the Response as an HTTP string.
*
* The string representation of the Response is the same as the
* one that will be sent to the client only if the prepare() method
* has been called before.
*
* @return string The Response as an HTTP string
*
* @see prepare()
*/
public function __toString()
{
return
sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
$this->headers."\r\n".
$this->getContent();
}
/**
* Sets the response status code.
*
* @param int $code HTTP status code
* @param mixed $text HTTP status text
*
* If the status text is null it will be automatically populated for the known
* status codes and left empty otherwise.
*
* @return Response
*
* @throws \InvalidArgumentException When the HTTP status code is not valid
*
* @api
*/
public function setStatusCode($code, $text = null)
{
$this->statusCode = $code = (int) $code;
if ($this->isInvalid()) {
throw new InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
}
if (null === $text) {
$this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : '';
return $this;
}
if (false === $text) {
$this->statusText = '';
return $this;
}
$this->statusText = $text;
return $this;
}
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
/**
* Is response invalid?
*
* @return bool
*
* @api
*/
public function isInvalid()
{
return $this->statusCode < 100 || $this->statusCode >= 600;
}
/**
* Set a header on the Response.
*
* @param string $key
* @param string $value
* @param bool $replace
* @return $this
*/
public function header($key, $value, $replace = true)
{
if (empty($this->headers[$key]))
{
$this->headers[$key] = array();
}
if ($replace)
{
$this->headers[$key] = array($value);
}
else
{
$this->headers[$key][] = $value;
}
return $this;
}
/**
* Sends HTTP headers and content.
*
* @return Response
*
* @api
*/
public function send()
{
$this->sendHeaders();
$this->sendContent();
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
return $this;
}
/**
* Sends content for the current web response.
*
* @return Response
*/
public function sendContent()
{
echo $this->content;
return $this;
}
/**
* Sends HTTP headers.
*
* @return Response
*/
public function sendHeaders()
{
// headers have already been sent by the developer
if (headers_sent()) {
return $this;
}
// status
header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
// headers
foreach ($this->headers as $name => $values) {
if (is_array($values))
{
foreach ($values as $value)
{
header($name . ': ' . $value, false, $this->statusCode);
}
}
else
{
header($name . ': ' . $values, false, $this->statusCode);
}
}
return $this;
}
}

View File

@@ -0,0 +1,82 @@
<?php
Class FTPClient
{
// *** Class variables
private $connectionId;
private $loginOk = false;
private $messageArray = array();
public function __construct() { }
private function logMessage($message)
{
$this->messageArray[] = $message;
}
public function getMessages()
{
return $this->messageArray;
}
public function connect ($server, $ftpUser, $ftpPassword, $isPassive = false)
{
// *** Set up basic connection
$this->connectionId = ftp_connect($server);
// *** Login with username and password
$loginResult = ftp_login($this->connectionId, $ftpUser, $ftpPassword);
// *** Sets passive mode on/off (default off)
ftp_pasv($this->connectionId, $isPassive);
// *** Check connection
if ((!$this->connectionId) || (!$loginResult)) {
$this->logMessage('FTP connection has failed!');
$this->logMessage('Attempted to connect to ' . $server . ' for user ' . $ftpUser, true);
return false;
} else {
$this->logMessage('Connected to ' . $server . ', for user ' . $ftpUser);
$this->loginOk = true;
return true;
}
}
public function makeDir($directory)
{
// *** If creating a directory is successful...
if (ftp_mkdir($this->connectionId, $directory)) {
$this->logMessage('Directory "' . $directory . '" created successfully');
return true;
} else {
// *** ...Else, FAIL.
$this->logMessage('Failed creating directory "' . $directory . '"');
return false;
}
}
public function changeDir($directory)
{
if (ftp_chdir($this->connectionId, $directory)) {
$this->logMessage('Current directory is now: ' . ftp_pwd($this->connectionId));
return true;
} else {
$this->logMessage('Couldn\'t change directory');
return false;
}
}
public function getDirListing($directory = '.', $parameters = '-la')
{
echo shell_exec('whoami')." is who i am </br>";
echo "Current directory is now: " . ftp_pwd($this->connectionId) . "</br>";
// get contents of the current directory
$contentsArray = ftp_rawlist($this->connectionId, $parameters . ' ' . $directory);
echo error_get_last();
return $contentsArray;
}
}

View File

@@ -0,0 +1,267 @@
<?php
$mime_types = array(
"application/postscript" => "ps",
"audio/x-aiff" => "aiff",
"text/plain" => "txt",
"video/x-ms-asf" => "asx",
"audio/basic" => "snd",
"video/x-msvideo" => "avi",
"application/x-bcpio" => "bcpio",
"application/octet-stream" => "so",
"image/bmp" => "bmp",
"application/x-rar" => "rar",
"application/x-bzip2" => "bz2",
"application/x-netcdf" => "nc",
"application/x-kchart" => "chrt",
"application/x-cpio" => "cpio",
"application/mac-compactpro" => "cpt",
"application/x-csh" => "csh",
"text/css" => "css",
"application/x-director" => "dxr",
"image/vnd.djvu" => "djvu",
"application/x-dvi" => "dvi",
"image/vnd.dwg" => "dwg",
"application/epub" => "epub",
"application/epub+zip" => "epub",
"text/x-setext" => "etx",
"application/andrew-inset" => "ez",
"video/x-flv" => "flv",
"image/gif" => "gif",
"application/x-gtar" => "gtar",
"application/x-gzip" => "tgz",
"application/x-hdf" => "hdf",
"application/mac-binhex40" => "hqx",
"text/html" => "html",
"text/htm" => "htm",
"x-conference/x-cooltalk" => "ice",
"image/ief" => "ief",
"model/iges" => "igs",
"text/vnd.sun.j2me.app-descriptor" => "jad",
"application/x-java-archive" => "jar",
"application/x-java-jnlp-file" => "jnlp",
"image/jpeg" => "jpg",
"application/x-javascript" => "js",
"audio/midi" => "midi",
"application/x-killustrator" => "kil",
"application/x-kpresenter" => "kpt",
"application/x-kspread" => "ksp",
"application/x-kword" => "kwt",
"application/vnd.google-earth.kml+xml" => "kml",
"application/vnd.google-earth.kmz" => "kmz",
"application/x-latex" => "latex",
"audio/x-mpegurl" => "m3u",
"application/x-troff-man" => "man",
"application/x-troff-me" => "me",
"model/mesh" => "silo",
"application/vnd.mif" => "mif",
"video/quicktime" => "mov",
"video/x-sgi-movie" => "movie",
"audio/mpeg" => "mp3",
"video/mp4" => "mp4",
"video/mpeg" => "mpeg",
"application/x-troff-ms" => "ms",
"video/vnd.mpegurl" => "mxu",
"application/vnd.oasis.opendocument.database" => "odb",
"application/vnd.oasis.opendocument.chart" => "odc",
"application/vnd.oasis.opendocument.formula" => "odf",
"application/vnd.oasis.opendocument.graphics" => "odg",
"application/vnd.oasis.opendocument.image" => "odi",
"application/vnd.oasis.opendocument.text-master" => "odm",
"application/vnd.oasis.opendocument.presentation" => "odp",
"application/vnd.oasis.opendocument.spreadsheet" => "ods",
"application/vnd.oasis.opendocument.text" => "odt",
"application/ogg" => "ogg",
"video/ogg" => "ogv",
"application/vnd.oasis.opendocument.graphics-template" => "otg",
"application/vnd.oasis.opendocument.text-web" => "oth",
"application/vnd.oasis.opendocument.presentation-template" => "otp",
"application/vnd.oasis.opendocument.spreadsheet-template" => "ots",
"application/vnd.oasis.opendocument.text-template" => "ott",
"image/x-portable-bitmap" => "pbm",
"chemical/x-pdb" => "pdb",
"application/pdf" => "pdf",
"image/x-portable-graymap" => "pgm",
"application/x-chess-pgn" => "pgn",
"text/x-php" => "php",
"image/png" => "png",
"image/x-portable-anymap" => "pnm",
"image/x-portable-pixmap" => "ppm",
"application/vnd.ms-powerpoint" => "ppt",
"audio/x-realaudio" => "ra",
"audio/x-pn-realaudio" => "rm",
"image/x-cmu-raster" => "ras",
"image/x-rgb" => "rgb",
"application/x-troff" => "tr",
"application/x-rpm" => "rpm",
"text/rtf" => "rtf",
"text/richtext" => "rtx",
"text/sgml" => "sgml",
"application/x-sh" => "sh",
"application/x-shar" => "shar",
"application/vnd.symbian.install" => "sis",
"application/x-stuffit" => "sit",
"application/x-koan" => "skt",
"application/smil" => "smil",
"image/svg+xml" => "svg",
"application/x-futuresplash" => "spl",
"application/x-wais-source" => "src",
"application/vnd.sun.xml.calc.template" => "stc",
"application/vnd.sun.xml.draw.template" => "std",
"application/vnd.sun.xml.impress.template" => "sti",
"application/vnd.sun.xml.writer.template" => "stw",
"application/x-sv4cpio" => "sv4cpio",
"application/x-sv4crc" => "sv4crc",
"application/x-shockwave-flash" => "swf",
"application/vnd.sun.xml.calc" => "sxc",
"application/vnd.sun.xml.draw" => "sxd",
"application/vnd.sun.xml.writer.global" => "sxg",
"application/vnd.sun.xml.impress" => "sxi",
"application/vnd.sun.xml.math" => "sxm",
"application/vnd.sun.xml.writer" => "sxw",
"application/x-tar" => "tar",
"application/x-tcl" => "tcl",
"application/x-tex" => "tex",
"application/x-texinfo" => "texinfo",
"image/tiff" => "tiff",
"image/tiff-fx" => "tiff",
"application/x-bittorrent" => "torrent",
"text/tab-separated-values" => "tsv",
"application/x-ustar" => "ustar",
"application/x-cdlink" => "vcd",
"model/vrml" => "wrl",
"audio/x-wav" => "wav",
"audio/x-ms-wax" => "wax",
"image/vnd.wap.wbmp" => "wbmp",
"application/vnd.wap.wbxml" => "wbxml",
"video/x-ms-wm" => "wm",
"audio/x-ms-wma" => "wma",
"text/vnd.wap.wml" => "wml",
"application/vnd.wap.wmlc" => "wmlc",
"text/vnd.wap.wmlscript" => "wmls",
"application/vnd.wap.wmlscriptc" => "wmlsc",
"video/x-ms-wmv" => "wmv",
"video/x-ms-wmx" => "wmx",
"video/x-ms-wvx" => "wvx",
"image/x-xbitmap" => "xbm",
"application/xhtml+xml" => "xhtml",
"application/xml" => "xml",
"image/x-xpixmap" => "xpm",
"text/xsl" => "xsl",
"image/x-xwindowdump" => "xwd",
"chemical/x-xyz" => "xyz",
"application/zip" => "zip",
"application/msword" => "doc",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.template" => "dotx",
"application/vnd.ms-word.document.macroEnabled.12" => "docm",
"application/vnd.ms-excel" => "xls",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.template" => "xltx",
"application/vnd.ms-excel.sheet.macroEnabled.12" => "xlsm",
"application/vnd.ms-excel.template.macroEnabled.12" => "xltm",
"application/vnd.ms-excel.addin.macroEnabled.12" => "xlam",
"application/vnd.ms-excel.sheet.binary.macroEnabled.12" => "xlsb",
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => "pptx",
"application/vnd.openxmlformats-officedocument.presentationml.template" => "potx",
"application/vnd.openxmlformats-officedocument.presentationml.slideshow" => "ppsx",
"application/vnd.ms-powerpoint.addin.macroEnabled.12" => "ppam",
"application/vnd.ms-powerpoint.presentation.macroEnabled.12" => "pptm",
"application/vnd.ms-powerpoint.template.macroEnabled.12" => "potm",
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12" => "ppsm",
);
if ( ! function_exists('get_extension_from_mime'))
{
function get_extension_from_mime($mime){
global $mime_types;
if(strpos($mime, ';')!==FALSE){
$mime = substr($mime, 0,strpos($mime, ';'));
}
if(isset($mime_types[$mime])){
return $mime_types[$mime];
}
return '';
}
}
if ( ! function_exists('get_file_mime_type'))
{
function get_file_mime_type($filename, $debug = false)
{
if (function_exists('finfo_open') && function_exists('finfo_file') && function_exists('finfo_close'))
{
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($fileinfo, $filename);
finfo_close($fileinfo);
if ( ! empty($mime_type))
{
if (true === $debug)
{
return array( 'mime_type' => $mime_type, 'method' => 'fileinfo' );
}
return $mime_type;
}
}
if (function_exists('mime_content_type'))
{
$mime_type = mime_content_type($filename);
if ( ! empty($mime_type))
{
if (true === $debug)
{
return array( 'mime_type' => $mime_type, 'method' => 'mime_content_type' );
}
return $mime_type;
}
}
global $mime_types;
$mime_types = array_flip($mime_types);
$tmp_array = explode('.', $filename);
$ext = strtolower(array_pop($tmp_array));
if ( ! empty($mime_types[ $ext ]))
{
if (true === $debug)
{
return array( 'mime_type' => $mime_types[ $ext ], 'method' => 'from_array' );
}
return $mime_types[ $ext ];
}
if (true === $debug)
{
return array( 'mime_type' => 'application/octet-stream', 'method' => 'last_resort' );
}
return 'application/octet-stream';
}
}
/********************
* The following code can be used to test the function.
* First put a plain text file named "test.txt" and a
* JPEG image file named "image.jpg" in the same folder
* as this file.
*
* Simply remove the "REMOVE ME TO TEST" lines below to have
* the code run when this file runs.
*
* Run the code with this command:
* php mime_type_lib.php
********************/
/* REMOVE ME TO TEST
echo get_file_mime_type( 'test.txt' ) . "\n";
echo print_r( get_file_mime_type( 'image.jpg', true ), true ) . "\n";
REMOVE ME TO TEST */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff