🔀 Merge branch 'dev'

This commit is contained in:
wisp-x
2019-10-31 12:58:11 +08:00
116 changed files with 3485 additions and 1969 deletions
+2 -1
View File
@@ -16,7 +16,8 @@
[![PHP](https://img.shields.io/badge/PHP->=5.6-orange.svg)](http://php.net)
[![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/wisp-x/lsky-pro.svg)](https://github.com/wisp-x/lsky-pro)
> 下载稳定版请点击[这里](https://github.com/wisp-x/lsky-pro/releases),发现 bug 可发送邮件至邮箱:i@wispx.cn,或提交 [issues](https://github.com/wisp-x/lsky-pro/issues),确认 bug 后我会及时修复,谢谢!
> 下载稳定版请点击[这里](https://github.com/wisp-x/lsky-pro/releases),发现 bug 可发送邮件至邮箱:i@wispx.cn,或提交 [issues](https://github.com/wisp-x/lsky-pro/issues)
> 下载速度慢的可以异步 Coding https://dev.tencent.com/u/wispx/p/lsky-pro-releases/git
![homepage.png](./public/static/app/images/demo/1.png)
![homepage.png](./public/static/app/images/demo/2.png)
+1 -1
View File
@@ -35,7 +35,7 @@ class Base extends Controller
$this->response('API is not open yet.', [], 500);
}
$this->token = $this->request->header('token');
$this->token = $this->request->header('token', $this->param('token'));
$this->auth($this->token);
$format = $this->param('format');
+53
View File
@@ -0,0 +1,53 @@
<?php
/**
* Created by WispX.
* User: WispX <1591788658@qq.com>
* Date: 2019/10/31
* Time: 11:10 上午
* Link: https://github.com/wisp-x
*/
namespace app\api\controller;
use app\common\model\Images;
class Image extends Base
{
private $model;
public function initialize()
{
parent::initialize();
$this->model = new Images();
$this->model = $this->model->where('user_id', $this->user->id)->field(['user_id', 'folder_id'], true);
}
public function find()
{
$id = $this->param('id');
$image = $this->model->where(['id' => $id])->find();
$this->response('success', $this->parseData($image));
}
public function items()
{
$page = $this->param('page', 1);
$rows = $this->param('rows', 20);
$images = $this->model->paginate(null, false, [
'page' => $page,
'list_rows' => $rows,
])->each(function ($item) {
$item = $this->parseData($item);
unset($item['create_time']);
return $item;
});
$this->response('success', $images);
}
private function parseData($data)
{
$data['upload_time'] = $data->getData('create_time');
$data['upload_date'] = $data->create_time;
return $data;
}
}
+2
View File
@@ -16,6 +16,8 @@ class Images extends Model
protected $insert = ['ip'];
protected $append = ['url'];
public function getUrlAttr($url, $data)
{
// 图片链接
+1 -10
View File
@@ -218,16 +218,7 @@ EOT;
$mysqli->query("SET NAMES utf8");
// 新建表字段
$tableFields = [
'lsky_images' => [
'folder_id' => "ALTER TABLE `lsky_images` ADD `folder_id` INT NOT NULL DEFAULT '0' COMMENT '文件夹ID' AFTER `user_id`;",
'suspicious' => "ALTER TABLE `lsky_images` ADD `suspicious` TINYINT(1) NOT NULL DEFAULT '0' COMMENT '可疑图片' AFTER `ip`;",
],
'lsky_users' => [
'default_folder' => "ALTER TABLE `lsky_users` ADD `default_folder` VARCHAR(32) DEFAULT NULL COMMENT '默认上传文件夹' AFTER `quota`;",
'group_id' => "ALTER TABLE `lsky_users` ADD `group_id` int(11) NOT NULL DEFAULT 0 COMMENT '角色组ID' AFTER `id`;"
],
];
$tableFields = Config::pull('table');
foreach ($tableFields as $table => $fields) {
foreach ($fields as $field => $sql) {
@@ -10,6 +10,7 @@ namespace app\index\controller\admin;
use app\common\model\Config;
use think\Db;
use app\common\model\Images;
use think\Exception;
/**
@@ -50,14 +51,14 @@ class System extends Base
public function console()
{
$storage = Db::name('images')->sum('size');
$imagesCount = Db::name('images')->count();
$suspiciousImagesCount = Db::name('images')->where('suspicious', 1)->count();
$users_count = Db::name('users')->count();
$today = Db::name('images')->whereTime('create_time', 'today')->count();
$yesterday = Db::name('images')->whereTime('create_time', 'yesterday')->count();
$month = Db::name('images')->whereTime('create_time', 'month')->count();
$tourists = Db::name('images')->where('user_id', 0)->count();
$storage = Images::sum('size');
$imagesCount = Images::count();
$suspiciousImagesCount = Images::where('suspicious', 1)->count();
$users_count = \app\common\model\Users::count();
$today = Images::whereTime('create_time', 'today')->count();
$yesterday = Images::whereTime('create_time', 'yesterday')->count();
$month = Images::whereTime('create_time', 'month')->count();
$tourists = Images::where('user_id', 0)->count();
$this->assign([
'storage' => format_size($storage, true), // 占用储存
@@ -0,0 +1,307 @@
<?php
/**
* Created by WispX.
* User: WispX <wisp-x@qq.com>
* Date: 2019-08-06
* Time: 15:51
* Link: https://github.com/wisp-x
*/
namespace app\index\controller\admin;
use think\Db;
use think\facade\Config;
use think\facade\Env;
class Update extends Base
{
public function index()
{
// https://dev.tencent.com/u/wispx/p/lsky-pro-releases/git/raw/master/releases/lsky-pro-1.5.4.zip
echo <<<EOT
<style>
body {background-color: black;color: white;}
span {color: white;}
</style>
<pre>
EOT;
try {
$this->out('检测更新中...');
$version = $this->checkUpdate();
if (!$version) {
throw new \Exception('版本信息获取失败!');
}
$this->out("检测到新版本 [v{$version}]");
$runtimePath = Env::get('runtime_path');
$url = "https://dev.tencent.com/u/wispx/p/lsky-pro-releases/git/raw/master/releases/lsky-pro-{$version}.zip";
$dirname = "lsky-pro-{$version}";
$name = "lsky-pro-{$version}.zip";
// $ip = $this->getRandIp();
$context = stream_context_create(
['http' => [
'header' => "User-Agent: {$this->getRandUserAgent()}",
'timeout' => 600
]]
);
$this->out('<font color="#ffd700">开始更新操作, 请勿关闭本窗口...</font>');
$this->out('安装包下载中, 请耐心等待...');
if (!$file = @file_get_contents($url, false, $context)) {
throw new \Exception('安装包下载失败, 请稍后再试!');
}
$this->out('安装包下载完成!', '正在保存安装包...');
if (!@file_put_contents($runtimePath . $name, $file)) {
throw new \Exception('安装包保存失败! 请检查 runtime 目录权限!');
}
$this->out('保存完成!', '正在执行解压...');
if (! $this->extractZip($runtimePath . $name)) {
throw new \Exception('安装包解压失败!');
}
// 读取sql文件
$this->out('解压完成!', '正在更新数据...');
// 更新表结构
//$tableFields = require "{$runtimePath}{$dirname}/config/table.php";
$sqlFile = file_get_contents("{$runtimePath}{$dirname}/update.sql");
$config = Config::pull('db');
$mysqli = new \mysqli(
$config['hostname'],
$config['username'],
$config['password'],
$config['database'],
$config['hostport']
);
if ($mysqli->connect_errno) {
$mysqli->close();
throw new \Exception("数据库连接失败! {$mysqli->connect_error}");
}
$mysqli->autocommit(false);
$mysqli->select_db($config['database']);
$mysqli->query("SET NAMES utf8");
/*foreach ($tableFields as $table => $fields) {
foreach ($fields as $field => $sql) {
$fetchFields = $mysqli->query("DESCRIBE `{$table}`;");
// 判断字段是否已存在
$flag = true;
foreach ($fetchFields as $fetchField) {
if ($field == $fetchField['Field']) {
$flag = false;
}
}
if ($flag) {
if (!$mysqli->query($sql)) {
throw new \Exception($mysqli->error);
}
}
}
}*/
foreach (explode(';', $sqlFile) as $value) {
if ($value && !ctype_space($value)) {
if (!$mysqli->query($value . ';')) {
throw new \Exception("数据更新失败! 错误信息:{$mysqli->error}, sql语句:{$value}");
}
}
}
$this->out('数据库更新完毕!', '正在复制文件...');
$this->out('清理临时数据...');
// TODO 复制文件
// TODO 清理临时数据
$mysqli->commit();
$mysqli->autocommit(true);
$mysqli->close();
$this->out("<font color='green'>更新成功!</font>");
} catch (\Exception $e) {
$this->out("<font color='red'>{$e->getMessage()}</font>");
}
ob_end_flush();
}
/**
* 解压文件到指定目录
*
* @param $filename zip压缩包路径加文件名
* @param bool $destDir 解压文件的目的路径
* @param bool $createZipNameDir 是否以压缩文件的名字创建目标文件夹
* @param bool $overwrite 是否覆盖
* @return bool
*/
public function extractZip($filename, $destDir = false, $createZipNameDir = false, $overwrite = true)
{
if ($zip = zip_open($filename)) {
if ($zip) {
$splitter = ($createZipNameDir === true) ? "." : "/";
if ($destDir === false) {
$destDir = substr($filename, 0, strrpos($filename, $splitter)) . "/";
}
// 如果不存在 创建目标解压目录
$this->mkdirs($destDir);
// 对每个文件进行解压
while ($zip_entry = zip_read($zip)) {
// 文件不在根目录
$pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
if ($pos_last_slash !== false) {
// 创建目录 在末尾带 /
$this->mkdirs($destDir . substr(zip_entry_name($zip_entry), 0, $pos_last_slash + 1));
}
// 打开包
if (zip_entry_open($zip, $zip_entry, "r")) {
// 文件名保存在磁盘上
$file_name = $destDir . zip_entry_name($zip_entry);
// 检查文件是否需要重写
if ($overwrite === true || $overwrite === false && !is_file($file_name)) {
// 读取压缩文件的内容
$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
@file_put_contents($file_name, $fstream);
// 设置权限
chmod($file_name, 0755);
}
zip_entry_close($zip_entry);
}
}
zip_close($zip);
}
} else {
return false;
}
return true;
}
/**
* 创建目录
*
* @param $path
*/
public function mkdirs($path)
{
if (!is_dir($path)) {
$directoryPath = "";
$directories = explode("/", $path);
array_pop($directories);
foreach ($directories as $directory) {
$directoryPath .= $directory . "/";
if (!is_dir($directoryPath)) {
mkdir($directoryPath);
chmod($directoryPath, 0777);
}
}
}
}
/**
* 检测最新版
*
* @return bool|string
* @throws \Exception
*/
private function checkUpdate()
{
$client = new \GuzzleHttp\Client();
$response = $client->get('https://api.github.com/repos/wisp-x/lsky-pro/releases/latest');
if (200 === $response->getStatusCode()) {
$result = json_decode($response->getBody()->getContents());
$version = ltrim(strtolower($result->name), 'v');
if ($this->config['system_version'] > $version) {
throw new \Exception('不可降级!');
}
if ($this->config['system_version'] == $version) {
throw new \Exception('当前已经是最新版!');
}
return $version;
}
return false;
}
/**
* Out Print
*
* @param mixed ...$args
*/
private function out(...$args)
{
if (ob_get_level() == 0) ob_start();
foreach ($args as $i => $arg) {
echo "<span><font color='green'>root@lsky-pro</font>:~$ {$arg}</span>";
echo str_pad('', 4096) . "\n";
ob_flush();
flush();
sleep(1);
}
}
/**
* 获取随机 UserAgent
*
* @return mixed
*/
private function getRandUserAgent()
{
$array = [
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
"Mozilla/5.0 (Macintosh; U; Mac OS X Mach-O; en-US; rv:2.0a) Gecko/20040614 Firefox/3.0.0 ",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.14) Gecko/20110218 AlexaToolbar/alxf-2.0 Firefox/3.6.14",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
"Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
"Opera/9.80 (Android 2.3.4; Linux; Opera mobi/adr-1107051709; U; zh-cn) Presto/2.8.149 Version/11.10",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10",
"Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
];
return $array[array_rand($array)];
}
/**
* 随机IP
*
* @return string
*/
private function getRandIp()
{
$array = ["218", "218", "66", "66", "218", "218", "60", "60", "202", "204", "66", "66", "66", "59", "61", "60", "222", "221", "66", "59", "60", "60", "66", "218", "218", "62", "63", "64", "66", "66", "122", "211"];
$rand = mt_rand(0, count($array));
$ip1id = $array[$rand];
$ip2id = round(rand(600000, 2550000) / 10000);
$ip3id = round(rand(600000, 2550000) / 10000);
$ip4id = round(rand(600000, 2550000) / 10000);
return $ip1id . "." . $ip2id . "." . $ip3id . "." . $ip4id;
}
}
@@ -10,7 +10,9 @@
<div class="mdui-col item mdui-m-b-2">
<div class="mdui-color-blue mdui-text-center mdui-text-color-white mdui-p-a-2 mdui-shadow-4 mdui-hoverable">
<p><i class="mdui-icon material-icons">&#xe623;</i> 占用储存</p>
<span class="mdui-text-color-amber">{$storage[0]} <small class="mdui-text-color-white">{$storage[1]}</small></span>
<span class="mdui-text-color-amber">{$storage[0]}
<small class="mdui-text-color-white">{if $storage[0]}{$storage[1]}{else/}Kb{/if}</small>
</span>
</div>
</div>
<div class="mdui-col item mdui-m-b-2">
+2 -2
View File
@@ -3,7 +3,7 @@
{block name="title"}登录 - {$config.site_name}{/block}
{block name="css"}
<link href="/static/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
{/block}
{block name="main"}
@@ -42,5 +42,5 @@
{/block}
{block name="js"}
<script src="/static/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="/static/bootstrap/4.3.1/js/bootstrap.min.js"></script>
{/block}
+2 -2
View File
@@ -3,7 +3,7 @@
{block name="title"}注册 - {$config.site_name}{/block}
{block name="css"}
<link href="/static/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
{/block}
{block name="main"}
@@ -67,5 +67,5 @@
{/block}
{block name="js"}
<script src="/static/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="/static/bootstrap/4.3.1/js/bootstrap.min.js"></script>
{/block}
+246
View File
@@ -227,6 +227,252 @@ Content-Type: image/png
"time": 1544245931
}</pre>
</div>
<div class="mdui-shadow-2 mdui-m-t-2 mdui-m-b-1 mdui-p-a-3 mdui-text-color-red">
注意:以下接口均需要 Token
</div>
<div class="mdui-m-b-2">
<h2>3. 获取图片列表</h2>
<div class="mdui-row">
<div class="mdui-col-md-6">
<div class="mdui-table-fluid mdui-m-t-1">
<table class="mdui-table">
<thead>
<tr>
<td>功能</td>
<td>接口</td>
</tr>
</thead>
<tbody>
<tr>
<td>请求方式</td>
<td>POST</td>
</tr>
<tr>
<td>URL</td>
<td>{$domain}/api/images</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<h4 class="mdui-m-t-2 mdui-m-b-1">请求参数</h4>
<div class="mdui-table-fluid">
<table class="mdui-table">
<thead>
<tr>
<td>参数名称</td>
<td>类型</td>
<td>是否必须</td>
<td>说明</td>
</tr>
</thead>
<tbody>
<tr>
<td>page</td>
<td>String</td>
<td></td>
<td>页码</td>
</tr>
<tr>
<td>rows</td>
<td>String</td>
<td></td>
<td>每页数量, 默认 20 条</td>
</tr>
</tbody>
</table>
</div>
<h4 class="mdui-m-t-2 mdui-m-b-1">返回数据(data)说明</h4>
<div class="mdui-table-fluid">
<table class="mdui-table">
<thead>
<tr>
<td>参数名称</td>
<td>类型</td>
<td>实例值</td>
<td>说明</td>
</tr>
</thead>
<tbody>
<tr>
<td>total</td>
<td>Number</td>
<td>999</td>
<td>数据总量</td>
</tr>
<tr>
<td>per_page</td>
<td>String</td>
<td>1</td>
<td>每页数量</td>
</tr>
<tr>
<td>current_page</td>
<td>Number</td>
<td>1</td>
<td>当前所在页码</td>
</tr>
<tr>
<td>last_page</td>
<td>Number</td>
<td>999</td>
<td>最后一页页码</td>
</tr>
</tbody>
</table>
</div>
<h4 class="mdui-m-t-2 mdui-m-b-1">图片数据说明</h4>
<div class="mdui-table-fluid">
<table class="mdui-table">
<thead>
<tr>
<td>参数名称</td>
<td>类型</td>
<td>实例值</td>
<td>说明</td>
</tr>
</thead>
<tbody>
<tr>
<td>id</td>
<td>Number</td>
<td>1</td>
<td>图片ID</td>
</tr>
<tr>
<td>strategy</td>
<td>String</td>
<td>oss</td>
<td>储存策略, (cos:腾讯云, kodo:七牛云, local:本地, oss:阿里云oss, remote:远程储存, uss:又拍云)</td>
</tr>
<tr>
<td>path</td>
<td>String</td>
<td>2019/10/31</td>
<td>图片所在路径</td>
</tr>
<tr>
<td>name</td>
<td>String</td>
<td>929616303ca92.jpg</td>
<td>图片名称</td>
</tr>
<tr>
<td>pathname</td>
<td>String</td>
<td>2019/10/31/929616303ca92.jpg</td>
<td>图片路径+名称</td>
</tr>
<tr>
<td>size</td>
<td>String</td>
<td>30405.00</td>
<td>图片大小(字节: b)</td>
</tr>
<tr>
<td>mime</td>
<td>String</td>
<td>image/jpeg</td>
<td>图片 mime 类型</td>
</tr>
<tr>
<td>sha1</td>
<td>String</td>
<td>0143f7904f12e2a76ff2935f21a771b8adadf961</td>
<td>图片 sha1 值</td>
</tr>
<tr>
<td>md5</td>
<td>String</td>
<td>e630c1d832f1701b0afe09cfe86a7f2b</td>
<td>图片 md5 值</td>
</tr>
<tr>
<td>ip</td>
<td>String</td>
<td>192.168.0.1</td>
<td>上传者 IP</td>
</tr>
<tr>
<td>suspicious</td>
<td>Number</td>
<td>0</td>
<td>是否是可疑图片, (0:否, 1:是)</td>
</tr>
<tr>
<td>update_time</td>
<td>Number</td>
<td>1572491936</td>
<td>图片上传时间</td>
</tr>
<tr>
<td>update_date</td>
<td>String</td>
<td>2019-10-31 11:18:56</td>
<td>图片上传日期</td>
</tr>
<tr>
<td>url</td>
<td>String</td>
<td>http://domain.com/2019/10/31/929616303ca92.jpg</td>
<td>图片链接</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="mdui-m-b-2">
<h2>4. 获取单张图片</h2>
<div class="mdui-row">
<div class="mdui-col-md-6">
<div class="mdui-table-fluid mdui-m-t-1">
<table class="mdui-table">
<thead>
<tr>
<td>功能</td>
<td>接口</td>
</tr>
</thead>
<tbody>
<tr>
<td>请求方式</td>
<td>POST</td>
</tr>
<tr>
<td>URL</td>
<td>{$domain}/api/image</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<h4 class="mdui-m-t-2 mdui-m-b-1">请求参数</h4>
<div class="mdui-table-fluid">
<table class="mdui-table">
<thead>
<tr>
<td>参数名称</td>
<td>类型</td>
<td>是否必须</td>
<td>说明</td>
</tr>
</thead>
<tbody>
<tr>
<td>id</td>
<td>String</td>
<td></td>
<td>图片ID</td>
</tr>
</tbody>
</table>
</div>
<h4 class="mdui-m-t-2 mdui-m-b-1">返回数据(data)与第三条相同</h4>
</div>
</main>
</div>
{/block}
+7 -1
View File
@@ -12,6 +12,12 @@
<div class="mdui-container">
<main>
<div class="upload-container">
{if $config.notice}
<div class="alert alert-info alert-dismissible fade show">
<button type="button" class="close" data-dismiss="alert">&times;</button>
{$config.notice|raw}
</div>
{/if}
<div class="title">
<h1>Image Upload</h1>
<p>最大可上传 {:round($config.upload_max_size / 1024 / 1024)} MB的图片,单次同时可选择 {$config.upload_single_num} 张。本站已托管 {$images_count} 张图片。</p>
@@ -84,7 +90,7 @@
};
$("#image").fileinput({
uploadUrl: "{:url('upload/upload')}",
uploadUrl: "{:url('upload/upload')}" + '?rand=' + new Date().getTime().toString(36) + Math.random().toString(36).slice(2),
language: "zh",
theme: "fas",
previewFileType: "image",
+2 -1
View File
@@ -23,7 +23,8 @@
"upyun/sdk": "^3.3",
"qcloud/cos-sdk-v5": "^1.2",
"topthink/think-image": "^1.0",
"phpmailer/phpmailer": "^6.0"
"phpmailer/phpmailer": "^6.0",
"nicolab/php-ftp-client": "^1.5"
},
"autoload": {
"psr-4": {
Generated
+104 -48
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "f3a07db17ca2f758f19303939f3bb3d6",
"content-hash": "fb6ffef3fc6c84854a1c9c891746c6e1",
"packages": [
{
"name": "aliyuncs/oss-sdk-php",
@@ -157,16 +157,16 @@
},
{
"name": "guzzlehttp/guzzle",
"version": "6.3.3",
"version": "6.4.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba"
"reference": "0895c932405407fd3a7368b6910c09a24d26db11"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/407b0cb880ace85c9b63c5f9551db498cb2d50ba",
"reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/0895c932405407fd3a7368b6910c09a24d26db11",
"reference": "0895c932405407fd3a7368b6910c09a24d26db11",
"shasum": "",
"mirrors": [
{
@@ -176,14 +176,15 @@
]
},
"require": {
"ext-json": "*",
"guzzlehttp/promises": "^1.0",
"guzzlehttp/psr7": "^1.4",
"guzzlehttp/psr7": "^1.6.1",
"php": ">=5.5"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0",
"psr/log": "^1.0"
"psr/log": "^1.1"
},
"suggest": {
"psr/log": "Required for using the Log middleware"
@@ -195,12 +196,12 @@
}
},
"autoload": {
"files": [
"src/functions_include.php"
],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
@@ -224,7 +225,7 @@
"rest",
"web service"
],
"time": "2018-04-22T15:46:56+00:00"
"time": "2019-10-23T15:58:00+00:00"
},
{
"name": "guzzlehttp/promises",
@@ -361,17 +362,72 @@
"time": "2019-07-01T23:21:34+00:00"
},
{
"name": "phpmailer/phpmailer",
"version": "v6.0.7",
"name": "nicolab/php-ftp-client",
"version": "v1.5.1",
"source": {
"type": "git",
"url": "https://github.com/PHPMailer/PHPMailer.git",
"reference": "0c41a36d4508d470e376498c1c0c527aa36a2d59"
"url": "https://github.com/Nicolab/php-ftp-client.git",
"reference": "8c66e1104da1b638f5d7a9e24624a5525b459a0c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/0c41a36d4508d470e376498c1c0c527aa36a2d59",
"reference": "0c41a36d4508d470e376498c1c0c527aa36a2d59",
"url": "https://api.github.com/repos/Nicolab/php-ftp-client/zipball/8c66e1104da1b638f5d7a9e24624a5525b459a0c",
"reference": "8c66e1104da1b638f5d7a9e24624a5525b459a0c",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"ext-ftp": "*",
"php": ">=5.4"
},
"type": "library",
"autoload": {
"psr-0": {
"FtpClient": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Tallefourtane",
"email": "dev@nicolab.net",
"homepage": "http://nicolab.net"
}
],
"description": "A flexible FTP and SSL-FTP client for PHP. This lib provides helpers easy to use to manage the remote files.",
"homepage": "https://github.com/Nicolab/php-ftp-client",
"keywords": [
"file",
"ftp",
"helper",
"lib",
"server",
"sftp",
"ssl",
"ssl-ftp"
],
"time": "2019-04-23T09:22:37+00:00"
},
{
"name": "phpmailer/phpmailer",
"version": "v6.1.1",
"source": {
"type": "git",
"url": "https://github.com/PHPMailer/PHPMailer.git",
"reference": "26bd96350b0b2fcbf0ef4e6f0f9cf3528302a9d8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/26bd96350b0b2fcbf0ef4e6f0f9cf3528302a9d8",
"reference": "26bd96350b0b2fcbf0ef4e6f0f9cf3528302a9d8",
"shasum": "",
"mirrors": [
{
@@ -410,17 +466,17 @@
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-2.1"
"LGPL-2.1-only"
],
"authors": [
{
"name": "Jim Jagielski",
"email": "jimjag@gmail.com"
},
{
"name": "Marcus Bointon",
"email": "phpmailer@synchromedia.co.uk"
},
{
"name": "Jim Jagielski",
"email": "jimjag@gmail.com"
},
{
"name": "Andy Prevost",
"email": "codeworxtech@users.sourceforge.net"
@@ -430,7 +486,7 @@
}
],
"description": "PHPMailer is a full-featured email creation and transfer class for PHP",
"time": "2019-02-01T15:04:28+00:00"
"time": "2019-09-27T21:33:43+00:00"
},
{
"name": "psr/http-message",
@@ -490,16 +546,16 @@
},
{
"name": "qcloud/cos-sdk-v5",
"version": "v1.3.3",
"version": "v1.3.4",
"source": {
"type": "git",
"url": "https://github.com/tencentyun/cos-php-sdk-v5.git",
"reference": "cd1b9cefa04521eaf125a82eb53552d9a87aae4d"
"reference": "1b32aa422f6dffe4ea411e5095e4b0da9135551b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/tencentyun/cos-php-sdk-v5/zipball/cd1b9cefa04521eaf125a82eb53552d9a87aae4d",
"reference": "cd1b9cefa04521eaf125a82eb53552d9a87aae4d",
"url": "https://api.github.com/repos/tencentyun/cos-php-sdk-v5/zipball/1b32aa422f6dffe4ea411e5095e4b0da9135551b",
"reference": "1b32aa422f6dffe4ea411e5095e4b0da9135551b",
"shasum": "",
"mirrors": [
{
@@ -538,20 +594,20 @@
"php",
"qcloud"
],
"time": "2019-08-07T10:15:47+00:00"
"time": "2019-09-02T12:08:44+00:00"
},
{
"name": "qiniu/php-sdk",
"version": "v7.2.9",
"version": "v7.2.10",
"source": {
"type": "git",
"url": "https://github.com/qiniu/php-sdk.git",
"reference": "afe7d8715d8a688b1d8d8cdf031240d2363dad90"
"reference": "d89987163f560ebf9dfa5bb25de9bd9b1a3b2bd8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/qiniu/php-sdk/zipball/afe7d8715d8a688b1d8d8cdf031240d2363dad90",
"reference": "afe7d8715d8a688b1d8d8cdf031240d2363dad90",
"url": "https://api.github.com/repos/qiniu/php-sdk/zipball/d89987163f560ebf9dfa5bb25de9bd9b1a3b2bd8",
"reference": "d89987163f560ebf9dfa5bb25de9bd9b1a3b2bd8",
"shasum": "",
"mirrors": [
{
@@ -595,7 +651,7 @@
"sdk",
"storage"
],
"time": "2019-07-09T07:55:07+00:00"
"time": "2019-10-28T10:23:23+00:00"
},
{
"name": "ralouphie/getallheaders",
@@ -711,16 +767,16 @@
},
{
"name": "topthink/framework",
"version": "v5.1.38",
"version": "v5.1.38.1",
"source": {
"type": "git",
"url": "https://github.com/top-think/framework.git",
"reference": "b538d2615794bfd05455b6f8232a359d09f5a8df"
"reference": "12d15c29d5d6a972fc8bfc8db005d64d4786028c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/top-think/framework/zipball/b538d2615794bfd05455b6f8232a359d09f5a8df",
"reference": "b538d2615794bfd05455b6f8232a359d09f5a8df",
"url": "https://api.github.com/repos/top-think/framework/zipball/12d15c29d5d6a972fc8bfc8db005d64d4786028c",
"reference": "12d15c29d5d6a972fc8bfc8db005d64d4786028c",
"shasum": "",
"mirrors": [
{
@@ -764,7 +820,7 @@
"orm",
"thinkphp"
],
"time": "2019-08-09T07:12:36+00:00"
"time": "2019-08-12T00:58:30+00:00"
},
{
"name": "topthink/think-captcha",
@@ -906,16 +962,16 @@
},
{
"name": "upyun/sdk",
"version": "3.3.0",
"version": "3.4.0",
"source": {
"type": "git",
"url": "https://github.com/upyun/php-sdk.git",
"reference": "1a2dd5ae31047956c733aef0f764f3a527d30628"
"reference": "b4819fd941e3f19a886f8b3c5f8bffcb8279185f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/upyun/php-sdk/zipball/1a2dd5ae31047956c733aef0f764f3a527d30628",
"reference": "1a2dd5ae31047956c733aef0f764f3a527d30628",
"url": "https://api.github.com/repos/upyun/php-sdk/zipball/b4819fd941e3f19a886f8b3c5f8bffcb8279185f",
"reference": "b4819fd941e3f19a886f8b3c5f8bffcb8279185f",
"shasum": "",
"mirrors": [
{
@@ -945,10 +1001,6 @@
"MIT"
],
"authors": [
{
"name": "totoleo",
"email": "totoleo@163.com"
},
{
"name": "lfeng",
"email": "bonevv@gmail.com"
@@ -957,6 +1009,10 @@
"name": "lvtongda",
"email": "riyao.lyu@gmail.com"
},
{
"name": "totoleo",
"email": "totoleo@163.com"
},
{
"name": "sabakugaara",
"email": "senellise@gmail.com"
@@ -968,7 +1024,7 @@
"sdk",
"upyun"
],
"time": "2017-11-12T09:17:42+00:00"
"time": "2019-04-29T09:27:51+00:00"
}
],
"packages-dev": [],
+3 -6
View File
@@ -8,13 +8,10 @@
// [命名规则配置文件]
$array = gettimeofday();
$aa = ($array['sec'] * 100000 + $array['usec'] / 10) & 0x7FFFFFFF;
$logId = ((($array['sec'] * 100000 + $array['usec'] / 10) & 0x7FFFFFFF) | 0x80000000);
$time = time();
$md5 = md5('LSKY PRO' . $logId . time());
$uniqid = substr(md5($logId), 8, 13);
$rand = function_exists('session_create_id') ? session_create_id() : uniqid();
$md5 = md5('LSKY PRO' . $rand . time());
$uniqid = substr(md5($rand), 8, 13);
return [
'path' => [
+4
View File
@@ -29,4 +29,8 @@ return [
'name' => '又拍云USS',
'class' => \strategy\driver\Uss::class
],
'remote' => [
'name' => '远程',
'class' => \strategy\driver\Remote::class
],
];
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* 表字段新增
*/
return [
'lsky_images' => [
'folder_id' => "ALTER TABLE `lsky_images` ADD `folder_id` INT NOT NULL DEFAULT '0' COMMENT '文件夹ID' AFTER `user_id`;",
'suspicious' => "ALTER TABLE `lsky_images` ADD `suspicious` TINYINT(1) NOT NULL DEFAULT '0' COMMENT '可疑图片' AFTER `ip`;",
],
'lsky_users' => [
'default_folder' => "ALTER TABLE `lsky_users` ADD `default_folder` VARCHAR(32) DEFAULT NULL COMMENT '默认上传文件夹' AFTER `quota`;",
'group_id' => "ALTER TABLE `lsky_users` ADD `group_id` int(11) NOT NULL DEFAULT 0 COMMENT '角色组ID' AFTER `id`;"
],
];
+2
View File
@@ -16,6 +16,8 @@ namespace strategy;
*/
interface Driver
{
public function __construct($options = []);
/**
* 创建文件
*
+113
View File
@@ -0,0 +1,113 @@
<?php
/**
* Created by WispX.
* User: WispX <1591788658@qq.com>
* Date: 2019/10/31
* Time: 9:39 上午
* Link: https://github.com/wisp-x
*/
namespace strategy\driver;
use FtpClient\FtpException;
use strategy\driver;
class Remote implements Driver
{
private $ftp;
private $error;
public function __construct($options = [])
{
try {
$this->ftp = new \FtpClient\FtpClient();
$this->ftp->connect($options['remote_host']);
$this->ftp->login($options['remote_name'], $options['remote_password']);
} catch (FtpException $e) {
$this->error = $e->getMessage();
}
}
/**
* 创建文件
*
* @param $pathname
* @param $file
*
* @return mixed
*/
public function create($pathname, $file)
{
try {
$dirname = dirname($pathname);
if (!$this->ftp->isDir($dirname)) {
if (!$this->ftp->mkdir($dirname, true)) {
throw new FtpException('文件夹创建失败!');
}
}
if (!$this->ftp->put($pathname, $file, FTP_BINARY)) {
throw new FtpException('上传失败');
}
} catch (FtpException $e) {
$this->error = $e->getMessage();
return false;
}
return true;
}
/**
* 删除单个文件
*
* @param $pathname
*
* @return mixed
*/
public function delete($pathname)
{
try {
if (!$this->ftp->remove($pathname, true)) {
throw new FtpException('删除失败');
}
} catch (FtpException $e) {
$this->error = $e->getMessage();
return false;
}
return true;
}
/**
* 删除多个文件
*
* @param array $list 一维数组
*
* @return mixed
*/
public function deletes(array $list)
{
try {
foreach ($list as $item) {
if (!$this->ftp->remove($item, true)) {
throw new FtpException('删除失败');
}
}
} catch (FtpException $e) {
$this->error = $e->getMessage();
return false;
}
return true;
}
/**
* 获取出错信息
*
* @return mixed
*/
public function getError()
{
return 'Remote' . $this->error;
}
}
+4 -2
View File
@@ -15,8 +15,10 @@ Route::view('compatibility', 'index@tpl/compatibility');
// [Api Route]
Route::group('api', function () {
Route::post('token', 'api/Token/index');
Route::post('upload', 'api/Upload/index');
Route::any('token', 'api/Token/index');
Route::any('upload', 'api/Upload/index');
Route::any('image', 'api/Image/find');
Route::any('images', 'api/Image/items');
})
->header('Access-Control-Allow-Headers', 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With, Token')
->allowCrossDomain();
+7 -1
View File
@@ -686,7 +686,13 @@ if (!function_exists('widget')) {
*/
function widget($name, $data = [])
{
return app()->action($name, $data, 'widget');
$result = app()->action($name, $data, 'widget');
if (is_object($result)) {
$result = $result->getContent();
}
return $result;
}
}
+1 -1
View File
@@ -353,7 +353,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
$result = isset($data[$field]) ? $data[$field] : null;
}
switch ($operator) {
switch (strtolower($operator)) {
case '===':
return $result === $value;
case '!==':
+4 -1
View File
@@ -160,7 +160,10 @@ class View
*/
public function filter($filter)
{
$this->filter = $filter;
if ($filter) {
$this->filter = $filter;
}
return $this;
}
+11
View File
@@ -76,3 +76,14 @@ UPDATE `lsky_config` SET `value` = '1.5.3' WHERE `lsky_config`.`name` = 'system_
-- v1.5.4
UPDATE `lsky_config` SET `value` = '1.5.4' WHERE `lsky_config`.`name` = 'system_version';
-- v1.5.5
UPDATE `lsky_config` SET `value` = '1.5.5' WHERE `lsky_config`.`name` = 'system_version';
INSERT IGNORE INTO `lsky_config` (`id`, `key`, `type`, `input_type`, `name`, `title`, `tip`, `value`, `extend`) VALUES
(NULL, 'basics', 'textarea', 'textarea', 'notice', '系统公告', '支持html', '', ''),
(NULL, 'remote', 'text', 'text', 'remote_cdn_domain', '域名', NULL, '', ''),
(NULL, 'remote', 'select', 'text', 'remote_type', '远程储存类型', NULL, 'ftp', '{\"ftp\":\"Ftp\"}'),
(NULL, 'remote', 'text', 'text', 'remote_host', '连接地址', NULL, '', ''),
(NULL, 'remote', 'text', 'text', 'remote_name', '登录账号', NULL, '', ''),
(NULL, 'remote', 'text', 'password', 'remote_password', '登录密码', NULL, '', ''),
(NULL, 'remote', 'text', 'number', 'remote_port', '连接端口', NULL, '21', '');
+1 -1
View File
@@ -4,4 +4,4 @@
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitf4c14462dd5d252f636d41b5c1345996::getLoader();
return ComposerAutoloaderInit13f660843321b76d914d974707eb3ce2::getLoader();
+1
View File
@@ -9,4 +9,5 @@ return array(
'Qcloud\\Cos\\' => array($vendorDir . '/qcloud/cos-sdk-v5/src'),
'Guzzle\\Tests' => array($vendorDir . '/guzzle/guzzle/tests'),
'Guzzle' => array($vendorDir . '/guzzle/guzzle/src'),
'FtpClient' => array($vendorDir . '/nicolab/php-ftp-client/src'),
);
+7 -7
View File
@@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitf4c14462dd5d252f636d41b5c1345996
class ComposerAutoloaderInit13f660843321b76d914d974707eb3ce2
{
private static $loader;
@@ -19,15 +19,15 @@ class ComposerAutoloaderInitf4c14462dd5d252f636d41b5c1345996
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitf4c14462dd5d252f636d41b5c1345996', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInit13f660843321b76d914d974707eb3ce2', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitf4c14462dd5d252f636d41b5c1345996', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInit13f660843321b76d914d974707eb3ce2', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitf4c14462dd5d252f636d41b5c1345996::getInitializer($loader));
call_user_func(\Composer\Autoload\ComposerStaticInit13f660843321b76d914d974707eb3ce2::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
@@ -48,19 +48,19 @@ class ComposerAutoloaderInitf4c14462dd5d252f636d41b5c1345996
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInitf4c14462dd5d252f636d41b5c1345996::$files;
$includeFiles = Composer\Autoload\ComposerStaticInit13f660843321b76d914d974707eb3ce2::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequiref4c14462dd5d252f636d41b5c1345996($fileIdentifier, $file);
composerRequire13f660843321b76d914d974707eb3ce2($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequiref4c14462dd5d252f636d41b5c1345996($fileIdentifier, $file)
function composerRequire13f660843321b76d914d974707eb3ce2($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
+11 -4
View File
@@ -4,7 +4,7 @@
namespace Composer\Autoload;
class ComposerStaticInitf4c14462dd5d252f636d41b5c1345996
class ComposerStaticInit13f660843321b76d914d974707eb3ce2
{
public static $files = array (
'7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php',
@@ -129,14 +129,21 @@ class ComposerStaticInitf4c14462dd5d252f636d41b5c1345996
0 => __DIR__ . '/..' . '/guzzle/guzzle/src',
),
),
'F' =>
array (
'FtpClient' =>
array (
0 => __DIR__ . '/..' . '/nicolab/php-ftp-client/src',
),
),
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitf4c14462dd5d252f636d41b5c1345996::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitf4c14462dd5d252f636d41b5c1345996::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInitf4c14462dd5d252f636d41b5c1345996::$prefixesPsr0;
$loader->prefixLengthsPsr4 = ComposerStaticInit13f660843321b76d914d974707eb3ce2::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit13f660843321b76d914d974707eb3ce2::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInit13f660843321b76d914d974707eb3ce2::$prefixesPsr0;
}, null, ClassLoader::class);
}
+111 -53
View File
@@ -154,17 +154,17 @@
},
{
"name": "guzzlehttp/guzzle",
"version": "6.3.3",
"version_normalized": "6.3.3.0",
"version": "6.4.1",
"version_normalized": "6.4.1.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba"
"reference": "0895c932405407fd3a7368b6910c09a24d26db11"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/407b0cb880ace85c9b63c5f9551db498cb2d50ba",
"reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/0895c932405407fd3a7368b6910c09a24d26db11",
"reference": "0895c932405407fd3a7368b6910c09a24d26db11",
"shasum": "",
"mirrors": [
{
@@ -174,19 +174,20 @@
]
},
"require": {
"ext-json": "*",
"guzzlehttp/promises": "^1.0",
"guzzlehttp/psr7": "^1.4",
"guzzlehttp/psr7": "^1.6.1",
"php": ">=5.5"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0",
"psr/log": "^1.0"
"psr/log": "^1.1"
},
"suggest": {
"psr/log": "Required for using the Log middleware"
},
"time": "2018-04-22T15:46:56+00:00",
"time": "2019-10-23T15:58:00+00:00",
"type": "library",
"extra": {
"branch-alias": {
@@ -195,12 +196,12 @@
},
"installation-source": "dist",
"autoload": {
"files": [
"src/functions_include.php"
],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
@@ -364,18 +365,75 @@
]
},
{
"name": "phpmailer/phpmailer",
"version": "v6.0.7",
"version_normalized": "6.0.7.0",
"name": "nicolab/php-ftp-client",
"version": "v1.5.1",
"version_normalized": "1.5.1.0",
"source": {
"type": "git",
"url": "https://github.com/PHPMailer/PHPMailer.git",
"reference": "0c41a36d4508d470e376498c1c0c527aa36a2d59"
"url": "https://github.com/Nicolab/php-ftp-client.git",
"reference": "8c66e1104da1b638f5d7a9e24624a5525b459a0c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/0c41a36d4508d470e376498c1c0c527aa36a2d59",
"reference": "0c41a36d4508d470e376498c1c0c527aa36a2d59",
"url": "https://api.github.com/repos/Nicolab/php-ftp-client/zipball/8c66e1104da1b638f5d7a9e24624a5525b459a0c",
"reference": "8c66e1104da1b638f5d7a9e24624a5525b459a0c",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"ext-ftp": "*",
"php": ">=5.4"
},
"time": "2019-04-23T09:22:37+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-0": {
"FtpClient": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Tallefourtane",
"email": "dev@nicolab.net",
"homepage": "http://nicolab.net"
}
],
"description": "A flexible FTP and SSL-FTP client for PHP. This lib provides helpers easy to use to manage the remote files.",
"homepage": "https://github.com/Nicolab/php-ftp-client",
"keywords": [
"file",
"ftp",
"helper",
"lib",
"server",
"sftp",
"ssl",
"ssl-ftp"
]
},
{
"name": "phpmailer/phpmailer",
"version": "v6.1.1",
"version_normalized": "6.1.1.0",
"source": {
"type": "git",
"url": "https://github.com/PHPMailer/PHPMailer.git",
"reference": "26bd96350b0b2fcbf0ef4e6f0f9cf3528302a9d8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/26bd96350b0b2fcbf0ef4e6f0f9cf3528302a9d8",
"reference": "26bd96350b0b2fcbf0ef4e6f0f9cf3528302a9d8",
"shasum": "",
"mirrors": [
{
@@ -406,7 +464,7 @@
"stevenmaguire/oauth2-microsoft": "Needed for Microsoft XOAUTH2 authentication",
"symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)"
},
"time": "2019-02-01T15:04:28+00:00",
"time": "2019-09-27T21:33:43+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@@ -416,17 +474,17 @@
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-2.1"
"LGPL-2.1-only"
],
"authors": [
{
"name": "Jim Jagielski",
"email": "jimjag@gmail.com"
},
{
"name": "Marcus Bointon",
"email": "phpmailer@synchromedia.co.uk"
},
{
"name": "Jim Jagielski",
"email": "jimjag@gmail.com"
},
{
"name": "Andy Prevost",
"email": "codeworxtech@users.sourceforge.net"
@@ -497,17 +555,17 @@
},
{
"name": "qcloud/cos-sdk-v5",
"version": "v1.3.3",
"version_normalized": "1.3.3.0",
"version": "v1.3.4",
"version_normalized": "1.3.4.0",
"source": {
"type": "git",
"url": "https://github.com/tencentyun/cos-php-sdk-v5.git",
"reference": "cd1b9cefa04521eaf125a82eb53552d9a87aae4d"
"reference": "1b32aa422f6dffe4ea411e5095e4b0da9135551b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/tencentyun/cos-php-sdk-v5/zipball/cd1b9cefa04521eaf125a82eb53552d9a87aae4d",
"reference": "cd1b9cefa04521eaf125a82eb53552d9a87aae4d",
"url": "https://api.github.com/repos/tencentyun/cos-php-sdk-v5/zipball/1b32aa422f6dffe4ea411e5095e4b0da9135551b",
"reference": "1b32aa422f6dffe4ea411e5095e4b0da9135551b",
"shasum": "",
"mirrors": [
{
@@ -520,7 +578,7 @@
"guzzle/guzzle": "~3.7",
"php": ">=5.3.0"
},
"time": "2019-08-07T10:15:47+00:00",
"time": "2019-09-02T12:08:44+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@@ -551,17 +609,17 @@
},
{
"name": "qiniu/php-sdk",
"version": "v7.2.9",
"version_normalized": "7.2.9.0",
"version": "v7.2.10",
"version_normalized": "7.2.10.0",
"source": {
"type": "git",
"url": "https://github.com/qiniu/php-sdk.git",
"reference": "afe7d8715d8a688b1d8d8cdf031240d2363dad90"
"reference": "d89987163f560ebf9dfa5bb25de9bd9b1a3b2bd8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/qiniu/php-sdk/zipball/afe7d8715d8a688b1d8d8cdf031240d2363dad90",
"reference": "afe7d8715d8a688b1d8d8cdf031240d2363dad90",
"url": "https://api.github.com/repos/qiniu/php-sdk/zipball/d89987163f560ebf9dfa5bb25de9bd9b1a3b2bd8",
"reference": "d89987163f560ebf9dfa5bb25de9bd9b1a3b2bd8",
"shasum": "",
"mirrors": [
{
@@ -577,7 +635,7 @@
"phpunit/phpunit": "~4.0",
"squizlabs/php_codesniffer": "~2.3"
},
"time": "2019-07-09T07:55:07+00:00",
"time": "2019-10-28T10:23:23+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@@ -726,17 +784,17 @@
},
{
"name": "topthink/framework",
"version": "v5.1.38",
"version_normalized": "5.1.38.0",
"version": "v5.1.38.1",
"version_normalized": "5.1.38.1",
"source": {
"type": "git",
"url": "https://github.com/top-think/framework.git",
"reference": "b538d2615794bfd05455b6f8232a359d09f5a8df"
"reference": "12d15c29d5d6a972fc8bfc8db005d64d4786028c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/top-think/framework/zipball/b538d2615794bfd05455b6f8232a359d09f5a8df",
"reference": "b538d2615794bfd05455b6f8232a359d09f5a8df",
"url": "https://api.github.com/repos/top-think/framework/zipball/12d15c29d5d6a972fc8bfc8db005d64d4786028c",
"reference": "12d15c29d5d6a972fc8bfc8db005d64d4786028c",
"shasum": "",
"mirrors": [
{
@@ -758,7 +816,7 @@
"sebastian/phpcpd": "2.*",
"squizlabs/php_codesniffer": "2.*"
},
"time": "2019-08-09T07:12:36+00:00",
"time": "2019-08-12T00:58:30+00:00",
"type": "think-framework",
"installation-source": "dist",
"notification-url": "https://packagist.org/downloads/",
@@ -929,17 +987,17 @@
},
{
"name": "upyun/sdk",
"version": "3.3.0",
"version_normalized": "3.3.0.0",
"version": "3.4.0",
"version_normalized": "3.4.0.0",
"source": {
"type": "git",
"url": "https://github.com/upyun/php-sdk.git",
"reference": "1a2dd5ae31047956c733aef0f764f3a527d30628"
"reference": "b4819fd941e3f19a886f8b3c5f8bffcb8279185f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/upyun/php-sdk/zipball/1a2dd5ae31047956c733aef0f764f3a527d30628",
"reference": "1a2dd5ae31047956c733aef0f764f3a527d30628",
"url": "https://api.github.com/repos/upyun/php-sdk/zipball/b4819fd941e3f19a886f8b3c5f8bffcb8279185f",
"reference": "b4819fd941e3f19a886f8b3c5f8bffcb8279185f",
"shasum": "",
"mirrors": [
{
@@ -958,7 +1016,7 @@
"phpdocumentor/phpdocumentor": "^2.9",
"phpunit/phpunit": "~4.0"
},
"time": "2017-11-12T09:17:42+00:00",
"time": "2019-04-29T09:27:51+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@@ -971,10 +1029,6 @@
"MIT"
],
"authors": [
{
"name": "totoleo",
"email": "totoleo@163.com"
},
{
"name": "lfeng",
"email": "bonevv@gmail.com"
@@ -983,6 +1037,10 @@
"name": "lvtongda",
"email": "riyao.lyu@gmail.com"
},
{
"name": "totoleo",
"email": "totoleo@163.com"
},
{
"name": "sabakugaara",
"email": "senellise@gmail.com"
+21
View File
@@ -0,0 +1,21 @@
<?php
$config = PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'declare_strict_types' => false,
'concat_space' => ['spacing'=>'one'],
// 'ordered_imports' => true,
// 'phpdoc_align' => ['align'=>'vertical'],
// 'native_function_invocation' => true,
])
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__.'/src')
->name('*.php')
)
;
return $config;
+17
View File
@@ -1,5 +1,22 @@
# Change Log
## 6.4.1 - 2019-10-23
* No `guzzle.phar` was created in 6.4.0 due expired API token. This release will fix that
* Added `parent::__construct()` to `FileCookieJar` and `SessionCookieJar`
## 6.4.0 - 2019-10-23
* Improvement: Improved error messages when using curl < 7.21.2 [#2108](https://github.com/guzzle/guzzle/pull/2108)
* Fix: Test if response is readable before returning a summary in `RequestException::getResponseBodySummary()` [#2081](https://github.com/guzzle/guzzle/pull/2081)
* Fix: Add support for GUZZLE_CURL_SELECT_TIMEOUT environment variable [#2161](https://github.com/guzzle/guzzle/pull/2161)
* Improvement: Added `GuzzleHttp\Exception\InvalidArgumentException` [#2163](https://github.com/guzzle/guzzle/pull/2163)
* Improvement: Added `GuzzleHttp\_current_time()` to use `hrtime()` if that function exists. [#2242](https://github.com/guzzle/guzzle/pull/2242)
* Improvement: Added curl's `appconnect_time` in `TransferStats` [#2284](https://github.com/guzzle/guzzle/pull/2284)
* Improvement: Make GuzzleException extend Throwable wherever it's available [#2273](https://github.com/guzzle/guzzle/pull/2273)
* Fix: Prevent concurrent writes to file when saving `CookieJar` [#2335](https://github.com/guzzle/guzzle/pull/2335)
* Improvement: Update `MockHandler` so we can test transfer time [#2362](https://github.com/guzzle/guzzle/pull/2362)
## 6.3.3 - 2018-04-22
* Fix: Default headers when decode_content is specified
+18
View File
@@ -0,0 +1,18 @@
FROM composer:latest as setup
RUN mkdir /guzzle
WORKDIR /guzzle
RUN set -xe \
&& composer init --name=guzzlehttp/test --description="Simple project for testing Guzzle scripts" --author="Márk Sági-Kazár <mark.sagikazar@gmail.com>" --no-interaction \
&& composer require guzzlehttp/guzzle
FROM php:7.3
RUN mkdir /guzzle
WORKDIR /guzzle
COPY --from=setup /guzzle /guzzle
+10 -11
View File
@@ -21,19 +21,18 @@ trivial to integrate with web services.
```php
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
echo $res->getStatusCode();
// 200
echo $res->getHeaderLine('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// '{"id": 1420053, "name": "guzzle", ...}'
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
// Send an asynchronous request.
echo $response->getStatusCode(); # 200
echo $response->getHeaderLine('content-type'); # 'application/json; charset=utf8'
echo $response->getBody(); # '{"id": 1420053, "name": "guzzle", ...}'
# Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
```
@@ -57,7 +56,7 @@ curl -sS https://getcomposer.org/installer | php
Next, run the Composer command to install the latest stable version of Guzzle:
```bash
php composer.phar require guzzlehttp/guzzle
composer require guzzlehttp/guzzle
```
After installing, you need to require Composer's autoloader:
@@ -69,7 +68,7 @@ require 'vendor/autoload.php';
You can then later update Guzzle using composer:
```bash
composer.phar update
composer update
```
@@ -86,6 +85,6 @@ composer.phar update
[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x
[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3
[guzzle-6-repo]: https://github.com/guzzle/guzzle
[guzzle-3-docs]: http://guzzle3.readthedocs.org/en/latest/
[guzzle-3-docs]: http://guzzle3.readthedocs.org
[guzzle-5-docs]: http://guzzle.readthedocs.org/en/5.3/
[guzzle-6-docs]: http://guzzle.readthedocs.org/en/latest/
+29 -15
View File
@@ -2,7 +2,15 @@
"name": "guzzlehttp/guzzle",
"type": "library",
"description": "Guzzle is a PHP HTTP client library",
"keywords": ["framework", "http", "rest", "web service", "curl", "client", "HTTP client"],
"keywords": [
"framework",
"http",
"rest",
"web service",
"curl",
"client",
"HTTP client"
],
"homepage": "http://guzzlephp.org/",
"license": "MIT",
"authors": [
@@ -14,31 +22,37 @@
],
"require": {
"php": ">=5.5",
"guzzlehttp/psr7": "^1.4",
"guzzlehttp/promises": "^1.0"
"ext-json": "*",
"guzzlehttp/promises": "^1.0",
"guzzlehttp/psr7": "^1.6.1"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0",
"psr/log": "^1.0"
},
"autoload": {
"files": ["src/functions_include.php"],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Tests\\": "tests/"
}
"psr/log": "^1.1"
},
"suggest": {
"psr/log": "Required for using the Log middleware"
},
"config": {
"sort-packages": true
},
"extra": {
"branch-alias": {
"dev-master": "6.3-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Tests\\": "tests/"
}
}
}
+9
View File
@@ -0,0 +1,9 @@
parameters:
level: 1
paths:
- src
ignoreErrors:
-
message: '#Function uri_template not found#'
path: %currentWorkingDirectory%/src/functions.php
+1 -1
View File
@@ -210,7 +210,7 @@ class Client implements ClientInterface
*
* @return array
*/
private function prepareDefaults($options)
private function prepareDefaults(array $options)
{
$defaults = $this->config;
+1 -1
View File
@@ -12,7 +12,7 @@ use Psr\Http\Message\UriInterface;
*/
interface ClientInterface
{
const VERSION = '6.3.3';
const VERSION = '6.4.1';
/**
* Send an HTTP request.
+1 -1
View File
@@ -120,7 +120,7 @@ class CookieJar implements CookieJarInterface
} elseif (!$path) {
$this->cookies = array_filter(
$this->cookies,
function (SetCookie $cookie) use ($path, $domain) {
function (SetCookie $cookie) use ($domain) {
return !$cookie->matchesDomain($domain);
}
);
+2 -1
View File
@@ -23,6 +23,7 @@ class FileCookieJar extends CookieJar
*/
public function __construct($cookieFile, $storeSessionCookies = false)
{
parent::__construct();
$this->filename = $cookieFile;
$this->storeSessionCookies = $storeSessionCookies;
@@ -56,7 +57,7 @@ class FileCookieJar extends CookieJar
}
$jsonStr = \GuzzleHttp\json_encode($json);
if (false === file_put_contents($filename, $jsonStr)) {
if (false === file_put_contents($filename, $jsonStr, LOCK_EX)) {
throw new \RuntimeException("Unable to save file {$filename}");
}
}
@@ -22,6 +22,7 @@ class SessionCookieJar extends CookieJar
*/
public function __construct($sessionKey, $storeSessionCookies = false)
{
parent::__construct();
$this->sessionKey = $sessionKey;
$this->storeSessionCookies = $storeSessionCookies;
$this->load();
+2 -2
View File
@@ -227,7 +227,7 @@ class SetCookie
/**
* Get whether or not this is a secure cookie
*
* @return null|bool
* @return bool|null
*/
public function getSecure()
{
@@ -247,7 +247,7 @@ class SetCookie
/**
* Get whether or not this is a session cookie
*
* @return null|bool
* @return bool|null
*/
public function getDiscard()
{
+3 -1
View File
@@ -4,4 +4,6 @@ namespace GuzzleHttp\Exception;
/**
* Exception when a client error is encountered (4xx codes)
*/
class ClientException extends BadResponseException {}
class ClientException extends BadResponseException
{
}
+20 -10
View File
@@ -1,13 +1,23 @@
<?php
namespace GuzzleHttp\Exception;
/**
* @method string getMessage()
* @method \Throwable|null getPrevious()
* @method mixed getCode()
* @method string getFile()
* @method int getLine()
* @method array getTrace()
* @method string getTraceAsString()
*/
interface GuzzleException {}
use Throwable;
if (interface_exists(Throwable::class)) {
interface GuzzleException extends Throwable
{
}
} else {
/**
* @method string getMessage()
* @method \Throwable|null getPrevious()
* @method mixed getCode()
* @method string getFile()
* @method int getLine()
* @method array getTrace()
* @method string getTraceAsString()
*/
interface GuzzleException
{
}
}
@@ -0,0 +1,7 @@
<?php
namespace GuzzleHttp\Exception;
final class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException
{
}
@@ -126,7 +126,7 @@ class RequestException extends TransferException
{
$body = $response->getBody();
if (!$body->isSeekable()) {
if (!$body->isSeekable() || !$body->isReadable()) {
return null;
}
+3 -1
View File
@@ -4,4 +4,6 @@ namespace GuzzleHttp\Exception;
/**
* Exception when a server error is encountered (5xx codes)
*/
class ServerException extends BadResponseException {}
class ServerException extends BadResponseException
{
}
@@ -1,4 +1,6 @@
<?php
namespace GuzzleHttp\Exception;
class TooManyRedirectsException extends RequestException {}
class TooManyRedirectsException extends RequestException
{
}
@@ -1,4 +1,6 @@
<?php
namespace GuzzleHttp\Exception;
class TransferException extends \RuntimeException implements GuzzleException {}
class TransferException extends \RuntimeException implements GuzzleException
{
}
+22 -7
View File
@@ -14,6 +14,9 @@ use Psr\Http\Message\RequestInterface;
*/
class CurlFactory implements CurlFactoryInterface
{
const CURL_VERSION_STR = 'curl_version';
const LOW_CURL_VERSION_NUMBER = '7.21.2';
/** @var array */
private $handles = [];
@@ -117,6 +120,7 @@ class CurlFactory implements CurlFactoryInterface
private static function invokeStats(EasyHandle $easy)
{
$curlStats = curl_getinfo($easy->handle);
$curlStats['appconnect_time'] = curl_getinfo($easy->handle, CURLINFO_APPCONNECT_TIME);
$stats = new TransferStats(
$easy->request,
$easy->response,
@@ -136,7 +140,9 @@ class CurlFactory implements CurlFactoryInterface
$ctx = [
'errno' => $easy->errno,
'error' => curl_error($easy->handle),
'appconnect_time' => curl_getinfo($easy->handle, CURLINFO_APPCONNECT_TIME),
] + curl_getinfo($easy->handle);
$ctx[self::CURL_VERSION_STR] = curl_version()['version'];
$factory->release($easy);
// Retry when nothing is present or when curl failed to rewind.
@@ -172,13 +178,22 @@ class CurlFactory implements CurlFactoryInterface
)
);
}
$message = sprintf(
'cURL error %s: %s (%s)',
$ctx['errno'],
$ctx['error'],
'see http://curl.haxx.se/libcurl/c/libcurl-errors.html'
);
if (version_compare($ctx[self::CURL_VERSION_STR], self::LOW_CURL_VERSION_NUMBER)) {
$message = sprintf(
'cURL error %s: %s (%s)',
$ctx['errno'],
$ctx['error'],
'see https://curl.haxx.se/libcurl/c/libcurl-errors.html'
);
} else {
$message = sprintf(
'cURL error %s: %s (%s) for %s',
$ctx['errno'],
$ctx['error'],
'see https://curl.haxx.se/libcurl/c/libcurl-errors.html',
$easy->request->getUri()
);
}
// Create a connection exception if it was a specific error code.
$error = isset($connectionErrors[$easy->errno])
+11 -5
View File
@@ -37,8 +37,14 @@ class CurlMultiHandler
{
$this->factory = isset($options['handle_factory'])
? $options['handle_factory'] : new CurlFactory(50);
$this->selectTimeout = isset($options['select_timeout'])
? $options['select_timeout'] : 1;
if (isset($options['select_timeout'])) {
$this->selectTimeout = $options['select_timeout'];
} elseif ($selectTimeout = getenv('GUZZLE_CURL_SELECT_TIMEOUT')) {
$this->selectTimeout = $selectTimeout;
} else {
$this->selectTimeout = 1;
}
}
public function __get($name)
@@ -82,7 +88,7 @@ class CurlMultiHandler
{
// Add any delayed handles if needed.
if ($this->delays) {
$currentTime = microtime(true);
$currentTime = \GuzzleHttp\_current_time();
foreach ($this->delays as $id => $delay) {
if ($currentTime >= $delay) {
unset($this->delays[$id]);
@@ -134,7 +140,7 @@ class CurlMultiHandler
if (empty($easy->options['delay'])) {
curl_multi_add_handle($this->_mh, $easy->handle);
} else {
$this->delays[$id] = microtime(true) + ($easy->options['delay'] / 1000);
$this->delays[$id] = \GuzzleHttp\_current_time() + ($easy->options['delay'] / 1000);
}
}
@@ -186,7 +192,7 @@ class CurlMultiHandler
private function timeToNext()
{
$currentTime = microtime(true);
$currentTime = \GuzzleHttp\_current_time();
$nextTime = PHP_INT_MAX;
foreach ($this->delays as $time) {
if ($time < $nextTime) {
+2 -1
View File
@@ -182,7 +182,8 @@ class MockHandler implements \Countable
$reason = null
) {
if (isset($options['on_stats'])) {
$stats = new TransferStats($request, $response, 0, $reason);
$transferTime = isset($options['transfer_time']) ? $options['transfer_time'] : 0;
$stats = new TransferStats($request, $response, $transferTime, $reason);
call_user_func($options['on_stats'], $stats);
}
}
+17 -5
View File
@@ -33,7 +33,7 @@ class StreamHandler
usleep($options['delay'] * 1000);
}
$startTime = isset($options['on_stats']) ? microtime(true) : null;
$startTime = isset($options['on_stats']) ? \GuzzleHttp\_current_time() : null;
try {
// Does not support the expect header.
@@ -42,7 +42,7 @@ class StreamHandler
// Append a content-length header if body size is zero to match
// cURL's behavior.
if (0 === $request->getBody()->getSize()) {
$request = $request->withHeader('Content-Length', 0);
$request = $request->withHeader('Content-Length', '0');
}
return $this->createResponse(
@@ -82,7 +82,7 @@ class StreamHandler
$stats = new TransferStats(
$request,
$response,
microtime(true) - $startTime,
\GuzzleHttp\_current_time() - $startTime,
$error,
[]
);
@@ -343,13 +343,25 @@ class StreamHandler
if ('v4' === $options['force_ip_resolve']) {
$records = dns_get_record($uri->getHost(), DNS_A);
if (!isset($records[0]['ip'])) {
throw new ConnectException(sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request);
throw new ConnectException(
sprintf(
"Could not resolve IPv4 address for host '%s'",
$uri->getHost()
),
$request
);
}
$uri = $uri->withHost($records[0]['ip']);
} elseif ('v6' === $options['force_ip_resolve']) {
$records = dns_get_record($uri->getHost(), DNS_AAAA);
if (!isset($records[0]['ipv6'])) {
throw new ConnectException(sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request);
throw new ConnectException(
sprintf(
"Could not resolve IPv6 address for host '%s'",
$uri->getHost()
),
$request
);
}
$uri = $uri->withHost('[' . $records[0]['ipv6'] . ']');
}
+4 -4
View File
@@ -206,7 +206,7 @@ class HandlerStack
}
/**
* @param $name
* @param string $name
* @return int
*/
private function findByName($name)
@@ -223,10 +223,10 @@ class HandlerStack
/**
* Splices a function into the middleware list at a specific position.
*
* @param $findName
* @param $withName
* @param string $findName
* @param string $withName
* @param callable $middleware
* @param $before
* @param bool $before
*/
private function splice($findName, $withName, callable $middleware, $before)
{
+3 -4
View File
@@ -7,7 +7,6 @@ use GuzzleHttp\Promise\RejectedPromise;
use GuzzleHttp\Psr7;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* Functions used to create and wrap handlers with handler middleware.
@@ -39,7 +38,7 @@ final class Middleware
$cookieJar->extractCookies($request, $response);
return $response;
}
);
);
};
};
}
@@ -58,7 +57,7 @@ final class Middleware
return $handler($request, $options);
}
return $handler($request, $options)->then(
function (ResponseInterface $response) use ($request, $handler) {
function (ResponseInterface $response) use ($request) {
$code = $response->getStatusCode();
if ($code < 400) {
return $response;
@@ -183,7 +182,7 @@ final class Middleware
*
* @return callable Returns a function that accepts the next handler.
*/
public static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = LogLevel::INFO)
public static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = 'info' /* \Psr\Log\LogLevel::INFO */)
{
return function (callable $handler) use ($logger, $formatter, $logLevel) {
return function ($request, array $options) use ($handler, $logger, $formatter, $logLevel) {
+1 -1
View File
@@ -6,7 +6,7 @@ use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Promise\EachPromise;
/**
* Sends and iterator of requests concurrently using a capped pool size.
* Sends an iterator of requests concurrently using a capped pool size.
*
* The pool will read from an iterator until it is cancelled or until the
* iterator is consumed. When a request is yielded, the request is sent after
+1 -1
View File
@@ -186,7 +186,7 @@ class RedirectMiddleware
if ($options['allow_redirects']['referer']
&& $modify['uri']->getScheme() === $request->getUri()->getScheme()
) {
$uri = $request->getUri()->withUserInfo('', '');
$uri = $request->getUri()->withUserInfo('');
$modify['set_headers']['Referer'] = (string) $uri;
} else {
$modify['remove_headers'][] = 'Referer';
+1 -1
View File
@@ -22,7 +22,7 @@ final class RequestOptions
* - strict: (bool, default=false) Set to true to use strict redirects
* meaning redirect POST requests with POST requests vs. doing what most
* browsers do which is redirect POST requests with GET requests
* - referer: (bool, default=true) Set to false to disable the Referer
* - referer: (bool, default=false) Set to true to enable the Referer
* header.
* - protocols: (array, default=['http', 'https']) Allowed redirect
* protocols.
+4 -1
View File
@@ -19,6 +19,9 @@ class RetryMiddleware
/** @var callable */
private $decider;
/** @var callable */
private $delay;
/**
* @param callable $decider Function that accepts the number of retries,
* a request, [response], and [exception] and
@@ -42,7 +45,7 @@ class RetryMiddleware
/**
* Default exponential backoff delay function.
*
* @param $retries
* @param int $retries
*
* @return int
*/
+1 -1
View File
@@ -20,7 +20,7 @@ final class TransferStats
/**
* @param RequestInterface $request Request that was sent.
* @param ResponseInterface $response Response received (if any)
* @param null $transferTime Total handler transfer time.
* @param float|null $transferTime Total handler transfer time.
* @param mixed $handlerErrorData Handler error data.
* @param array $handlerStats Handler specific stats.
*/
+18 -5
View File
@@ -196,7 +196,8 @@ function default_ca_bundle()
}
}
throw new \RuntimeException(<<< EOT
throw new \RuntimeException(
<<< EOT
No system CA bundle could be found in any of the the common system locations.
PHP versions earlier than 5.6 are not properly configured to use the system's
CA bundle by default. In order to verify peer certificates, you will need to
@@ -294,14 +295,14 @@ function is_host_in_noproxy($host, array $noProxyArray)
* @param int $options Bitmask of JSON decode options.
*
* @return mixed
* @throws \InvalidArgumentException if the JSON cannot be decoded.
* @throws Exception\InvalidArgumentException if the JSON cannot be decoded.
* @link http://www.php.net/manual/en/function.json-decode.php
*/
function json_decode($json, $assoc = false, $depth = 512, $options = 0)
{
$data = \json_decode($json, $assoc, $depth, $options);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(
throw new Exception\InvalidArgumentException(
'json_decode error: ' . json_last_error_msg()
);
}
@@ -317,17 +318,29 @@ function json_decode($json, $assoc = false, $depth = 512, $options = 0)
* @param int $depth Set the maximum depth. Must be greater than zero.
*
* @return string
* @throws \InvalidArgumentException if the JSON cannot be encoded.
* @throws Exception\InvalidArgumentException if the JSON cannot be encoded.
* @link http://www.php.net/manual/en/function.json-encode.php
*/
function json_encode($value, $options = 0, $depth = 512)
{
$json = \json_encode($value, $options, $depth);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(
throw new Exception\InvalidArgumentException(
'json_encode error: ' . json_last_error_msg()
);
}
return $json;
}
/**
* Wrapper for the hrtime() or microtime() functions
* (depending on the PHP version, one of the two is used)
*
* @return float|mixed UNIX timestamp
* @internal
*/
function _current_time()
{
return function_exists('hrtime') ? hrtime(true) / 1e9 : microtime(true);
}
+7
View File
@@ -0,0 +1,7 @@
/vendor
composer.phar
composer.lock
.DS_Store
Thumbs.db
/.Trash-1000
.idea/
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014 Nicolas Tallefourtane dev@nicolab.net
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+249
View File
@@ -0,0 +1,249 @@
# nicolab/php-ftp-client
A flexible FTP and SSL-FTP client for PHP.
This lib provides helpers easy to use to manage the remote files.
> This package is aimed to remain simple and light. It's only a wrapper of the FTP native API of PHP, with some useful helpers. If you want to customize some methods, you can do this by inheriting one of the [3 classes of the package](src/FtpClient).
## Install
* Use composer: _require_ `nicolab/php-ftp-client`
* Or use GIT clone command: `git clone git@github.com:Nicolab/php-ftp-client.git`
* Or download the library, configure your autoloader or include the 3 files of `php-ftp-client/src/FtpClient` directory.
## Getting Started
Connect to a server FTP :
```php
$ftp = new \FtpClient\FtpClient();
$ftp->connect($host);
$ftp->login($login, $password);
```
OR
Connect to a server FTP via SSL (on port 990 or another port) :
```php
$ftp = new \FtpClient\FtpClient();
$ftp->connect($host, true, 990);
$ftp->login($login, $password);
```
Note: The connection is implicitly closed at the end of script execution (when the object is destroyed). Therefore it is unnecessary to call `$ftp->close()`, except for an explicit re-connection.
### Usage
Upload all files and all directories is easy :
```php
// upload with the BINARY mode
$ftp->putAll($source_directory, $target_directory);
// Is equal to
$ftp->putAll($source_directory, $target_directory, FTP_BINARY);
// or upload with the ASCII mode
$ftp->putAll($source_directory, $target_directory, FTP_ASCII);
```
*Note : FTP_ASCII and FTP_BINARY are predefined PHP internal constants.*
Get a directory size :
```php
// size of the current directory
$size = $ftp->dirSize();
// size of a given directory
$size = $ftp->dirSize('/path/of/directory');
```
Count the items in a directory :
```php
// count in the current directory
$total = $ftp->count();
// count in a given directory
$total = $ftp->count('/path/of/directory');
// count only the "files" in the current directory
$total_file = $ftp->count('.', 'file');
// count only the "files" in a given directory
$total_file = $ftp->count('/path/of/directory', 'file');
// count only the "directories" in a given directory
$total_dir = $ftp->count('/path/of/directory', 'directory');
// count only the "symbolic links" in a given directory
$total_link = $ftp->count('/path/of/directory', 'link');
```
Detailed list of all files and directories :
```php
// scan the current directory and returns the details of each item
$items = $ftp->scanDir();
// scan the current directory (recursive) and returns the details of each item
var_dump($ftp->scanDir('.', true));
```
Result:
'directory#www' =>
array (size=10)
'permissions' => string 'drwx---r-x' (length=10)
'number' => string '3' (length=1)
'owner' => string '32385' (length=5)
'group' => string 'users' (length=5)
'size' => string '5' (length=1)
'month' => string 'Nov' (length=3)
'day' => string '24' (length=2)
'time' => string '17:25' (length=5)
'name' => string 'www' (length=3)
'type' => string 'directory' (length=9)
'link#www/index.html' =>
array (size=11)
'permissions' => string 'lrwxrwxrwx' (length=10)
'number' => string '1' (length=1)
'owner' => string '0' (length=1)
'group' => string 'users' (length=5)
'size' => string '38' (length=2)
'month' => string 'Nov' (length=3)
'day' => string '16' (length=2)
'time' => string '14:57' (length=5)
'name' => string 'index.html' (length=10)
'type' => string 'link' (length=4)
'target' => string '/var/www/shared/index.html' (length=26)
'file#www/README' =>
array (size=10)
'permissions' => string '-rw----r--' (length=10)
'number' => string '1' (length=1)
'owner' => string '32385' (length=5)
'group' => string 'users' (length=5)
'size' => string '0' (length=1)
'month' => string 'Nov' (length=3)
'day' => string '24' (length=2)
'time' => string '17:25' (length=5)
'name' => string 'README' (length=6)
'type' => string 'file' (length=4)
All FTP PHP functions are supported and some improved :
```php
// Requests execution of a command on the FTP server
$ftp->exec($command);
// Turns passive mode on or off
$ftp->pasv(true);
// Set permissions on a file via FTP
$ftp->chmod(0777, 'file.php');
// Removes a directory
$ftp->rmdir('path/of/directory/to/remove');
// Removes a directory (recursive)
$ftp->rmdir('path/of/directory/to/remove', true);
// Creates a directory
$ftp->mkdir('path/of/directory/to/create');
// Creates a directory (recursive),
// creates automaticaly the sub directory if not exist
$ftp->mkdir('path/of/directory/to/create', true);
// and more ...
```
Get the help information of remote FTP server :
```php
var_dump($ftp->help());
```
Result :
array (size=6)
0 => string '214-The following SITE commands are recognized' (length=46)
1 => string ' ALIAS' (length=6)
2 => string ' CHMOD' (length=6)
3 => string ' IDLE' (length=5)
4 => string ' UTIME' (length=6)
5 => string '214 Pure-FTPd - http://pureftpd.org/' (length=36)
_Note : The result depend of FTP server._
### Extend
Create your custom `FtpClient`.
```php
// MyFtpClient.php
/**
* My custom FTP Client
* @inheritDoc
*/
class MyFtpClient extends \FtpClient\FtpClient {
public function removeByTime($path, $timestamp) {
// your code here
}
public function search($regex) {
// your code here
}
}
```
```php
// example.php
$ftp = new MyFtpClient();
$ftp->connect($host);
$ftp->login($login, $password);
// remove the old files
$ftp->removeByTime('/www/mysite.com/demo', time() - 86400));
// search PNG files
$ftp->search('/(.*)\.png$/i');
```
## API doc
See the [source code](https://github.com/Nicolab/php-ftp-client/tree/master/src/FtpClient) for more details.
It is fully documented :blue_book:
## Testing
Tested with "atoum" unit testing framework.
## License
[MIT](https://github.com/Nicolab/php-ftp-client/blob/master/LICENSE) c) 2014, Nicolas Tallefourtane.
## Author
| [![Nicolas Tallefourtane - Nicolab.net](http://www.gravatar.com/avatar/d7dd0f4769f3aa48a3ecb308f0b457fc?s=64)](http://nicolab.net) |
|---|
| [Nicolas Talle](http://nicolab.net) |
| [![Make a donation via Paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=PGRH4ZXP36GUC) |
+23
View File
@@ -0,0 +1,23 @@
{
"name": "nicolab/php-ftp-client",
"type": "library",
"description": "A flexible FTP and SSL-FTP client for PHP. This lib provides helpers easy to use to manage the remote files.",
"license": "MIT",
"keywords": ["ftp", "sftp", "ssl-ftp", "ssl", "file", "server", "lib", "helper"],
"homepage": "https://github.com/Nicolab/php-ftp-client",
"authors" : [
{
"name" : "Nicolas Tallefourtane",
"email" : "dev@nicolab.net",
"homepage" : "http://nicolab.net"
}
],
"require": {
"php": ">=5.4",
"ext-ftp": "*"
},
"autoload": {
"psr-0": {"FtpClient": "src/"}
}
}
@@ -0,0 +1,938 @@
<?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($ignore_user_abort);
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) {
$result = $files;
// 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 ($part == '') {
continue;
}
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;
}
/**
* Downloads a file from the FTP server into a string
*
* @param string $remote_file
* @param int $mode
* @param int $resumepos
* @return string|null
*/
public function getContent($remote_file, $mode = FTP_BINARY, $resumepos = 0)
{
$handle = fopen('php://temp', 'r+');
if ($this->fget($handle, $remote_file, $mode, $resumepos)) {
rewind($handle);
return stream_get_contents($handle);
}
return null;
}
/**
* 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;
}
/**
* Downloads all files from remote FTP directory
*
* @param string $source_directory The remote directory
* @param string $target_directory The local directory
* @param int $mode
* @return FtpClient
*/
public function getAll($source_directory, $target_directory, $mode = FTP_BINARY)
{
if ($source_directory != ".") {
if ($this->ftp->chdir($source_directory) == false) {
throw new FtpException("Unable to change directory: ".$source_directory);
}
if (!(is_dir($source_directory))) {
mkdir($source_directory);
}
chdir($source_directory);
}
$contents = $this->ftp->nlist(".");
foreach ($contents as $file) {
if ($file == '.' || $file == '..') {
continue;
}
$this->ftp->get($target_directory."/".$file, $file, $mode);
}
$this->ftp->chdir("..");
chdir("..");
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.');
}
if (strpos($directory, " ") > 0) {
$ftproot = $this->ftp->pwd();
$this->ftp->chdir($directory);
$list = $this->ftp->rawlist("");
$this->ftp->chdir($ftproot);
} else {
$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, 9);
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;
}
// Prepare for filename that has space
$nameSlices = array_slice($chunks, 8, true);
$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' => implode(' ', $nameSlices),
'type' => $this->rawToType($chunks[0]),
];
if ($item['type'] == 'link' && isset($chunks[10])) {
$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;
}
}
@@ -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 {}
@@ -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);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
use \mageekguy\atoum;
$report = $script->addDefaultReport();
// This will add a green or red logo after each run depending on its status.
$report->addField(new atoum\report\fields\runner\result\logo());
$script->bootstrapFile(__DIR__. '/bootstrap.php');
$runner->addTestsFromDirectory(__DIR__. '/units');
+6
View File
@@ -0,0 +1,6 @@
<?php
if (!defined('FTP_CLIENT_TEST_VENDOR')) {
define('FTP_CLIENT_TEST_VENDOR', __DIR__ . '/../../../');
}
$loader = require_once FTP_CLIENT_TEST_VENDOR . '/autoload.php';
@@ -0,0 +1,34 @@
<?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 tests\units\FtpClient;
use
mageekguy\atoum,
FtpClient\FtpClient as TestedClass
;
/**
* Tests the FtpClient\FtpClient class.
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpClient extends atoum\test
{
public function test__construct()
{
$this
->given($ftp = new TestedClass())
->object($ftp)
->isInstanceOf('\FtpClient\FtpClient')
;
}
}
@@ -0,0 +1,43 @@
<?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 tests\units\FtpClient;
use
mageekguy\atoum,
FtpClient\FtpException as TestedClass
;
/**
* Tests the FtpClient\FtpException class.
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpException extends atoum\test
{
public function test__instance()
{
$ftp = new \FtpClient\FtpClient();
$this
->given($e = new TestedClass())
->object($e)
->isInstanceOf('\FtpClient\FtpException')
->isInstanceOf('\Exception')
->exception(function () use ($ftp) {
$ftp->doNotExist();
})
->isInstanceOf('\FtpClient\FtpException')
->isInstanceOf('\Exception')
;
}
}
@@ -0,0 +1,53 @@
<?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 tests\units\FtpClient;
use
mageekguy\atoum,
FtpClient\FtpWrapper as TestedClass
;
/**
* Tests the FtpClient\FtpWrapper class.
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpWrapper extends atoum\test
{
public function test__construct()
{
$conn = null;
$this
->given($wrapper = new TestedClass($conn))
->object($wrapper)
->isInstanceOf('\FtpClient\FtpWrapper')
;
}
public function test__call()
{
$conn = null;
$this
->given($wrapper = new TestedClass($conn))
->exception(function () use ($wrapper) {
$wrapper->doNotExist();
})
->isInstanceOf('\FtpClient\FtpException')
->isInstanceOf('\Exception')
->variable(array($wrapper, 'alloc'))
->isCallable()
;
}
}
+29 -26
View File
@@ -10,13 +10,13 @@ Build status: [![Build Status](https://travis-ci.org/PHPMailer/PHPMailer.svg)](h
## Class Features
- Probably the world's most popular code for sending email from PHP!
- Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more
- Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla!, and many more
- Integrated SMTP support - send without a local mail server
- Send emails with multiple To, CC, BCC and Reply-to addresses
- Multipart/alternative emails for mail clients that do not read HTML email
- Add attachments, including inline
- Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings
- SMTP authentication with LOGIN, PLAIN, CRAM-MD5 and XOAUTH2 mechanisms over SSL and SMTP+STARTTLS transports
- SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SSL and SMTP+STARTTLS transports
- Validates email addresses automatically
- Protect against header injection attacks
- Error messages in over 50 languages!
@@ -26,12 +26,12 @@ Build status: [![Build Status](https://travis-ci.org/PHPMailer/PHPMailer.svg)](h
- Much more!
## Why you might need it
Many PHP developers utilize email in their code. The only PHP function that supports this is the `mail()` function. However, it does not provide any assistance for making use of popular features such as HTML-based emails and attachments.
Many PHP developers need to send email from their code. The only PHP function that supports this is [`mail()`](https://www.php.net/manual/en/function.mail.php). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.
Formatting email correctly is surprisingly difficult. There are myriad overlapping RFCs, requiring tight adherence to horribly complicated formatting and encoding rules - the vast majority of code that you'll find online that uses the `mail()` function directly is just plain wrong!
*Please* don't be tempted to do it yourself - if you don't use PHPMailer, there are many other excellent libraries that you should look at before rolling your own - try [SwiftMailer](https://swiftmailer.symfony.com/), [Zend/Mail](https://zendframework.github.io/zend-mail/), [eZcomponents](https://github.com/zetacomponents/Mail) etc.
Formatting email correctly is surprisingly difficult. There are myriad overlapping RFCs, requiring tight adherence to horribly complicated formatting and encoding rules the vast majority of code that you'll find online that uses the `mail()` function directly is just plain wrong!
*Please* don't be tempted to do it yourself if you don't use PHPMailer, there are many other excellent libraries that you should look at before rolling your own. Try [SwiftMailer](https://swiftmailer.symfony.com/), [Zend/Mail](https://zendframework.github.io/zend-mail/), [ZetaComponents](https://github.com/zetacomponents/Mail) etc.
The PHP `mail()` function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD and OS X platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP implementation allows email sending on Windows platforms without a local mail server.
The PHP `mail()` function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD, and macOS platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP implementation allows email sending on Windows platforms without a local mail server.
## License
This software is distributed under the [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html) license, along with the [GPL Cooperation Commitment](https://gplcc.github.io/gplcc/). Please read LICENSE for information on the software availability and distribution.
@@ -40,7 +40,7 @@ This software is distributed under the [LGPL 2.1](http://www.gnu.org/licenses/lg
PHPMailer is available on [Packagist](https://packagist.org/packages/phpmailer/phpmailer) (using semantic versioning), and installation via [Composer](https://getcomposer.org) is the recommended way to install PHPMailer. Just add this line to your `composer.json` file:
```json
"phpmailer/phpmailer": "~6.0"
"phpmailer/phpmailer": "~6.1"
```
or run
@@ -70,15 +70,13 @@ If you're not using the `SMTP` class explicitly (you're probably not), you don't
If you don't speak git or just want a tarball, click the 'zip' button on the right of the project page in GitHub, though note that docs and examples are not included in the tarball.
## Legacy versions
PHPMailer 5.2 (which is compatible with PHP 5.0 - 7.0) is no longer being supported for feature updates, and will only be receiving security updates from now on. You will find the latest version of 5.2 in the [5.2-stable branch](https://github.com/PHPMailer/PHPMailer/tree/5.2-stable), and future versions of 5.2 will be tagged with 5.2.x version numbers, so existing Composer configs should remain working. If you're using PHP 5.5 or later, we recommend you make the necessary changes to switch to the 6.0 release.
PHPMailer 5.2 (which is compatible with PHP 5.0 - 7.0) is no longer being supported, even for security updates. You will find the latest version of 5.2 in the [5.2-stable branch](https://github.com/PHPMailer/PHPMailer/tree/5.2-stable). If you're using PHP 5.5 or later (which you should be), switch to the 6.x releases.
The 5.2 branch will not receive security updates after December 31st 2018.
## Upgrading from 5.2
### Upgrading from 5.2
The biggest changes are that source files are now in the `src/` folder, and PHPMailer now declares the namespace `PHPMailer\PHPMailer`. This has several important effects [read the upgrade guide](https://github.com/PHPMailer/PHPMailer/tree/master/UPGRADING.md) for more details.
### Minimal installation
While installing the entire package manually or with Composer is simple, convenient and reliable, you may want to include only vital files in your project. At the very least you will need [src/PHPMailer.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/PHPMailer.php). If you're using SMTP, you'll need [src/SMTP.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/SMTP.php), and if you're using POP-before SMTP, you'll need [src/POP3.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/POP3.php). You can skip the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder if you're not showing errors to users and can make do with English-only errors. If you're using XOAUTH2 you will need [src/OAuth.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/OAuth.php) as well as the Composer dependencies for the services you wish to authenticate with. Really, it's much easier to use Composer!
While installing the entire package manually or with Composer is simple, convenient, and reliable, you may want to include only vital files in your project. At the very least you will need [src/PHPMailer.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/PHPMailer.php). If you're using SMTP, you'll need [src/SMTP.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/SMTP.php), and if you're using POP-before SMTP, you'll need [src/POP3.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/POP3.php). You can skip the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder if you're not showing errors to users and can make do with English-only errors. If you're using XOAUTH2 you will need [src/OAuth.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/OAuth.php) as well as the Composer dependencies for the services you wish to authenticate with. Really, it's much easier to use Composer!
## A Simple Example
@@ -87,22 +85,25 @@ While installing the entire package manually or with Composer is simple, conveni
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
// Load Composer's autoloader
require 'vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user@example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp1.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user@example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('from@example.com', 'Mailer');
@@ -112,11 +113,11 @@ try {
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
//Attachments
// Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
@@ -125,16 +126,18 @@ try {
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
```
You'll find plenty more to play with in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder.
If you are re-using the instance (e.g. when sending to a mailing list), you may need to clear the recipient list to avoid sending duplicate messages. See [the mailing list example](https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps) for further guidance.
That's it. You should now be ready to use PHPMailer!
## Localization
PHPMailer defaults to English, but in the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder you'll find numerous (48 at the time of writing!) translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this:
PHPMailer defaults to English, but in the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder you'll find many translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this:
```php
// To load the French version
+1 -1
View File
@@ -1 +1 @@
6.0.7
6.1.1
+1 -1
View File
@@ -51,5 +51,5 @@
"PHPMailer\\Test\\": "test/"
}
},
"license": "LGPL-2.1"
"license": "LGPL-2.1-only"
}
@@ -0,0 +1,25 @@
<?php
/**
* Afrikaans PHPMailer language file: refer to English translation for definitive list
* @package PHPMailer
*/
$PHPMAILER_LANG['authenticate'] = 'SMTP-fout: kon nie geverifieer word nie.';
$PHPMAILER_LANG['connect_host'] = 'SMTP-fout: kon nie aan SMTP-verbind nie.';
$PHPMAILER_LANG['data_not_accepted'] = 'SMTP-fout: data nie aanvaar nie.';
$PHPMAILER_LANG['empty_message'] = 'Boodskapliggaam leeg.';
$PHPMAILER_LANG['encoding'] = 'Onbekende kodering: ';
$PHPMAILER_LANG['execute'] = 'Kon nie uitvoer nie: ';
$PHPMAILER_LANG['file_access'] = 'Kon nie lêer oopmaak nie: ';
$PHPMAILER_LANG['file_open'] = 'Lêerfout: Kon nie lêer oopmaak nie: ';
$PHPMAILER_LANG['from_failed'] = 'Die volgende Van adres misluk: ';
$PHPMAILER_LANG['instantiate'] = 'Kon nie posfunksie instansieer nie.';
$PHPMAILER_LANG['invalid_address'] = 'Ongeldige adres: ';
$PHPMAILER_LANG['mailer_not_supported'] = ' mailer word nie ondersteun nie.';
$PHPMAILER_LANG['provide_address'] = 'U moet ten minste een ontvanger e-pos adres verskaf.';
$PHPMAILER_LANG['recipients_failed'] = 'SMTP-fout: Die volgende ontvangers het misluk: ';
$PHPMAILER_LANG['signing'] = 'Ondertekening Fout: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP-verbinding () misluk.';
$PHPMAILER_LANG['smtp_error'] = 'SMTP-bediener fout: ';
$PHPMAILER_LANG['variable_set'] = 'Kan nie veranderlike instel of herstel nie: ';
$PHPMAILER_LANG['extension_missing'] = 'Uitbreiding ontbreek: ';
+1 -1
View File
@@ -24,4 +24,4 @@ $PHPMAILER_LANG['signing'] = 'خطا در امضا: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'خطا در اتصال به SMTP.';
$PHPMAILER_LANG['smtp_error'] = 'خطا در SMTP Server: ';
$PHPMAILER_LANG['variable_set'] = 'امکان ارسال یا ارسال مجدد متغیر‌ها وجود ندارد: ';
//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: ';
$PHPMAILER_LANG['extension_missing'] = 'افزونه موجود نیست: ';
@@ -26,4 +26,4 @@ $PHPMAILER_LANG['signing'] = 'Erro de Assinatura: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falhou.';
$PHPMAILER_LANG['smtp_error'] = 'Erro de servidor SMTP: ';
$PHPMAILER_LANG['variable_set'] = 'Não foi possível definir ou redefinir a variável: ';
$PHPMAILER_LANG['extension_missing'] = 'Extensão ausente: ';
$PHPMAILER_LANG['extension_missing'] = 'Extensão não existe: ';
+8 -8
View File
@@ -7,21 +7,21 @@
*/
$PHPMAILER_LANG['authenticate'] = 'Ошибка SMTP: ошибка авторизации.';
$PHPMAILER_LANG['connect_host'] = 'Ошибка SMTP: не удается подключиться к серверу SMTP.';
$PHPMAILER_LANG['connect_host'] = 'Ошибка SMTP: не удается подключиться к SMTP-серверу.';
$PHPMAILER_LANG['data_not_accepted'] = 'Ошибка SMTP: данные не приняты.';
$PHPMAILER_LANG['encoding'] = 'Неизвестный вид кодировки: ';
$PHPMAILER_LANG['encoding'] = 'Неизвестная кодировка: ';
$PHPMAILER_LANG['execute'] = 'Невозможно выполнить команду: ';
$PHPMAILER_LANG['file_access'] = 'Нет доступа к файлу: ';
$PHPMAILER_LANG['file_open'] = 'Файловая ошибка: не удается открыть файл: ';
$PHPMAILER_LANG['file_open'] = 'Файловая ошибка: не удаётся открыть файл: ';
$PHPMAILER_LANG['from_failed'] = 'Неверный адрес отправителя: ';
$PHPMAILER_LANG['instantiate'] = 'Невозможно запустить функцию mail.';
$PHPMAILER_LANG['provide_address'] = 'Пожалуйста, введите хотя бы один адрес e-mail получателя.';
$PHPMAILER_LANG['instantiate'] = 'Невозможно запустить функцию mail().';
$PHPMAILER_LANG['provide_address'] = 'Пожалуйста, введите хотя бы один email-адрес получателя.';
$PHPMAILER_LANG['mailer_not_supported'] = ' — почтовый сервер не поддерживается.';
$PHPMAILER_LANG['recipients_failed'] = 'Ошибка SMTP: отправка по следующим адресам получателей не удалась: ';
$PHPMAILER_LANG['recipients_failed'] = 'Ошибка SMTP: не удалась отправка таким адресатам: ';
$PHPMAILER_LANG['empty_message'] = 'Пустое сообщение';
$PHPMAILER_LANG['invalid_address'] = 'Не отослано, неправильный формат email адреса: ';
$PHPMAILER_LANG['invalid_address'] = 'Не отправлено из-за неправильного формата email-адреса: ';
$PHPMAILER_LANG['signing'] = 'Ошибка подписи: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'Ошибка соединения с SMTP-сервером';
$PHPMAILER_LANG['smtp_error'] = 'Ошибка SMTP-сервера: ';
$PHPMAILER_LANG['variable_set'] = 'Невозможно установить или переустановить переменную: ';
$PHPMAILER_LANG['variable_set'] = 'Невозможно установить или сбросить переменную: ';
$PHPMAILER_LANG['extension_missing'] = 'Расширение отсутствует: ';
+11 -11
View File
@@ -7,21 +7,21 @@
*/
$PHPMAILER_LANG['authenticate'] = 'Помилка SMTP: помилка авторизації.';
$PHPMAILER_LANG['connect_host'] = 'Помилка SMTP: не вдається під\'єднатися до серверу SMTP.';
$PHPMAILER_LANG['data_not_accepted'] = 'Помилка SMTP: дані не прийняті.';
$PHPMAILER_LANG['encoding'] = 'Невідомий тип кодування: ';
$PHPMAILER_LANG['connect_host'] = 'Помилка SMTP: не вдається під\'єднатися до SMTP-серверу.';
$PHPMAILER_LANG['data_not_accepted'] = 'Помилка SMTP: дані не прийнято.';
$PHPMAILER_LANG['encoding'] = 'Невідоме кодування: ';
$PHPMAILER_LANG['execute'] = 'Неможливо виконати команду: ';
$PHPMAILER_LANG['file_access'] = 'Немає доступу до файлу: ';
$PHPMAILER_LANG['file_open'] = 'Помилка файлової системи: не вдається відкрити файл: ';
$PHPMAILER_LANG['from_failed'] = 'Невірна адреса відправника: ';
$PHPMAILER_LANG['instantiate'] = 'Неможливо запустити функцію mail.';
$PHPMAILER_LANG['provide_address'] = 'Будь-ласка, введіть хоча б одну адресу e-mail отримувача.';
$PHPMAILER_LANG['instantiate'] = 'Неможливо запустити функцію mail().';
$PHPMAILER_LANG['provide_address'] = 'Будь-ласка, введіть хоча б одну email-адресу отримувача.';
$PHPMAILER_LANG['mailer_not_supported'] = ' - поштовий сервер не підтримується.';
$PHPMAILER_LANG['recipients_failed'] = 'Помилка SMTP: відправлення наступним отримувачам не вдалося: ';
$PHPMAILER_LANG['empty_message'] = 'Пусте тіло повідомлення';
$PHPMAILER_LANG['invalid_address'] = 'Не відправлено, невірний формат адреси e-mail: ';
$PHPMAILER_LANG['recipients_failed'] = 'Помилка SMTP: не вдалося відправлення для таких отримувачів: ';
$PHPMAILER_LANG['empty_message'] = 'Пусте повідомлення';
$PHPMAILER_LANG['invalid_address'] = 'Не відправлено через невірний формат email-адреси: ';
$PHPMAILER_LANG['signing'] = 'Помилка підпису: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'Помилка з\'єднання із SMTP-сервером';
$PHPMAILER_LANG['smtp_connect_failed'] = 'Помилка з\'єднання з SMTP-сервером';
$PHPMAILER_LANG['smtp_error'] = 'Помилка SMTP-сервера: ';
$PHPMAILER_LANG['variable_set'] = 'Неможливо встановити або перевстановити змінну: ';
$PHPMAILER_LANG['extension_missing'] = 'Не знайдено розширення: ';
$PHPMAILER_LANG['variable_set'] = 'Неможливо встановити або скинути змінну: ';
$PHPMAILER_LANG['extension_missing'] = 'Розширення відсутнє: ';
+1 -1
View File
@@ -23,7 +23,7 @@ namespace PHPMailer\PHPMailer;
/**
* PHPMailer exception handler.
*
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
*/
class Exception extends \Exception
{
File diff suppressed because it is too large Load Diff
+8 -8
View File
@@ -3,13 +3,13 @@
* PHPMailer POP-Before-SMTP Authentication Class.
* PHP Version 5.5.
*
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
*
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2017 Marcus Bointon
* @copyright 2012 - 2019 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
@@ -29,14 +29,14 @@ namespace PHPMailer\PHPMailer;
* and then loop through your mail sending script. Providing this process doesn't
* take longer than the verification period lasts on your POP3 server, you should be fine.
* 3) This is really ancient technology; you should only need to use it to talk to very old systems.
* 4) This POP3 class is deliberately lightweight and incomplete, and implements just
* 4) This POP3 class is deliberately lightweight and incomplete, implementing just
* enough to do authentication.
* If you want a more complete class there are other POP3 classes for PHP available.
*
* @author Richard Davey (original author) <rich@corephp.co.uk>
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Richard Davey (original author) <rich@corephp.co.uk>
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
*/
class POP3
{
@@ -45,7 +45,7 @@ class POP3
*
* @var string
*/
const VERSION = '6.0.7';
const VERSION = '6.1.1';
/**
* Default POP3 port number.
+41 -10
View File
@@ -9,7 +9,7 @@
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2017 Marcus Bointon
* @copyright 2012 - 2019 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
@@ -24,8 +24,8 @@ namespace PHPMailer\PHPMailer;
* PHPMailer RFC821 SMTP email transport class.
* Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
*
* @author Chris Ryan
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
* @author Chris Ryan
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
*/
class SMTP
{
@@ -34,7 +34,7 @@ class SMTP
*
* @var string
*/
const VERSION = '6.0.7';
const VERSION = '6.1.1';
/**
* SMTP line break constant.
@@ -59,26 +59,36 @@ class SMTP
/**
* Debug level for no output.
*
* @var int
*/
const DEBUG_OFF = 0;
/**
* Debug level to show client -> server messages.
*
* @var int
*/
const DEBUG_CLIENT = 1;
/**
* Debug level to show client -> server and server -> client messages.
*
* @var int
*/
const DEBUG_SERVER = 2;
/**
* Debug level to show connection status, client -> server and server -> client messages.
*
* @var int
*/
const DEBUG_CONNECTION = 3;
/**
* Debug level to show all messages.
*
* @var int
*/
const DEBUG_LOWLEVEL = 4;
@@ -745,7 +755,7 @@ class SMTP
*
* @return bool
*
* @see hello()
* @see hello()
*/
protected function sendHello($hello, $host)
{
@@ -853,14 +863,35 @@ class SMTP
* Implements from RFC 821: RCPT <SP> TO:<forward-path> <CRLF>.
*
* @param string $address The address the message is being sent to
* @param string $dsn Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE
* or DELAY. If you specify NEVER all other notifications are ignored.
*
* @return bool
*/
public function recipient($address)
public function recipient($address, $dsn = '')
{
if (empty($dsn)) {
$rcpt = 'RCPT TO:<' . $address . '>';
} else {
$dsn = strtoupper($dsn);
$notify = [];
if (strpos($dsn, 'NEVER') !== false) {
$notify[] = 'NEVER';
} else {
foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) {
if (strpos($dsn, $value) !== false) {
$notify[] = $value;
}
}
}
$rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify);
}
return $this->sendCommand(
'RCPT TO',
'RCPT TO:<' . $address . '>',
$rcpt,
[250, 251]
);
}
@@ -904,7 +935,7 @@ class SMTP
$this->last_reply = $this->get_lines();
// Fetch SMTP code and possible error code explanation
$matches = [];
if (preg_match('/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/', $this->last_reply, $matches)) {
if (preg_match('/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]{1,2}) )?/', $this->last_reply, $matches)) {
$code = $matches[1];
$code_ex = (count($matches) > 2 ? $matches[2] : null);
// Cut off error code from each response line
@@ -1289,7 +1320,7 @@ class SMTP
* If no reply has been received yet, it will return null.
* If no pattern was matched, it will return false.
*
* @return bool|null|string
* @return bool|string|null
*/
protected function recordLastTransactionID()
{
@@ -1315,7 +1346,7 @@ class SMTP
* If no reply has been received yet, it will return null.
* If no pattern was matched, it will return false.
*
* @return bool|null|string
* @return bool|string|null
*
* @see recordLastTransactionID()
*/
@@ -47,7 +47,6 @@ class BucketStyleListener implements EventSubscriberInterface {
* @param Event $event Event emitted.
*/
public function onCommandAfterPrepare(Event $event) {
$command = $event['command'];
$bucket = $command['Bucket'];
$request = $command->getRequest();
@@ -81,7 +80,7 @@ class BucketStyleListener implements EventSubscriberInterface {
$bucket = $bucket.'-'.$this->appId;
}
$request->getParams()->set('bucket', $bucket)->set('key', $key);
$realHost = $bucket. '.' . $request->getHost();
if($this->ipport != null) {
$request->setHost($this->ipport);
+1 -1
View File
@@ -12,7 +12,7 @@ use Qcloud\Cos\Signature;
use Qcloud\Cos\TokenListener;
class Client extends GSClient {
const VERSION = '1.3.3';
const VERSION = '1.3.4';
private $region; // string: region.
private $credentials;
+4 -2
View File
@@ -11,9 +11,10 @@ class Signature {
public function __destruct() {
}
public function signRequest(RequestInterface $request) {
$host = $request->getHeader('Host');
$signTime = (string)(time() - 60) . ';' . (string)(time() + 3600);
$httpString = strtolower($request->getMethod()) . "\n" . urldecode($request->getPath()) .
"\n\nhost=" . $request->getHost() . "\n";
"\n\nhost=" . $host . "\n";
$sha1edHttpString = sha1($httpString);
$stringToSign = "sha1\n$signTime\n$sha1edHttpString\n";
$signKey = hash_hmac('sha1', $signTime, $this->secretKey);
@@ -27,9 +28,10 @@ class Signature {
RequestInterface $request,
$expires = "10 minutes"
) {
$host = $request->getHeader('Host');
$signTime = (string)(time() - 60) . ';' . (string)(strtotime($expires));
$httpString = strtolower($request->getMethod()) . "\n" . urldecode($request->getPath()) .
"\n\nhost=" . $request->getHost() . "\n";
"\n\nhost=" . $host . "\n";
$sha1edHttpString = sha1($httpString);
$stringToSign = "sha1\n$signTime\n$sha1edHttpString\n";
$signKey = hash_hmac('sha1', $signTime, $this->secretKey);
+2
View File
@@ -7,6 +7,8 @@ php:
- 5.6
- 7.0
dist: trusty
before_script:
- export QINIU_TEST_ENV="travis"
- travis_retry composer self-update
+2 -9
View File
@@ -170,23 +170,16 @@ final class CdnManager
public static function createTimestampAntiLeechUrl($rawUrl, $encryptKey, $durationInSeconds)
{
$parsedUrl = parse_url($rawUrl);
$deadline = time() + $durationInSeconds;
$expireHex = dechex($deadline);
$path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
$path = implode('/', array_map('rawurlencode', explode('/', $path)));
$strToSign = $encryptKey . $path . $expireHex;
$signStr = md5($strToSign);
$url = $parsedUrl['scheme'].'://'.$parsedUrl['host'].$path;
if (isset($parsedUrl['query'])) {
$signedUrl = $url . '&sign=' . $signStr . '&t=' . $expireHex;
$signedUrl = $rawUrl . '&sign=' . $signStr . '&t=' . $expireHex;
} else {
$signedUrl = $url . '?sign=' . $signStr . '&t=' . $expireHex;
$signedUrl = $rawUrl . '?sign=' . $signStr . '&t=' . $expireHex;
}
return $signedUrl;
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ namespace Qiniu;
final class Config
{
const SDK_VER = '7.2.9';
const SDK_VER = '7.2.10';
const BLOCK_SIZE = 4194304; //4*1024*1024 分块上传块大小,该参数为接口规格,不能修改
+2 -2
View File
@@ -33,7 +33,7 @@ class AppClient
if (!empty($maxUsers)) {
$params['maxUsers'] = $maxUsers;
}
if (!empty($noAutoKickUser)) {
if ($noAutoKickUser !== null) {
$params['noAutoKickUser'] = $noAutoKickUser;
}
$body = json_encode($params);
@@ -65,7 +65,7 @@ class AppClient
if (!empty($maxUsers)) {
$params['maxUsers'] = $maxUsers;
}
if (!empty($noAutoKickUser)) {
if ($noAutoKickUser !== null) {
$params['noAutoKickUser'] = $noAutoKickUser;
}
if (!empty($mergePublishRtmp)) {
+18 -18
View File
@@ -33,7 +33,7 @@ class Sms
"signature_id": <signature_id>
}
*/
public function createSignature(string $signature, string $source, string $pics = null)
public function createSignature($signature, $source, $pics = null)
{
$params['signature'] = $signature;
$params['source'] = $source;
@@ -62,7 +62,7 @@ class Sms
"signature": string
}
*/
public function updateSignature(string $id, string $signature, string $source, string $pics = null)
public function updateSignature($id, $signature, $source, $pics = null)
{
$params['signature'] = $signature;
$params['source'] = $source;
@@ -96,7 +96,7 @@ class Sms
"page_size": int,
}
*/
public function checkSignature(string $audit_status = null, int $page = 1, int $page_size = 20)
public function checkSignature($audit_status = null, $page = 1, $page_size = 20)
{
$url = sprintf(
@@ -116,7 +116,7 @@ class Sms
* id 签名id string 类型,必填,
* @retrun : 请求成功 HTTP 状态码为 200
*/
public function deleteSignature(string $id)
public function deleteSignature($id)
{
$url = $this->baseURL . 'signature/' . $id;
list(, $err) = $this->delete($url);
@@ -139,11 +139,11 @@ class Sms
}
*/
public function createTemplate(
string $name,
string $template,
string $type,
string $description,
string $signture_id
$name,
$template,
$type,
$description,
$signture_id
) {
$params['name'] = $name;
$params['template'] = $template;
@@ -181,7 +181,7 @@ class Sms
"page_size": int
}
*/
public function queryTemplate(string $audit_status = null, int $page = 1, int $page_size = 20)
public function queryTemplate($audit_status = null, $page = 1, $page_size = 20)
{
$url = sprintf(
@@ -205,11 +205,11 @@ class Sms
* @retrun : 请求成功 HTTP 状态码为 200
*/
public function updateTemplate(
string $id,
string $name,
string $template,
string $description,
string $signature_id
$id,
$name,
$template,
$description,
$signature_id
) {
$params['name'] = $name;
$params['template'] = $template;
@@ -226,7 +226,7 @@ class Sms
* id :模板id string 类型,必填,
* @retrun : 请求成功 HTTP 状态码为 200
*/
public function deleteTemplate(string $id)
public function deleteTemplate($id)
{
$url = $this->baseURL . 'template/' . $id;
list(, $err) = $this->delete($url);
@@ -243,7 +243,7 @@ class Sms
"job_id": string
}
*/
public function sendMessage(string $template_id, array $mobiles, array $parameters = null)
public function sendMessage($template_id, $mobiles, $parameters = null)
{
$params['template_id'] = $template_id;
$params['mobiles'] = $mobiles;
@@ -256,7 +256,7 @@ class Sms
return $ret;
}
public function imgToBase64(string $img_file)
public function imgToBase64($img_file)
{
$img_base64 = '';
if (file_exists($img_file)) {
+1 -1
View File
@@ -59,7 +59,7 @@ final class BucketManager
$line = 'false',
$shared = 'false'
) {
$path = '/v3/buckets?region=' . $region . '&line=' . $line . '&shared=' . $share;
$path = '/v3/buckets?region=' . $region . '&line=' . $line . '&shared=' . $shared;
$info = $this->ucPost($path);
return $info;
}
+1 -1
View File
@@ -46,7 +46,7 @@ final class UploadManager
$data,
$params = null,
$mime = 'application/octet-stream',
$fname = null
$fname = "default_filename"
) {
$params = self::trimParams($params);
+1 -1
View File
@@ -25,7 +25,7 @@ class CdnManagerTest extends \PHPUnit_Framework_TestCase
$this->cdnManager = new CdnManager($testAuth);
$this->encryptKey = $timestampAntiLeechEncryptKey;
$this->imgUrl = $customDomain . '/24.jpg';
$this->imgUrl = $customDomain . '/sdktest.png';
}
public function testCreateTimestampAntiLeechUrl()
+2 -2
View File
@@ -8,7 +8,7 @@ class DownloadTest extends \PHPUnit_Framework_TestCase
public function test()
{
global $testAuth;
$base_url = 'http://private-res.qiniudn.com/gogopher.jpg';
$base_url = 'http://sdk.peterpy.cn/gogopher.jpg';
$private_url = $testAuth->privateDownloadUrl($base_url);
$response = Client::get($private_url);
$this->assertEquals(200, $response->statusCode);
@@ -17,7 +17,7 @@ class DownloadTest extends \PHPUnit_Framework_TestCase
public function testFop()
{
global $testAuth;
$base_url = 'http://private-res.qiniudn.com/gogopher.jpg?exif';
$base_url = 'http://sdk.peterpy.cn/gogopher.jpg?exif';
$private_url = $testAuth->privateDownloadUrl($base_url);
$response = Client::get($private_url);
$this->assertEquals(200, $response->statusCode);
+1 -1
View File
@@ -8,7 +8,7 @@ class FopTest extends \PHPUnit_Framework_TestCase
{
public function testExifPub()
{
$fop = new Operation('testres.qiniudn.com');
$fop = new Operation('sdk.peterpy.cn');
list($exif, $error) = $fop->execute('gogopher.jpg', 'exif');
$this->assertNull($error);
$this->assertNotNull($exif);
+1 -1
View File
@@ -21,7 +21,7 @@ $dummyAuth = new Auth($dummyAccessKey, $dummySecretKey);
//cdn
$timestampAntiLeechEncryptKey = getenv('QINIU_TIMESTAMP_ENCRPTKEY');
$customDomain = "http://phpsdk.peterpy.cn";
$customDomain = "http://sdk.peterpy.cn";
$tid = getenv('TRAVIS_JOB_NUMBER');
if (!empty($tid)) {
+6
View File
@@ -0,0 +1,6 @@
* text=auto
/examples export-ignore
/tests export-ignore
/doc.md export-ignore
/phpunit.xml export-ignore
+9
View File
@@ -95,6 +95,15 @@ $file = fopen('/local/path/file', 'r');
$client->write('/save/path', $file);
```
#### 使用并行式断点续传上传文件
```
$serviceConfig->setUploadType('BLOCK_PARALLEL');
$client = new Upyun($serviceConfig);
$file = fopen('/local/path/file', 'r');
$client->write('/save/path', $file);
```
#### 上传图片并转换格式为 `png`,详见[上传作图](http://docs.upyun.com/cloud/image/#_2)
```

Some files were not shown because too many files have changed in this diff Show More