PSR规范调整

This commit is contained in:
thinkphp
2015-10-04 13:05:15 +08:00
parent 1cfb3704c6
commit 27e724bb3c
135 changed files with 9426 additions and 11556 deletions

View File

@@ -11,12 +11,14 @@
namespace think;
class Auto {
class Auto
{
protected $auto = [];
protected $auto = [];
public function rule($rule){
$this->auto = $rule;
public function rule($rule)
{
$this->auto = $rule;
return $this;
}
@@ -26,32 +28,38 @@ class Auto {
* @param array $data 创建数据
* @return mixed
*/
public function operate($data) {
public function operate($data)
{
// 自动填充
if($this->auto) {
foreach ($this->auto as $auto){
if ($this->auto) {
foreach ($this->auto as $auto) {
// 填充因子定义格式
// array('field','填充内容','附加规则',[额外参数])
switch(trim($auto[2])) {
switch (trim($auto[2])) {
case 'callback': // 使用回调方法
$args = isset($auto[3])?(array)$auto[3]:[];
if(isset($data[$auto[0]])) {
array_unshift($args,$data[$auto[0]]);
$args = isset($auto[3]) ? (array) $auto[3] : [];
if (isset($data[$auto[0]])) {
array_unshift($args, $data[$auto[0]]);
}
$data[$auto[0]] = call_user_func_array($auto[1], $args);
$data[$auto[0]] = call_user_func_array($auto[1], $args);
break;
case 'field': // 用其它字段的值进行填充
case 'field': // 用其它字段的值进行填充
$data[$auto[0]] = $data[$auto[1]];
break;
case 'ignore': // 为空忽略
if(''===$data[$auto[0]])
if ('' === $data[$auto[0]]) {
unset($data[$auto[0]]);
}
break;
case 'string':
default: // 默认作为字符串填充
$data[$auto[0]] = $auto[1];
}
if(false === $data[$auto[0]] ) unset($data[$auto[0]]);
if (false === $data[$auto[0]]) {
unset($data[$auto[0]]);
}
}
}
return $data;

View File

@@ -11,7 +11,8 @@
namespace think;
class Crypt {
class Crypt
{
/**
* 加密字符串
* @access public
@@ -19,20 +20,24 @@ class Crypt {
* @param string $key 加密key
* @return string
*/
static public function encrypt($data,$key,$expire=0){
public static function encrypt($data, $key, $expire = 0)
{
$key = md5($key);
$data = base64_encode($data);
$x = 0;
$len = strlen($data);
$l = strlen($key);
$char = '';
for ($i = 0; $i< $len; $i++) {
if ($x == $l) $x = 0;
$char .=substr($key, $x, 1);
for ($i = 0; $i < $len; $i++) {
if ($x == $l) {
$x = 0;
}
$char .= substr($key, $x, 1);
$x++;
}
$str = sprintf('%010d', $expire ? $expire + time() : 0);
for ($i=0; $i< $len; $i++) {
for ($i = 0; $i < $len; $i++) {
$str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
}
return str_replace('=', '', base64_encode($str));
@@ -45,27 +50,31 @@ class Crypt {
* @param string $key 加密key
* @return string
*/
static public function decrypt($data,$key){
public static function decrypt($data, $key)
{
$key = md5($key);
$x = 0;
$data = base64_decode($data);
$expire = substr($data,0,10);
$data = substr($data,10);
if($expire > 0 && $expire<time()) {
$expire = substr($data, 0, 10);
$data = substr($data, 10);
if ($expire > 0 && $expire < time()) {
return '';
}
$len = strlen($data);
$l = strlen($key);
$l = strlen($key);
$char = $str = '';
for ($i=0; $i< $len; $i++) {
if ($x == $l) $x = 0;
for ($i = 0; $i < $len; $i++) {
if ($x == $l) {
$x = 0;
}
$char .= substr($key, $x, 1);
$x++;
}
for ($i = 0; $i < $len; $i++) {
if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
}else{
} else {
$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
}
}

View File

@@ -12,22 +12,22 @@
namespace think;
/* 缩略图相关常量定义 */
define('THINKIMAGE_THUMB_SCALING', 1); //常量,标识缩略图等比例缩放类型
define('THINKIMAGE_THUMB_FILLED', 2); //常量,标识缩略图缩放后填充类型
define('THINKIMAGE_THUMB_CENTER', 3); //常量,标识缩略图居中裁剪类型
define('THINKIMAGE_THUMB_SCALING', 1); //常量,标识缩略图等比例缩放类型
define('THINKIMAGE_THUMB_FILLED', 2); //常量,标识缩略图缩放后填充类型
define('THINKIMAGE_THUMB_CENTER', 3); //常量,标识缩略图居中裁剪类型
define('THINKIMAGE_THUMB_NORTHWEST', 4); //常量,标识缩略图左上角裁剪类型
define('THINKIMAGE_THUMB_SOUTHEAST', 5); //常量,标识缩略图右下角裁剪类型
define('THINKIMAGE_THUMB_FIXED', 6); //常量,标识缩略图固定尺寸缩放类型
define('THINKIMAGE_THUMB_FIXED', 6); //常量,标识缩略图固定尺寸缩放类型
/* 水印相关常量定义 */
define('THINKIMAGE_WATER_NORTHWEST', 1); //常量,标识左上角水印
define('THINKIMAGE_WATER_NORTH', 2); //常量,标识上居中水印
define('THINKIMAGE_WATER_NORTH', 2); //常量,标识上居中水印
define('THINKIMAGE_WATER_NORTHEAST', 3); //常量,标识右上角水印
define('THINKIMAGE_WATER_WEST', 4); //常量,标识左居中水印
define('THINKIMAGE_WATER_CENTER', 5); //常量,标识居中水印
define('THINKIMAGE_WATER_EAST', 6); //常量,标识右居中水印
define('THINKIMAGE_WATER_WEST', 4); //常量,标识左居中水印
define('THINKIMAGE_WATER_CENTER', 5); //常量,标识居中水印
define('THINKIMAGE_WATER_EAST', 6); //常量,标识右居中水印
define('THINKIMAGE_WATER_SOUTHWEST', 7); //常量,标识左下角水印
define('THINKIMAGE_WATER_SOUTH', 8); //常量,标识下居中水印
define('THINKIMAGE_WATER_SOUTH', 8); //常量,标识下居中水印
define('THINKIMAGE_WATER_SOUTHEAST', 9); //常量,标识右下角水印
/**
@@ -35,7 +35,8 @@ define('THINKIMAGE_WATER_SOUTHEAST', 9); //常量,标识右下角水印
* 目前支持GD库和imagick
* @author 麦当苗儿 <zuojiazi.cn@gmail.com>
*/
class Image {
class Image
{
/**
* 图片资源
* @var resource
@@ -46,15 +47,17 @@ class Image {
* 初始化方法,用于实例化一个图片处理对象
* @param string $type 要使用的类库默认使用GD库
*/
static public function init($type = 'Gd', $imgname = null){
public static function init($type = 'Gd', $imgname = null)
{
/* 引入处理库,实例化图片处理对象 */
$class = '\\think\\image\\driver\\'.strtolower($type);
$class = '\\think\\image\\driver\\' . strtolower($type);
self::$im = new $class($imgname);
return self::$im;
}
// 调用驱动类的方法
static public function __callStatic($method, $params){
public static function __callStatic($method, $params)
{
self::$im || self::init();
return call_user_func_array([self::$im, $method], $params);
}

View File

@@ -11,7 +11,8 @@
namespace think\image\driver;
class Gd{
class Gd
{
/**
* 图像资源对象
* @var resource
@@ -28,7 +29,8 @@ class Gd{
* 构造方法,可用于打开一张图像
* @param string $imgname 图像路径
*/
public function __construct($imgname = null) {
public function __construct($imgname = null)
{
$imgname && $this->open($imgname);
}
@@ -36,15 +38,18 @@ class Gd{
* 打开一张图像
* @param string $imgname 图像路径
*/
public function open($imgname){
public function open($imgname)
{
//检测图像文件
if(!is_file($imgname)) throw new \Exception('不存在的图像文件');
if (!is_file($imgname)) {
throw new \Exception('不存在的图像文件');
}
//获取图像信息
$info = getimagesize($imgname);
//检测图像合法性
if(false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))){
if (false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))) {
throw new \Exception('非法图像文件');
}
@@ -60,12 +65,12 @@ class Gd{
empty($this->im) || imagedestroy($this->im);
//打开图像
if('gif' == $this->info['type']){
$class = '\\Think\\Image\\Driver\\Gif';
if ('gif' == $this->info['type']) {
$class = '\\Think\\Image\\Driver\\Gif';
$this->gif = new $class($imgname);
$this->im = imagecreatefromstring($this->gif->image());
$this->im = imagecreatefromstring($this->gif->image());
} else {
$fun = "imagecreatefrom{$this->info['type']}";
$fun = "imagecreatefrom{$this->info['type']}";
$this->im = $fun($imgname);
}
return $this;
@@ -77,24 +82,27 @@ class Gd{
* @param string $type 图像类型
* @param boolean $interlace 是否对JPEG类型图像设置隔行扫描
*/
public function save($imgname, $type = null, $interlace = true){
if(empty($this->im)) throw new \Exception('没有可以被保存的图像资源');
public function save($imgname, $type = null, $interlace = true)
{
if (empty($this->im)) {
throw new \Exception('没有可以被保存的图像资源');
}
//自动获取图像类型
if(is_null($type)){
if (is_null($type)) {
$type = $this->info['type'];
} else {
$type = strtolower($type);
}
//JPEG图像设置隔行扫描
if('jpeg' == $type || 'jpg' == $type){
if ('jpeg' == $type || 'jpg' == $type) {
$type = 'jpeg';
imageinterlace($this->im, $interlace);
}
//保存图像
if('gif' == $type && !empty($this->gif)){
if ('gif' == $type && !empty($this->gif)) {
$this->gif->save($imgname);
} else {
$fun = "image{$type}";
@@ -107,8 +115,12 @@ class Gd{
* 返回图像宽度
* @return integer 图像宽度
*/
public function width(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function width()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return $this->info['width'];
}
@@ -116,8 +128,12 @@ class Gd{
* 返回图像高度
* @return integer 图像高度
*/
public function height(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function height()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return $this->info['height'];
}
@@ -125,8 +141,12 @@ class Gd{
* 返回图像类型
* @return string 图像类型
*/
public function type(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function type()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return $this->info['type'];
}
@@ -134,8 +154,12 @@ class Gd{
* 返回图像MIME类型
* @return string 图像MIME类型
*/
public function mime(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function mime()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return $this->info['mime'];
}
@@ -143,8 +167,12 @@ class Gd{
* 返回图像尺寸数组 0 - 图像宽度1 - 图像高度
* @return array 图像尺寸
*/
public function size(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function size()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return [$this->info['width'], $this->info['height']];
}
@@ -157,11 +185,14 @@ class Gd{
* @param integer $width 图像保存宽度
* @param integer $height 图像保存高度
*/
public function crop($w, $h, $x = 0, $y = 0, $width = null, $height = null){
if(empty($this->im)) throw new \Exception('没有可以被裁剪的图像资源');
public function crop($w, $h, $x = 0, $y = 0, $width = null, $height = null)
{
if (empty($this->im)) {
throw new \Exception('没有可以被裁剪的图像资源');
}
//设置保存尺寸
empty($width) && $width = $w;
empty($width) && $width = $w;
empty($height) && $height = $h;
do {
@@ -177,7 +208,7 @@ class Gd{
//设置新图像
$this->im = $img;
} while(!empty($this->gif) && $this->gifNext());
} while (!empty($this->gif) && $this->gifNext());
$this->info['width'] = $width;
$this->info['height'] = $height;
@@ -190,8 +221,11 @@ class Gd{
* @param integer $height 缩略图最大高度
* @param integer $type 缩略图裁剪类型
*/
public function thumb($width, $height, $type = THINKIMAGE_THUMB_SCALE){
if(empty($this->im)) throw new \Exception('没有可以被缩略的图像资源');
public function thumb($width, $height, $type = THINKIMAGE_THUMB_SCALE)
{
if (empty($this->im)) {
throw new \Exception('没有可以被缩略的图像资源');
}
//原图宽度和高度
$w = $this->info['width'];
@@ -202,13 +236,15 @@ class Gd{
/* 等比例缩放 */
case THINKIMAGE_THUMB_SCALING:
//原图尺寸小于缩略图尺寸则不进行缩略
if($w < $width && $h < $height) return;
if ($w < $width && $h < $height) {
return;
}
//计算缩放比例
$scale = min($width/$w, $height/$h);
$scale = min($width / $w, $height / $h);
//设置缩略图的坐标及宽度和高度
$x = $y = 0;
$x = $y = 0;
$width = $w * $scale;
$height = $h * $scale;
break;
@@ -216,34 +252,34 @@ class Gd{
/* 居中裁剪 */
case THINKIMAGE_THUMB_CENTER:
//计算缩放比例
$scale = max($width/$w, $height/$h);
$scale = max($width / $w, $height / $h);
//设置缩略图的坐标及宽度和高度
$w = $width/$scale;
$h = $height/$scale;
$x = ($this->info['width'] - $w)/2;
$y = ($this->info['height'] - $h)/2;
$w = $width / $scale;
$h = $height / $scale;
$x = ($this->info['width'] - $w) / 2;
$y = ($this->info['height'] - $h) / 2;
break;
/* 左上角裁剪 */
case THINKIMAGE_THUMB_NORTHWEST:
//计算缩放比例
$scale = max($width/$w, $height/$h);
$scale = max($width / $w, $height / $h);
//设置缩略图的坐标及宽度和高度
$x = $y = 0;
$w = $width/$scale;
$h = $height/$scale;
$w = $width / $scale;
$h = $height / $scale;
break;
/* 右下角裁剪 */
case THINKIMAGE_THUMB_SOUTHEAST:
//计算缩放比例
$scale = max($width/$w, $height/$h);
$scale = max($width / $w, $height / $h);
//设置缩略图的坐标及宽度和高度
$w = $width/$scale;
$h = $height/$scale;
$w = $width / $scale;
$h = $height / $scale;
$x = $this->info['width'] - $w;
$y = $this->info['height'] - $h;
break;
@@ -251,19 +287,19 @@ class Gd{
/* 填充 */
case THINKIMAGE_THUMB_FILLED:
//计算缩放比例
if($w < $width && $h < $height){
if ($w < $width && $h < $height) {
$scale = 1;
} else {
$scale = min($width/$w, $height/$h);
$scale = min($width / $w, $height / $h);
}
//设置缩略图的坐标及宽度和高度
$neww = $w * $scale;
$newh = $h * $scale;
$posx = ($width - $w * $scale)/2;
$posy = ($height - $h * $scale)/2;
$posx = ($width - $w * $scale) / 2;
$posy = ($height - $h * $scale) / 2;
do{
do {
//创建新图像
$img = imagecreatetruecolor($width, $height);
// 调整默认颜色
@@ -274,8 +310,8 @@ class Gd{
imagecopyresampled($img, $this->im, $posx, $posy, $x, $y, $neww, $newh, $w, $h);
imagedestroy($this->im); //销毁原图
$this->im = $img;
} while(!empty($this->gif) && $this->gifNext());
} while (!empty($this->gif) && $this->gifNext());
$this->info['width'] = $width;
$this->info['height'] = $height;
return $this;
@@ -300,14 +336,20 @@ class Gd{
* @param integer $locate 水印位置
* @param integer $alpha 水印透明度
*/
public function water($source, $locate = THINKIMAGE_WATER_SOUTHEAST){
public function water($source, $locate = THINKIMAGE_WATER_SOUTHEAST)
{
//资源检测
if(empty($this->im)) throw new \Exception('没有可以被添加水印的图像资源');
if(!is_file($source)) throw new \Exception('水印图像不存在');
if (empty($this->im)) {
throw new \Exception('没有可以被添加水印图像资源');
}
if (!is_file($source)) {
throw new \Exception('水印图像不存在');
}
//获取水印图像信息
$info = getimagesize($source);
if(false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))){
if (false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))) {
throw new \Exception('非法水印文件');
}
@@ -345,44 +387,44 @@ class Gd{
/* 居中水印 */
case THINKIMAGE_WATER_CENTER:
$x = ($this->info['width'] - $info[0])/2;
$y = ($this->info['height'] - $info[1])/2;
$x = ($this->info['width'] - $info[0]) / 2;
$y = ($this->info['height'] - $info[1]) / 2;
break;
/* 下居中水印 */
case THINKIMAGE_WATER_SOUTH:
$x = ($this->info['width'] - $info[0])/2;
$x = ($this->info['width'] - $info[0]) / 2;
$y = $this->info['height'] - $info[1];
break;
/* 右居中水印 */
case THINKIMAGE_WATER_EAST:
$x = $this->info['width'] - $info[0];
$y = ($this->info['height'] - $info[1])/2;
$y = ($this->info['height'] - $info[1]) / 2;
break;
/* 上居中水印 */
case THINKIMAGE_WATER_NORTH:
$x = ($this->info['width'] - $info[0])/2;
$x = ($this->info['width'] - $info[0]) / 2;
$y = 0;
break;
/* 左居中水印 */
case THINKIMAGE_WATER_WEST:
$x = 0;
$y = ($this->info['height'] - $info[1])/2;
$y = ($this->info['height'] - $info[1]) / 2;
break;
default:
/* 自定义水印坐标 */
if(is_array($locate)){
if (is_array($locate)) {
list($x, $y) = $locate;
} else {
throw new \Exception('不支持的水印位置类型');
}
}
do{
do {
//添加水印
$src = imagecreatetruecolor($info[0], $info[1]);
// 调整默认颜色
@@ -395,7 +437,7 @@ class Gd{
//销毁零时图片资源
imagedestroy($src);
} while(!empty($this->gif) && $this->gifNext());
} while (!empty($this->gif) && $this->gifNext());
//销毁水印资源
imagedestroy($water);
@@ -412,18 +454,23 @@ class Gd{
* @param integer $offset 文字相对当前位置的偏移量
* @param integer $angle 文字倾斜角度
*/
public function text($text, $font, $size, $color = '#00000000',
$locate = THINKIMAGE_WATER_SOUTHEAST, $offset = 0, $angle = 0){
public function text($text, $font, $size, $color = '#00000000',
$locate = THINKIMAGE_WATER_SOUTHEAST, $offset = 0, $angle = 0) {
//资源检测
if(empty($this->im)) throw new \Exception('没有可以被写入文字的图像资源');
if(!is_file($font)) throw new \Exception("不存在的字体文件:{$font}");
if (empty($this->im)) {
throw new \Exception('没有可以被写入文字的图像资源');
}
if (!is_file($font)) {
throw new \Exception("不存在的字体文件:{$font}");
}
//获取文字信息
$info = imagettfbbox($size, $angle, $font, $text);
$minx = min($info[0], $info[2], $info[4], $info[6]);
$maxx = max($info[0], $info[2], $info[4], $info[6]);
$miny = min($info[1], $info[3], $info[5], $info[7]);
$maxy = max($info[1], $info[3], $info[5], $info[7]);
$minx = min($info[0], $info[2], $info[4], $info[6]);
$maxx = max($info[0], $info[2], $info[4], $info[6]);
$miny = min($info[1], $info[3], $info[5], $info[7]);
$maxy = max($info[1], $info[3], $info[5], $info[7]);
/* 计算文字初始坐标和尺寸 */
$x = $minx;
@@ -435,7 +482,7 @@ class Gd{
switch ($locate) {
/* 右下角文字 */
case THINKIMAGE_WATER_SOUTHEAST:
$x += $this->info['width'] - $w;
$x += $this->info['width'] - $w;
$y += $this->info['height'] - $h;
break;
@@ -456,35 +503,35 @@ class Gd{
/* 居中文字 */
case THINKIMAGE_WATER_CENTER:
$x += ($this->info['width'] - $w)/2;
$y += ($this->info['height'] - $h)/2;
$x += ($this->info['width'] - $w) / 2;
$y += ($this->info['height'] - $h) / 2;
break;
/* 下居中文字 */
case THINKIMAGE_WATER_SOUTH:
$x += ($this->info['width'] - $w)/2;
$x += ($this->info['width'] - $w) / 2;
$y += $this->info['height'] - $h;
break;
/* 右居中文字 */
case THINKIMAGE_WATER_EAST:
$x += $this->info['width'] - $w;
$y += ($this->info['height'] - $h)/2;
$y += ($this->info['height'] - $h) / 2;
break;
/* 上居中文字 */
case THINKIMAGE_WATER_NORTH:
$x += ($this->info['width'] - $w)/2;
$x += ($this->info['width'] - $w) / 2;
break;
/* 左居中文字 */
case THINKIMAGE_WATER_WEST:
$y += ($this->info['height'] - $h)/2;
$y += ($this->info['height'] - $h) / 2;
break;
default:
/* 自定义文字坐标 */
if(is_array($locate)){
if (is_array($locate)) {
list($posx, $posy) = $locate;
$x += $posx;
$y += $posy;
@@ -494,35 +541,36 @@ class Gd{
}
/* 设置偏移量 */
if(is_array($offset)){
$offset = array_map('intval', $offset);
if (is_array($offset)) {
$offset = array_map('intval', $offset);
list($ox, $oy) = $offset;
} else{
} else {
$offset = intval($offset);
$ox = $oy = $offset;
$ox = $oy = $offset;
}
/* 设置颜色 */
if(is_string($color) && 0 === strpos($color, '#')){
if (is_string($color) && 0 === strpos($color, '#')) {
$color = str_split(substr($color, 1), 2);
$color = array_map('hexdec', $color);
if(empty($color[3]) || $color[3] > 127){
if (empty($color[3]) || $color[3] > 127) {
$color[3] = 0;
}
} elseif (!is_array($color)) {
throw new \Exception('错误的颜色值');
}
do{
do {
/* 写入文字 */
$col = imagecolorallocatealpha($this->im, $color[0], $color[1], $color[2], $color[3]);
imagettftext($this->im, $size, $angle, $x + $ox, $y + $oy, $col, $font, $text);
} while(!empty($this->gif) && $this->gifNext());
} while (!empty($this->gif) && $this->gifNext());
return $this;
}
/* 切换到GIF的下一帧并保存当前帧内部使用 */
private function gifNext(){
private function gifNext()
{
ob_start();
ob_implicit_flush(0);
imagegif($this->im);
@@ -531,7 +579,7 @@ class Gd{
$this->gif->image($img);
$next = $this->gif->nextImage();
if($next){
if ($next) {
$this->im = imagecreatefromstring($next);
return $next;
} else {
@@ -543,7 +591,8 @@ class Gd{
/**
* 析构方法,用于销毁图像资源
*/
public function __destruct() {
public function __destruct()
{
empty($this->im) || imagedestroy($this->im);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,10 @@
namespace think\image\driver;
class Imagick{
use think\Lang as Lang;
use think\image\driver\Imagick as Imagick;
class Imagick
{
/**
* 图像资源对象
* @var resource
@@ -28,9 +31,10 @@ class Imagick{
* 构造方法,可用于打开一张图像
* @param string $imgname 图像路径
*/
public function __construct($imgname = null) {
if ( !extension_loaded('Imagick') ) {
throw new \Exception(Lang::get('_NOT_SUPPERT_').':Imagick');
public function __construct($imgname = null)
{
if (!extension_loaded('Imagick')) {
throw new \Exception(Lang::get('_NOT_SUPPERT_') . ':Imagick');
}
$imgname && $this->open($imgname);
}
@@ -39,9 +43,12 @@ class Imagick{
* 打开一张图像
* @param string $imgname 图像路径
*/
public function open($imgname){
public function open($imgname)
{
//检测图像文件
if(!is_file($imgname)) throw new \Exception('不存在的图像文件');
if (!is_file($imgname)) {
throw new \Exception('不存在的图像文件');
}
//销毁已存在的图像
empty($this->im) || $this->im->destroy();
@@ -64,11 +71,14 @@ class Imagick{
* @param string $type 图像类型
* @param boolean $interlace 是否对JPEG类型图像设置隔行扫描
*/
public function save($imgname, $type = null, $interlace = true){
if(empty($this->im)) throw new \Exception('没有可以被保存的图像资源');
public function save($imgname, $type = null, $interlace = true)
{
if (empty($this->im)) {
throw new \Exception('没有可以被保存的图像资源');
}
//设置图片类型
if(is_null($type)){
if (is_null($type)) {
$type = $this->info['type'];
} else {
$type = strtolower($type);
@@ -76,7 +86,7 @@ class Imagick{
}
//JPEG图像设置隔行扫描
if('jpeg' == $type || 'jpg' == $type){
if ('jpeg' == $type || 'jpg' == $type) {
$this->im->setImageInterlaceScheme(1);
}
@@ -96,8 +106,12 @@ class Imagick{
* 返回图像宽度
* @return integer 图像宽度
*/
public function width(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function width()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return $this->info['width'];
}
@@ -105,8 +119,12 @@ class Imagick{
* 返回图像高度
* @return integer 图像高度
*/
public function height(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function height()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return $this->info['height'];
}
@@ -114,8 +132,12 @@ class Imagick{
* 返回图像类型
* @return string 图像类型
*/
public function type(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function type()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return $this->info['type'];
}
@@ -123,8 +145,12 @@ class Imagick{
* 返回图像MIME类型
* @return string 图像MIME类型
*/
public function mime(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function mime()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return $this->info['mime'];
}
@@ -132,8 +158,12 @@ class Imagick{
* 返回图像尺寸数组 0 - 图像宽度1 - 图像高度
* @return array 图像尺寸
*/
public function size(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
public function size()
{
if (empty($this->im)) {
throw new \Exception('没有指定图像资源');
}
return [$this->info['width'], $this->info['height']];
}
@@ -146,15 +176,18 @@ class Imagick{
* @param integer $width 图像保存宽度
* @param integer $height 图像保存高度
*/
public function crop($w, $h, $x = 0, $y = 0, $width = null, $height = null){
if(empty($this->im)) throw new \Exception('没有可以被裁剪的图像资源');
public function crop($w, $h, $x = 0, $y = 0, $width = null, $height = null)
{
if (empty($this->im)) {
throw new \Exception('没有可以被裁剪的图像资源');
}
//设置保存尺寸
empty($width) && $width = $w;
empty($width) && $width = $w;
empty($height) && $height = $h;
//裁剪图片
if('gif' == $this->info['type']){
if ('gif' == $this->info['type']) {
$img = $this->im->coalesceImages();
$this->im->destroy(); //销毁原图
@@ -162,7 +195,7 @@ class Imagick{
do {
$this->_crop($w, $h, $x, $y, $width, $height, $img);
} while ($img->nextImage());
//压缩图片
$this->im = $img->deconstructImages();
$img->destroy(); //销毁零时图片
@@ -172,18 +205,19 @@ class Imagick{
}
/* 裁剪图片,内部调用 */
private function _crop($w, $h, $x, $y, $width, $height, $img = null){
private function _crop($w, $h, $x, $y, $width, $height, $img = null)
{
is_null($img) && $img = $this->im;
//裁剪
$info = $this->info;
if($x != 0 || $y != 0 || $w != $info['width'] || $h != $info['height']){
if (0 != $x || 0 != $y || $w != $info['width'] || $h != $info['height']) {
$img->cropImage($w, $h, $x, $y);
$img->setImagePage($w, $h, 0, 0); //调整画布和图片一致
}
//调整大小
if($w != $width || $h != $height){
if ($w != $width || $h != $height) {
$img->scaleImage($width, $height);
}
@@ -198,8 +232,11 @@ class Imagick{
* @param integer $height 缩略图最大高度
* @param integer $type 缩略图裁剪类型
*/
public function thumb($width, $height, $type = THINKIMAGE_THUMB_SCALE){
if(empty($this->im)) throw new \Exception('没有可以被缩略的图像资源');
public function thumb($width, $height, $type = THINKIMAGE_THUMB_SCALE)
{
if (empty($this->im)) {
throw new \Exception('没有可以被缩略的图像资源');
}
//原图宽度和高度
$w = $this->info['width'];
@@ -210,13 +247,15 @@ class Imagick{
/* 等比例缩放 */
case THINKIMAGE_THUMB_SCALING:
//原图尺寸小于缩略图尺寸则不进行缩略
if($w < $width && $h < $height) return;
if ($w < $width && $h < $height) {
return;
}
//计算缩放比例
$scale = min($width/$w, $height/$h);
$scale = min($width / $w, $height / $h);
//设置缩略图的坐标及宽度和高度
$x = $y = 0;
$x = $y = 0;
$width = $w * $scale;
$height = $h * $scale;
break;
@@ -224,34 +263,34 @@ class Imagick{
/* 居中裁剪 */
case THINKIMAGE_THUMB_CENTER:
//计算缩放比例
$scale = max($width/$w, $height/$h);
$scale = max($width / $w, $height / $h);
//设置缩略图的坐标及宽度和高度
$w = $width/$scale;
$h = $height/$scale;
$x = ($this->info['width'] - $w)/2;
$y = ($this->info['height'] - $h)/2;
$w = $width / $scale;
$h = $height / $scale;
$x = ($this->info['width'] - $w) / 2;
$y = ($this->info['height'] - $h) / 2;
break;
/* 左上角裁剪 */
case THINKIMAGE_THUMB_NORTHWEST:
//计算缩放比例
$scale = max($width/$w, $height/$h);
$scale = max($width / $w, $height / $h);
//设置缩略图的坐标及宽度和高度
$x = $y = 0;
$w = $width/$scale;
$h = $height/$scale;
$w = $width / $scale;
$h = $height / $scale;
break;
/* 右下角裁剪 */
case THINKIMAGE_THUMB_SOUTHEAST:
//计算缩放比例
$scale = max($width/$w, $height/$h);
$scale = max($width / $w, $height / $h);
//设置缩略图的坐标及宽度和高度
$w = $width/$scale;
$h = $height/$scale;
$w = $width / $scale;
$h = $height / $scale;
$x = $this->info['width'] - $w;
$y = $this->info['height'] - $h;
break;
@@ -259,24 +298,23 @@ class Imagick{
/* 填充 */
case THINKIMAGE_THUMB_FILLED:
//计算缩放比例
if($w < $width && $h < $height){
if ($w < $width && $h < $height) {
$scale = 1;
} else {
$scale = min($width/$w, $height/$h);
$scale = min($width / $w, $height / $h);
}
//设置缩略图的坐标及宽度和高度
$neww = $w * $scale;
$newh = $h * $scale;
$posx = ($width - $w * $scale)/2;
$posy = ($height - $h * $scale)/2;
$posx = ($width - $w * $scale) / 2;
$posy = ($height - $h * $scale) / 2;
//创建一张新图像
$newimg = new Imagick();
$newimg->newImage($width, $height, 'white', $this->info['type']);
if('gif' == $this->info['type']){
if ('gif' == $this->info['type']) {
$imgs = $this->im->coalesceImages();
$img = new Imagick();
$this->im->destroy(); //销毁原图
@@ -285,7 +323,7 @@ class Imagick{
do {
//填充图像
$image = $this->_fill($newimg, $posx, $posy, $neww, $newh, $imgs);
$img->addImage($image);
$img->setImageDelay($imgs->getImageDelay());
$img->setImagePage($width, $height, 0, 0);
@@ -327,11 +365,12 @@ class Imagick{
}
/* 填充指定图像,内部使用 */
private function _fill($newimg, $posx, $posy, $neww, $newh, $img = null){
private function _fill($newimg, $posx, $posy, $neww, $newh, $img = null)
{
is_null($img) && $img = $this->im;
/* 将指定图片绘入空白图片 */
$draw = new ImagickDraw();
$draw = new ImagickDraw();
$draw->composite($img->getImageCompose(), $posx, $posy, $neww, $newh, $img);
$image = $newimg->clone();
$image->drawImage($draw);
@@ -346,10 +385,16 @@ class Imagick{
* @param integer $locate 水印位置
* @param integer $alpha 水印透明度
*/
public function water($source, $locate = THINKIMAGE_WATER_SOUTHEAST){
public function water($source, $locate = THINKIMAGE_WATER_SOUTHEAST)
{
//资源检测
if(empty($this->im)) throw new \Exception('没有可以被添加水印的图像资源');
if(!is_file($source)) throw new \Exception('水印图像不存在');
if (empty($this->im)) {
throw new \Exception('没有可以被添加水印图像资源');
}
if (!is_file($source)) {
throw new \Exception('水印图像不存在');
}
//创建水印图像资源
$water = new Imagick(realpath($source));
@@ -382,37 +427,37 @@ class Imagick{
/* 居中水印 */
case THINKIMAGE_WATER_CENTER:
$x = ($this->info['width'] - $info[0])/2;
$y = ($this->info['height'] - $info[1])/2;
$x = ($this->info['width'] - $info[0]) / 2;
$y = ($this->info['height'] - $info[1]) / 2;
break;
/* 下居中水印 */
case THINKIMAGE_WATER_SOUTH:
$x = ($this->info['width'] - $info[0])/2;
$x = ($this->info['width'] - $info[0]) / 2;
$y = $this->info['height'] - $info[1];
break;
/* 右居中水印 */
case THINKIMAGE_WATER_EAST:
$x = $this->info['width'] - $info[0];
$y = ($this->info['height'] - $info[1])/2;
$y = ($this->info['height'] - $info[1]) / 2;
break;
/* 上居中水印 */
case THINKIMAGE_WATER_NORTH:
$x = ($this->info['width'] - $info[0])/2;
$x = ($this->info['width'] - $info[0]) / 2;
$y = 0;
break;
/* 左居中水印 */
case THINKIMAGE_WATER_WEST:
$x = 0;
$y = ($this->info['height'] - $info[1])/2;
$y = ($this->info['height'] - $info[1]) / 2;
break;
default:
/* 自定义水印坐标 */
if(is_array($locate)){
if (is_array($locate)) {
list($x, $y) = $locate;
} else {
throw new \Exception('不支持的水印位置类型');
@@ -422,12 +467,12 @@ class Imagick{
//创建绘图资源
$draw = new ImagickDraw();
$draw->composite($water->getImageCompose(), $x, $y, $info[0], $info[1], $water);
if('gif' == $this->info['type']){
if ('gif' == $this->info['type']) {
$img = $this->im->coalesceImages();
$this->im->destroy(); //销毁原图
do{
do {
//添加水印
$img->drawImage($draw);
} while ($img->nextImage());
@@ -456,35 +501,39 @@ class Imagick{
* @param integer $offset 文字相对当前位置的偏移量
* @param integer $angle 文字倾斜角度
*/
public function text($text, $font, $size, $color = '#00000000',
$locate = THINKIMAGE_WATER_SOUTHEAST, $offset = 0, $angle = 0){
public function text($text, $font, $size, $color = '#00000000',
$locate = THINKIMAGE_WATER_SOUTHEAST, $offset = 0, $angle = 0) {
//资源检测
if(empty($this->im)) throw new \Exception('没有可以被写入文字的图像资源');
if(!is_file($font)) throw new \Exception("不存在的字体文件:{$font}");
if (empty($this->im)) {
throw new \Exception('没有可以被写入文字的图像资源');
}
if (!is_file($font)) {
throw new \Exception("不存在的字体文件:{$font}");
}
//获取颜色和透明度
if(is_array($color)){
if (is_array($color)) {
$color = array_map('dechex', $color);
foreach ($color as &$value) {
$value = str_pad($value, 2, '0', STR_PAD_LEFT);
}
$color = '#' . implode('', $color);
} elseif(!is_string($color) || 0 !== strpos($color, '#')) {
} elseif (!is_string($color) || 0 !== strpos($color, '#')) {
throw new \Exception('错误的颜色值');
}
$col = substr($color, 0, 7);
$alp = strlen($color) == 9 ? substr($color, -2) : 0;
//获取文字信息
$draw = new ImagickDraw();
$draw->setFont(realpath($font));
$draw->setFontSize($size);
$draw->setFillColor($col);
$draw->setFillAlpha(1-hexdec($alp)/127);
$draw->setFillAlpha(1 - hexdec($alp) / 127);
$draw->setTextAntialias(true);
$draw->setStrokeAntialias(true);
$metrics = $this->im->queryFontMetrics($draw, $text);
/* 计算文字初始坐标和尺寸 */
@@ -497,7 +546,7 @@ class Imagick{
switch ($locate) {
/* 右下角文字 */
case THINKIMAGE_WATER_SOUTHEAST:
$x += $this->info['width'] - $w;
$x += $this->info['width'] - $w;
$y += $this->info['height'] - $h;
break;
@@ -518,35 +567,35 @@ class Imagick{
/* 居中文字 */
case THINKIMAGE_WATER_CENTER:
$x += ($this->info['width'] - $w)/2;
$y += ($this->info['height'] - $h)/2;
$x += ($this->info['width'] - $w) / 2;
$y += ($this->info['height'] - $h) / 2;
break;
/* 下居中文字 */
case THINKIMAGE_WATER_SOUTH:
$x += ($this->info['width'] - $w)/2;
$x += ($this->info['width'] - $w) / 2;
$y += $this->info['height'] - $h;
break;
/* 右居中文字 */
case THINKIMAGE_WATER_EAST:
$x += $this->info['width'] - $w;
$y += ($this->info['height'] - $h)/2;
$y += ($this->info['height'] - $h) / 2;
break;
/* 上居中文字 */
case THINKIMAGE_WATER_NORTH:
$x += ($this->info['width'] - $w)/2;
$x += ($this->info['width'] - $w) / 2;
break;
/* 左居中文字 */
case THINKIMAGE_WATER_WEST:
$y += ($this->info['height'] - $h)/2;
$y += ($this->info['height'] - $h) / 2;
break;
default:
/* 自定义文字坐标 */
if(is_array($locate)){
if (is_array($locate)) {
list($posx, $posy) = $locate;
$x += $posx;
$y += $posy;
@@ -556,19 +605,19 @@ class Imagick{
}
/* 设置偏移量 */
if(is_array($offset)){
$offset = array_map('intval', $offset);
if (is_array($offset)) {
$offset = array_map('intval', $offset);
list($ox, $oy) = $offset;
} else{
} else {
$offset = intval($offset);
$ox = $oy = $offset;
$ox = $oy = $offset;
}
/* 写入文字 */
if('gif' == $this->info['type']){
if ('gif' == $this->info['type']) {
$img = $this->im->coalesceImages();
$this->im->destroy(); //销毁原图
do{
do {
$img->annotateImage($draw, $x + $ox, $y + $oy, $angle, $text);
} while ($img->nextImage());
@@ -585,7 +634,8 @@ class Imagick{
/**
* 析构方法,用于销毁图像资源
*/
public function __destruct() {
public function __destruct()
{
empty($this->im) || $this->im->destroy();
}
}

View File

@@ -17,14 +17,15 @@ namespace think;
// Oauth::login(); // 跳转到授权登录页面 或者 Oauth::login($callbackUrl);
// Oauth::call('api','params'); // 调用API接口
// </code>
class Oauth {
class Oauth
{
/**
* 操作句柄
* @var object
* @access protected
*/
static protected $handler = null;
protected static $handler = null;
/**
* 连接oauth
@@ -33,39 +34,46 @@ class Oauth {
* @param array $options 配置数组
* @return object
*/
static public function connect($type,$options=[]) {
$class = 'think\\oauth\\driver\\'.strtolower($type);
public static function connect($type, $options = [])
{
$class = 'think\\oauth\\driver\\' . strtolower($type);
self::$handler = new $class($options);
return self::$handler;
}
// 跳转到授权登录页面
static public function login($callback=''){
public static function login($callback = '')
{
self::$handler->login($callback);
}
// 获取access_token
static public function getAccessToken($code){
public static function getAccessToken($code)
{
self::$handler->getAccessToken($code);
}
// 设置保存过的token信息
static public function setToken($token){
public static function setToken($token)
{
self::$handler->setToken($token);
}
// 获取oauth用户信息
static public function getOauthInfo(){
public static function getOauthInfo()
{
return self::$handler->getOauthInfo();
}
// 获取openid信息
static public function getOpenId(){
public static function getOpenId()
{
return self::$handler->getOpenId();
}
// 调用oauth接口API
static public function call($api,$param='',$method='GET'){
return self::$handler->call($api,$param,$method);
public static function call($api, $param = '', $method = 'GET')
{
return self::$handler->call($api, $param, $method);
}
}

View File

@@ -11,7 +11,8 @@
namespace think\oauth;
abstract class Driver {
abstract class Driver
{
/**
* oauth版本
@@ -39,7 +40,7 @@ abstract class Driver {
/**
* grant_type 目前只能为 authorization_code
* @var string
* @var string
*/
protected $grantType = 'authorization_code';
@@ -75,18 +76,20 @@ abstract class Driver {
/**
* 构造方法,配置应用信息
* @param array $config
* @param array $config
*/
public function __construct($config = []){
public function __construct($config = [])
{
$this->appKey = $config['app_key'];
$this->appSecret = $config['app_secret'];
$this->authorize = isset($config['authorize']) ? $config['authorize'] : '';
$this->callback = isset($config['callback']) ? $config['callback'] : '';
$this->callback = isset($config['callback']) ? $config['callback'] : '';
}
// 跳转到授权登录页面
public function login($callback = ''){
if($callback) {
public function login($callback = '')
{
if ($callback) {
$this->callback = $callback;
}
//跳转到授权页面
@@ -95,20 +98,21 @@ abstract class Driver {
}
/**
* 请求code
* 请求code
*/
public function getRequestCodeURL(){
public function getRequestCodeURL()
{
//Oauth 标准参数
$params = array(
'client_id' => $this->appKey,
'redirect_uri' => $this->callback,
'response_type' => $this->responseType,
);
//获取额外参数
if($this->authorize){
if ($this->authorize) {
parse_str($this->authorize, $_param);
if(is_array($_param)){
if (is_array($_param)) {
$params = array_merge($params, $_param);
} else {
throw new \Exception('AUTHORIZE配置不正确');
@@ -116,18 +120,19 @@ abstract class Driver {
}
return $this->getRequestCodeURL . '?' . http_build_query($params);
}
/**
* 获取access_token
* @param string $code 授权登录成功后得到的code信息
*/
public function getAccessToken($code){
public function getAccessToken($code)
{
$params = array(
'client_id' => $this->appKey,
'client_secret' => $this->appSecret,
'grant_type' => $this->grantType,
'redirect_uri' => $this->callback,
'code' => $code,
'client_id' => $this->appKey,
'client_secret' => $this->appSecret,
'grant_type' => $this->grantType,
'redirect_uri' => $this->callback,
'code' => $code,
);
// 获取token信息
$data = $this->http($this->getAccessTokenURL, $params, 'POST');
@@ -140,8 +145,9 @@ abstract class Driver {
* 设置access_token
* @param string $token
*/
public function setToken($token){
$this->token = $token;
public function setToken($token)
{
$this->token = $token;
}
/**
@@ -150,9 +156,12 @@ abstract class Driver {
* @param array/string $param 额外参数
* @return array:
*/
protected function param($params, $param){
if(is_string($param))
protected function param($params, $param)
{
if (is_string($param)) {
parse_str($param, $param);
}
return array_merge($params, $param);
}
@@ -162,7 +171,8 @@ abstract class Driver {
* @param string $fix api后缀
* @return string 请求的完整URL
*/
protected function url($api, $fix = ''){
protected function url($api, $fix = '')
{
return $this->apiBase . $api . $fix;
}
@@ -173,39 +183,43 @@ abstract class Driver {
* @param string $method 请求方法GET/POST
* @return array $data 响应数据
*/
protected function http($url, $params, $method = 'GET', $header = [], $multi = false){
protected function http($url, $params, $method = 'GET', $header = [], $multi = false)
{
$opts = array(
CURLOPT_TIMEOUT => 30,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => $header
CURLOPT_HTTPHEADER => $header,
);
/* 根据请求类型设置特定参数 */
switch(strtoupper($method)){
switch (strtoupper($method)) {
case 'GET':
$opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
break;
case 'POST':
//判断是否传输文件
$params = $multi ? $params : http_build_query($params);
$opts[CURLOPT_URL] = $url;
$opts[CURLOPT_POST] = 1;
$params = $multi ? $params : http_build_query($params);
$opts[CURLOPT_URL] = $url;
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = $params;
break;
default:
throw new \Exception('不支持的请求方式!');
}
/* 初始化并执行curl请求 */
$ch = curl_init();
curl_setopt_array($ch, $opts);
$data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if($error) throw new \Exception('请求发生错误:' . $error);
return $data;
if ($error) {
throw new \Exception('请求发生错误:' . $error);
}
return $data;
}
/**
@@ -224,7 +238,7 @@ abstract class Driver {
* 抽象方法在SNSSDK中实现
* 获取当前授权用户的SNS标识
*/
abstract public function getOpenId();
abstract public function getOpenId();
/**
* 抽象方法

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Baidu extends Driver{
class Baidu extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,12 +40,13 @@ class Baidu extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* 百度调用公共参数 */
$params = array(
'access_token' => $this->token['access_token'],
);
$data = $this->http($this->url($api), $this->param($params, $param), $method);
return json_decode($data, true);
}
@@ -52,38 +55,45 @@ class Baidu extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['refresh_token']){
if ($data['access_token'] && $data['expires_in'] && $data['refresh_token']) {
$data['openid'] = $this->openid();
return $data;
} else
} else {
throw new \Exception("获取百度ACCESS_TOKEN出错{$data['error']}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
$data = $this->call('passport/users/getLoggedInUser');
return !empty($data['uid'])?$data['uid']:null;
return !empty($data['uid']) ? $data['uid'] : null;
}
/**
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$data = $this->call('passport/users/getLoggedInUser');
if(!empty($data['uid'])){
$userInfo['type'] = 'BAIDU';
$userInfo['name'] = $data['uid'];
$userInfo['nick'] = $data['uname'];
$userInfo['avatar'] = "http://tb.himg.baidu.com/sys/portrait/item/{$data['portrait']}";
public function getOauthInfo()
{
$data = $this->call('passport/users/getLoggedInUser');
if (!empty($data['uid'])) {
$userInfo['type'] = 'BAIDU';
$userInfo['name'] = $data['uid'];
$userInfo['nick'] = $data['uname'];
$userInfo['avatar'] = "http://tb.himg.baidu.com/sys/portrait/item/{$data['portrait']}";
return $userInfo;
} else {
throw new \Exception("获取百度用户信息失败:{$data['error_msg']}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Diandian extends Driver{
class Diandian extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,12 +40,13 @@ class Diandian extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* 点点网调用公共参数 */
$params = array(
'access_token' => $this->token['access_token'],
);
$data = $this->http($this->url($api, '.json'), $this->param($params, $param), $method);
return json_decode($data, true);
}
@@ -52,23 +55,29 @@ class Diandian extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['token_type'] && $data['uid']){
if ($data['access_token'] && $data['expires_in'] && $data['token_type'] && $data['uid']) {
$data['openid'] = $data['uid'];
unset($data['uid']);
return $data;
} else
} else {
throw new \Exception("获取点点网ACCESS_TOKEN出错{$data['error']}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
return null;
}
@@ -76,14 +85,15 @@ class Diandian extends Driver{
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$data = $this->call('user/info');
public function getOauthInfo()
{
$data = $this->call('user/info');
if(!empty($data['meta']['status']) && $data['meta']['status'] == 200){
$userInfo['type'] = 'DIANDIAN';
$userInfo['name'] = $data['response']['name'];
$userInfo['nick'] = $data['response']['name'];
$userInfo['avatar'] = "https://api.diandian.com/v1/blog/{$data['response']['blogs'][0]['blogUuid']}/avatar/144";
if (!empty($data['meta']['status']) && 200 == $data['meta']['status']) {
$userInfo['type'] = 'DIANDIAN';
$userInfo['name'] = $data['response']['name'];
$userInfo['nick'] = $data['response']['name'];
$userInfo['avatar'] = "https://api.diandian.com/v1/blog/{$data['response']['blogs'][0]['blogUuid']}/avatar/144";
return $userInfo;
} else {
E("获取点点用户信息失败:{$data}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Douban extends Driver{
class Douban extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,7 +40,8 @@ class Douban extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* 豆瓣调用公共参数 */
$params = [];
$header = array("Authorization: Bearer {$this->token['access_token']}");
@@ -50,38 +53,45 @@ class Douban extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['refresh_token'] && $data['douban_user_id']){
if ($data['access_token'] && $data['expires_in'] && $data['refresh_token'] && $data['douban_user_id']) {
$data['openid'] = $data['douban_user_id'];
unset($data['douban_user_id']);
return $data;
} else
} else {
throw new \Exception("获取豆瓣ACCESS_TOKEN出错{$data['msg']}");
}
}
/**
* 获取当前授权应用的openid
* @return string|null
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
return null;
}
/**
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$data = $this->call('user/~me');
public function getOauthInfo()
{
$data = $this->call('user/~me');
if(empty($data['code'])){
$userInfo['type'] = 'DOUBAN';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['avatar'];
if (empty($data['code'])) {
$userInfo['type'] = 'DOUBAN';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['avatar'];
return $userInfo;
} else {
E("获取豆瓣用户信息失败:{$data['msg']}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Github extends Driver{
class Github extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,7 +40,8 @@ class Github extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* Github 调用公共参数 */
$params = [];
$header = array("Authorization: bearer {$this->token['access_token']}");
@@ -51,39 +54,45 @@ class Github extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
parse_str($result, $data);
if($data['access_token'] && $data['token_type']){
if ($data['access_token'] && $data['token_type']) {
$data['openid'] = $this->getOpenId();
return $data;
} else
} else {
throw new \Exception("获取 Github ACCESS_TOKEN出错未知错误");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
$data = $this->call('user');
return !empty($data['id'])?$data['id']:null;
return !empty($data['id']) ? $data['id'] : null;
}
/**
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$data = $this->call('user');
public function getOauthInfo()
{
$data = $this->call('user');
if(empty($data['code'])){
$userInfo['type'] = 'GITHUB';
$userInfo['name'] = $data['login'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['avatar_url'];
if (empty($data['code'])) {
$userInfo['type'] = 'GITHUB';
$userInfo['name'] = $data['login'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['avatar_url'];
return $userInfo;
} else {
E("获取Github用户信息失败{$data}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Google extends Driver{
class Google extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -44,7 +46,8 @@ class Google extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* Google 调用公共参数 */
$params = [];
$header = array("Authorization: Bearer {$this->token['access_token']}");
@@ -57,39 +60,45 @@ class Google extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['token_type'] && $data['expires_in']){
if ($data['access_token'] && $data['token_type'] && $data['expires_in']) {
$data['openid'] = $this->getOpenId();
return $data;
} else
} else {
throw new \Exception("获取 Google ACCESS_TOKEN出错未知错误");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
$data = $this->call('userinfo');
return !empty($data['id'])?$data['id']:null;
return !empty($data['id']) ? $data['id'] : null;
}
/**
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$data = $this->call('userinfo');
public function getOauthInfo()
{
$data = $this->call('userinfo');
if(!empty($data['id'])){
$userInfo['type'] = 'GOOGLE';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['picture'];
if (!empty($data['id'])) {
$userInfo['type'] = 'GOOGLE';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['picture'];
return $userInfo;
} else {
E("获取Google用户信息失败{$data}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Kaixin extends Driver{
class Kaixin extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,12 +40,13 @@ class Kaixin extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* 开心网调用公共参数 */
$params = array(
'access_token' => $this->token['access_token'],
);
$data = $this->http($this->url($api, '.json'), $this->param($params, $param), $method);
return json_decode($data, true);
}
@@ -52,39 +55,45 @@ class Kaixin extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['refresh_token']){
if ($data['access_token'] && $data['expires_in'] && $data['refresh_token']) {
$data['openid'] = $this->getOpenId();
return $data;
} else
} else {
throw new \Exception("获取开心网ACCESS_TOKEN出错{$data['error']}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
$data = $this->call('users/me');
return !empty($data['uid'])?$data['uid']:null;
return !empty($data['uid']) ? $data['uid'] : null;
}
/**
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$data = $this->call('users/me');
if(!empty($data['uid'])){
$userInfo['type'] = 'KAIXIN';
$userInfo['name'] = $data['uid'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['logo50'];
public function getOauthInfo()
{
$data = $this->call('users/me');
if (!empty($data['uid'])) {
$userInfo['type'] = 'KAIXIN';
$userInfo['name'] = $data['uid'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['logo50'];
return $userInfo;
} else {
E("获取开心网用户信息失败:{$data['error']}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Msn extends Driver{
class Msn extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -44,7 +46,8 @@ class Msn extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* MSN 调用公共参数 */
$params = array(
'access_token' => $this->token['access_token'],
@@ -58,39 +61,45 @@ class Msn extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['token_type'] && $data['expires_in']){
if ($data['access_token'] && $data['token_type'] && $data['expires_in']) {
$data['openid'] = $this->getOpenId();
return $data;
} else
} else {
throw new \Exception("获取 MSN ACCESS_TOKEN出错未知错误");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
$data = $this->call('me');
return !empty($data['id'])?$data['id']:null;
return !empty($data['id']) ? $data['id'] : null;
}
/**
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
public function getOauthInfo()
{
$data = $this->call('me');
if(!empty($data['id'])){
$userInfo['type'] = 'MSN';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = '微软暂未提供头像URL请通过 me/picture 接口下载';
if (!empty($data['id'])) {
$userInfo['type'] = 'MSN';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = '微软暂未提供头像URL请通过 me/picture 接口下载';
return $userInfo;
} else {
E("获取msn用户信息失败{$data}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Qq extends Driver{
class Qq extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -44,56 +46,66 @@ class Qq extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* 腾讯QQ调用公共参数 */
$params = array(
'oauth_consumer_key' => $this->AppKey,
'access_token' => $this->token['access_token'],
'openid' => $this->openid(),
'format' => 'json'
'format' => 'json',
);
$data = $this->http($this->url($api), $this->param($params, $param), $method);
return json_decode($data, true);
}
/**
* 解析access_token方法请求后的返回值
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
parse_str($result, $data);
if($data['access_token'] && $data['expires_in']){
if ($data['access_token'] && $data['expires_in']) {
$data['openid'] = $this->getOpenId();
return $data;
} else
} else {
throw new \Exception("获取腾讯QQ ACCESS_TOKEN 出错:{$result}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
if($data['access_token']){
}
if ($data['access_token']) {
$data = $this->http($this->url('oauth2.0/me'), array('access_token' => $data['access_token']));
$data = json_decode(trim(substr($data, 9), " );\n"), true);
if(isset($data['openid']))
if (isset($data['openid'])) {
return $data['openid'];
}
}
return null;
}
public function getOauthInfo(){
public function getOauthInfo()
{
$data = $this->call('user/get_user_info');
if($data['ret'] == 0){
$userInfo['type'] = 'QQ';
$userInfo['name'] = $data['nickname'];
$userInfo['nick'] = $data['nickname'];
$userInfo['avatar'] = $data['figureurl_2'];
if (0 == $data['ret']) {
$userInfo['type'] = 'QQ';
$userInfo['name'] = $data['nickname'];
$userInfo['nick'] = $data['nickname'];
$userInfo['avatar'] = $data['figureurl_2'];
return $userInfo;
} else {
E("获取腾讯QQ用户信息失败{$data['msg']}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Renren extends Driver{
class Renren extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,7 +40,8 @@ class Renren extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'POST'){
public function call($api, $param = '', $method = 'POST')
{
/* 人人网调用公共参数 */
$params = array(
'method' => $api,
@@ -46,7 +49,7 @@ class Renren extends Driver{
'v' => '1.0',
'format' => 'json',
);
$data = $this->http($this->url(''), $this->param($params, $param), $method);
return json_decode($data, true);
}
@@ -57,16 +60,17 @@ class Renren extends Driver{
* @param array/string $param 额外参数
* @return array:
*/
protected function param($params, $param){
protected function param($params, $param)
{
$params = parent::param($params, $param);
/* 签名 */
ksort($params);
$param = [];
foreach ($params as $key => $value){
foreach ($params as $key => $value) {
$param[] = "{$key}={$value}";
}
$sign = implode('', $param).$this->AppSecret;
$sign = implode('', $param) . $this->AppSecret;
$params['sig'] = md5($sign);
return $params;
@@ -76,23 +80,29 @@ class Renren extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['refresh_token'] && $data['user']['id']){
if ($data['access_token'] && $data['expires_in'] && $data['refresh_token'] && $data['user']['id']) {
$data['openid'] = $data['user']['id'];
unset($data['user']);
return $data;
} else
} else {
throw new \Exception("获取人人网ACCESS_TOKEN出错{$data['error_description']}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
return null;
}
@@ -100,14 +110,15 @@ class Renren extends Driver{
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$data = $this->call('users.getInfo');
public function getOauthInfo()
{
$data = $this->call('users.getInfo');
if(!isset($data['error_code'])){
$userInfo['type'] = 'RENREN';
$userInfo['name'] = $data[0]['name'];
$userInfo['nick'] = $data[0]['name'];
$userInfo['avatar'] = $data[0]['headurl'];
if (!isset($data['error_code'])) {
$userInfo['type'] = 'RENREN';
$userInfo['name'] = $data[0]['name'];
$userInfo['nick'] = $data[0]['name'];
$userInfo['avatar'] = $data[0]['headurl'];
return $userInfo;
} else {
E("获取人人网用户信息失败:{$data['error_msg']}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Sina extends Driver{
class Sina extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,12 +40,13 @@ class Sina extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET', $multi = false){
public function call($api, $param = '', $method = 'GET', $multi = false)
{
/* 新浪微博调用公共参数 */
$params = array(
'access_token' => $this->token['access_token'],
);
$data = $this->http($this->url($api, '.json'), $this->param($params, $param), $method, $multi);
return json_decode($data, true);
}
@@ -52,23 +55,29 @@ class Sina extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['remind_in'] && $data['uid']){
if ($data['access_token'] && $data['expires_in'] && $data['remind_in'] && $data['uid']) {
$data['openid'] = $data['uid'];
unset($data['uid']);
return $data;
} else
} else {
throw new \Exception("获取新浪微博ACCESS_TOKEN出错{$data['error']}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
return null;
}
@@ -76,14 +85,15 @@ class Sina extends Driver{
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$data = $this->call('users.getInfo');
public function getOauthInfo()
{
$data = $this->call('users.getInfo');
if(!isset($data['error_code'])){
$userInfo['type'] = 'RENREN';
$userInfo['name'] = $data[0]['name'];
$userInfo['nick'] = $data[0]['name'];
$userInfo['avatar'] = $data[0]['headurl'];
if (!isset($data['error_code'])) {
$userInfo['type'] = 'RENREN';
$userInfo['name'] = $data[0]['name'];
$userInfo['nick'] = $data[0]['name'];
$userInfo['avatar'] = $data[0]['headurl'];
return $userInfo;
} else {
E("获取人人网用户信息失败:{$data['error_msg']}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Sohu extends Driver{
class Sohu extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,7 +40,8 @@ class Sohu extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* 搜狐调用公共参数 */
$params = array(
'access_token' => $this->token['access_token'],
@@ -52,23 +55,29 @@ class Sohu extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['refresh_token'] && $data['open_id']){
if ($data['access_token'] && $data['expires_in'] && $data['refresh_token'] && $data['open_id']) {
$data['openid'] = $data['open_id'];
unset($data['open_id']);
return $data;
} else
} else {
throw new \Exception("获取搜狐ACCESS_TOKEN出错{$data['error']}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
return null;
}
@@ -76,14 +85,15 @@ class Sohu extends Driver{
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
public function getOauthInfo()
{
$data = $this->call('i/prv/1/user/get-basic-info');
if('success' == $data['message'] && !empty($data['data'])){
$userInfo['type'] = 'SOHU';
$userInfo['name'] = $data['data']['open_id'];
$userInfo['nick'] = $data['data']['nick'];
$userInfo['avatar'] = $data['data']['icon'];
if ('success' == $data['message'] && !empty($data['data'])) {
$userInfo['type'] = 'SOHU';
$userInfo['name'] = $data['data']['open_id'];
$userInfo['nick'] = $data['data']['nick'];
$userInfo['avatar'] = $data['data']['icon'];
return $userInfo;
} else {
E("获取搜狐用户信息失败:{$data['message']}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class T163 extends Driver{
class T163 extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,12 +40,13 @@ class T163 extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* 新浪微博调用公共参数 */
$params = array(
'oauth_token' => $this->token['access_token'],
);
$data = $this->http($this->url($api, '.json'), $this->param($params, $param), $method);
return json_decode($data, true);
}
@@ -52,40 +55,46 @@ class T163 extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['uid'] && $data['access_token'] && $data['expires_in'] && $data['refresh_token']){
if ($data['uid'] && $data['access_token'] && $data['expires_in'] && $data['refresh_token']) {
$data['openid'] = $data['uid'];
unset($data['uid']);
return $data;
} else
} else {
throw new \Exception("获取网易微博ACCESS_TOKEN出错{$data['error']}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
$data = $this->call('users/show');
return !empty($data['id'])?$data['id']:null;
return !empty($data['id']) ? $data['id'] : null;
}
/**
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
public function getOauthInfo()
{
$data = $this->call('users/show');
if($data['error_code'] == 0){
$userInfo['type'] = 'T163';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['screen_name'];
$userInfo['avatar'] = str_replace('w=48&h=48', 'w=180&h=180', $data['profile_image_url']);
if (0 == $data['error_code']) {
$userInfo['type'] = 'T163';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['screen_name'];
$userInfo['avatar'] = str_replace('w=48&h=48', 'w=180&h=180', $data['profile_image_url']);
return $userInfo;
} else {
E("获取网易微博用户信息失败:{$data['error']}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Taobao extends Driver{
class Taobao extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,7 +40,8 @@ class Taobao extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* 淘宝网调用公共参数 */
$params = array(
'method' => $api,
@@ -54,23 +57,29 @@ class Taobao extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['taobao_user_id']){
if ($data['access_token'] && $data['expires_in'] && $data['taobao_user_id']) {
$data['openid'] = $data['taobao_user_id'];
unset($data['taobao_user_id']);
return $data;
} else
} else {
throw new \Exception("获取淘宝网ACCESS_TOKEN出错{$data['error']}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
return null;
}
@@ -78,20 +87,21 @@ class Taobao extends Driver{
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$fields = 'user_id,nick,sex,buyer_credit,avatar,has_shop,vip_info';
$data = $this->call('taobao.user.buyer.get', "fields={$fields}");
if(!empty($data['user_buyer_get_response']['user'])){
$user = $data['user_buyer_get_response']['user'];
$userInfo['type'] = 'TAOBAO';
$userInfo['name'] = $user['user_id'];
$userInfo['nick'] = $user['nick'];
$userInfo['avatar'] = $user['avatar'];
return $userInfo;
} else {
E("获取淘宝网用户信息失败:{$data['error_response']['msg']}");
}
public function getOauthInfo()
{
$fields = 'user_id,nick,sex,buyer_credit,avatar,has_shop,vip_info';
$data = $this->call('taobao.user.buyer.get', "fields={$fields}");
if (!empty($data['user_buyer_get_response']['user'])) {
$user = $data['user_buyer_get_response']['user'];
$userInfo['type'] = 'TAOBAO';
$userInfo['name'] = $user['user_id'];
$userInfo['nick'] = $user['nick'];
$userInfo['avatar'] = $user['avatar'];
return $userInfo;
} else {
E("获取淘宝网用户信息失败:{$data['error_response']['msg']}");
}
}
}

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class Tencent extends Driver{
class Tencent extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,7 +40,8 @@ class Tencent extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET', $multi = false){
public function call($api, $param = '', $method = 'GET', $multi = false)
{
/* 腾讯微博调用公共参数 */
$params = array(
'oauth_consumer_key' => $this->AppKey,
@@ -47,7 +50,7 @@ class Tencent extends Driver{
'clientip' => get_client_ip(),
'oauth_version' => '2.a',
'scope' => 'all',
'format' => 'json'
'format' => 'json',
);
$data = $this->http($this->url($api), $this->param($params, $param), $method, $multi);
@@ -55,25 +58,31 @@ class Tencent extends Driver{
}
/**
* 解析access_token方法请求后的返回值
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
parse_str($result, $data);
$data = array_merge($data, ['openid' => $_GET['openid'], 'openkey' => $_GET['openkey']]);
if($data['access_token'] && $data['expires_in'] && $data['openid'])
if ($data['access_token'] && $data['expires_in'] && $data['openid']) {
return $data;
else
} else {
throw new \Exception("获取腾讯微博 ACCESS_TOKEN 出错:{$result}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
return null;
}
@@ -81,14 +90,15 @@ class Tencent extends Driver{
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
$data = $this->call('users.getInfo');
public function getOauthInfo()
{
$data = $this->call('users.getInfo');
if(!isset($data['error_code'])){
$userInfo['type'] = 'RENREN';
$userInfo['name'] = $data[0]['name'];
$userInfo['nick'] = $data[0]['name'];
$userInfo['avatar'] = $data[0]['headurl'];
if (!isset($data['error_code'])) {
$userInfo['type'] = 'RENREN';
$userInfo['name'] = $data[0]['name'];
$userInfo['nick'] = $data[0]['name'];
$userInfo['avatar'] = $data[0]['headurl'];
return $userInfo;
} else {
E("获取人人网用户信息失败:{$data['error_msg']}");

View File

@@ -10,9 +10,11 @@
// +----------------------------------------------------------------------
namespace think\oauth\driver;
use think\oauth\Driver;
class X360 extends Driver{
class X360 extends Driver
{
/**
* 获取requestCode的api接口
* @var string
@@ -38,12 +40,13 @@ class X360 extends Driver{
* @param string $method HTTP请求方法 默认为GET
* @return json
*/
public function call($api, $param = '', $method = 'GET'){
public function call($api, $param = '', $method = 'GET')
{
/* 360开放平台调用公共参数 */
$params = array(
'access_token' => $this->token['access_token'],
);
$data = $this->http($this->url($api, '.json'), $this->param($params, $param), $method);
return json_decode($data, true);
}
@@ -52,38 +55,45 @@ class X360 extends Driver{
* 解析access_token方法请求后的返回值
* @param string $result 获取access_token的方法的返回值
*/
protected function parseToken($result){
protected function parseToken($result)
{
$data = json_decode($result, true);
if($data['access_token'] && $data['expires_in'] && $data['refresh_token']){
if ($data['access_token'] && $data['expires_in'] && $data['refresh_token']) {
$data['openid'] = $this->getOpenId();
return $data;
} else
} else {
throw new \Exception("获取360开放平台ACCESS_TOKEN出错{$data['error']}");
}
}
/**
* 获取当前授权应用的openid
* @return string
*/
public function getOpenId(){
if(!empty($this->token['openid']))
public function getOpenId()
{
if (!empty($this->token['openid'])) {
return $this->token['openid'];
}
$data = $this->call('user/me');
return !empty($data['id'])?$data['id']:null;
return !empty($data['id']) ? $data['id'] : null;
}
/**
* 获取当前登录的用户信息
* @return array
*/
public function getOauthInfo(){
public function getOauthInfo()
{
$data = $this->call('user/me');
if($data['error_code'] == 0){
$userInfo['type'] = 'X360';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['avatar'];
if (0 == $data['error_code']) {
$userInfo['type'] = 'X360';
$userInfo['name'] = $data['name'];
$userInfo['nick'] = $data['name'];
$userInfo['avatar'] = $data['avatar'];
return $userInfo;
} else {
E("获取360用户信息失败{$data['error']}");

View File

@@ -12,21 +12,24 @@
namespace think;
// 内容解析类
class Parser {
class Parser
{
static private $handler = [];
private static $handler = [];
// 解析内容
static public function parse($content,$type){
if(!isset(self::$handler[$type])) {
$class = '\\think\\parser\\driver\\'.strtolower($type);
self::$handler[$type] = new $class();
public static function parse($content, $type)
{
if (!isset(self::$handler[$type])) {
$class = '\\think\\parser\\driver\\' . strtolower($type);
self::$handler[$type] = new $class();
}
return self::$handler[$type]->parse($content);
}
// 调用驱动类的方法
static public function __callStatic($method, $params){
return self::parse($params[0],$method);
public static function __callStatic($method, $params)
{
return self::parse($params[0], $method);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -13,278 +13,303 @@
namespace think\parser\driver;
class Ubb{
/**
* UBB标签匹配规则
* @var array
*/
private $ubb = [
['table' , '\[table(?:=([\d%]*))?\]', '\[\/table\]', 'width'],
['tr' , '\[tr\]', '\[\/tr\]', 'tag'],
['th' , '\[th(?:=([\d%]*)(?:,([\d%]*))?)?\]', '\[\/th\]', 'widthAndHeight'],
['td' , '\[td(?:=([\d%]*)(?:,([\d%]*))?)?\]', '\[\/td\]', 'widthAndHeight'],
['img' , '\[img(?:=([\d%]*)(?:,([\d%]*))?)?\]', '\[\/img\]', 'imgWidthAndHeight'],
['img' , '\[img=(.*?)(?:,([\d%]*)(?:,([\d%]*))?)?\/\]', 'img'],
['a' , '\[url(?:=(.*?)(?:,([\w\-]*))?)?\]', '\[\/url\]', 'urlClass'],
['a' , '\[a(?:=(.*?)(?:,([\w\-]*))?)?\]', '\[\/a\]', 'urlClass'],
['a' , '\[url=(.*?)(?:,([\w\-]*))?\/\]', 'url'],
['a' , '\[a=(.*?)(?:,([\w\-]*))?\/\]', 'url'],
['a' , '\[email(?:=([\w\-]*))?\]', '\[\/email\]', 'emailClass'],
['ul' , '\[ul(?:=([\w\-]*))?\]', '\[\/ul\]', 'class'],
['ol' , '\[ol(?:=([\w\-]*))?\]', '\[\/ol\]', 'class'],
['li' , '\[li(?:=([\w\-]*))?\]', '\[\/li\]', 'class'],
['span' , '\[span(?:=([\w\-]*))?\]', '\[\/span\]', 'class'],
['div' , '\[div(?:=([\w\-]*))?\]', '\[\/div\]', 'class'],
['p' , '\[p(?:=([\w\-]*))?\]', '\[\/p\]', 'class'],
['strong' , '\[b\]', '\[\/b\]', 'tag'],
['strong' , '\[strong\]', '\[\/strong\]', 'tag'],
['i' , '\[i\]', '\[\/i\]', 'tag'],
['em' , '\[em\]', '\[\/em\]', 'tag'],
['sub' , '\[sub\]', '\[\/sub\]', 'tag'],
['sup' , '\[sup\]', '\[\/sup\]', 'tag'],
['pre' , '\[code(?:=([a-z#\+\/]*))?\]', '\[\/code\]', 'code'],
['code' , '\[line(?:=([a-z#\+\/]*))?\]', '\[\/line\]', 'code'],
];
class Ubb
{
/**
* UBB标签匹配规则
* @var array
*/
private $ubb = [
['table', '\[table(?:=([\d%]*))?\]', '\[\/table\]', 'width'],
['tr', '\[tr\]', '\[\/tr\]', 'tag'],
['th', '\[th(?:=([\d%]*)(?:,([\d%]*))?)?\]', '\[\/th\]', 'widthAndHeight'],
['td', '\[td(?:=([\d%]*)(?:,([\d%]*))?)?\]', '\[\/td\]', 'widthAndHeight'],
['img', '\[img(?:=([\d%]*)(?:,([\d%]*))?)?\]', '\[\/img\]', 'imgWidthAndHeight'],
['img', '\[img=(.*?)(?:,([\d%]*)(?:,([\d%]*))?)?\/\]', 'img'],
['a', '\[url(?:=(.*?)(?:,([\w\-]*))?)?\]', '\[\/url\]', 'urlClass'],
['a', '\[a(?:=(.*?)(?:,([\w\-]*))?)?\]', '\[\/a\]', 'urlClass'],
['a', '\[url=(.*?)(?:,([\w\-]*))?\/\]', 'url'],
['a', '\[a=(.*?)(?:,([\w\-]*))?\/\]', 'url'],
['a', '\[email(?:=([\w\-]*))?\]', '\[\/email\]', 'emailClass'],
['ul', '\[ul(?:=([\w\-]*))?\]', '\[\/ul\]', 'class'],
['ol', '\[ol(?:=([\w\-]*))?\]', '\[\/ol\]', 'class'],
['li', '\[li(?:=([\w\-]*))?\]', '\[\/li\]', 'class'],
['span', '\[span(?:=([\w\-]*))?\]', '\[\/span\]', 'class'],
['div', '\[div(?:=([\w\-]*))?\]', '\[\/div\]', 'class'],
['p', '\[p(?:=([\w\-]*))?\]', '\[\/p\]', 'class'],
['strong', '\[b\]', '\[\/b\]', 'tag'],
['strong', '\[strong\]', '\[\/strong\]', 'tag'],
['i', '\[i\]', '\[\/i\]', 'tag'],
['em', '\[em\]', '\[\/em\]', 'tag'],
['sub', '\[sub\]', '\[\/sub\]', 'tag'],
['sup', '\[sup\]', '\[\/sup\]', 'tag'],
['pre', '\[code(?:=([a-z#\+\/]*))?\]', '\[\/code\]', 'code'],
['code', '\[line(?:=([a-z#\+\/]*))?\]', '\[\/line\]', 'code'],
];
/**
* 解析UBB代码为HTML
* @param string $content 要解析的UBB代码
* @return string 解析后的HTML代码
*/
public function parse($content = ''){
if(empty($content)) return '';
/**
* 解析UBB代码为HTML
* @param string $content 要解析的UBB代码
* @return string 解析后的HTML代码
*/
public function parse($content = '')
{
if (empty($content)) {
return '';
}
for($i = 0, $count = count($this->ubb); $i < $count; $i++){
if(count($this->ubb[$i]) == 4){ //解析闭合标签
$content = $this->closeTag($content, $this->ubb[$i]);
} else {
$content = $this->onceTag($content, $this->ubb[$i]);
}
}
for ($i = 0, $count = count($this->ubb); $i < $count; $i++) {
if (count($this->ubb[$i]) == 4) {
//解析闭合标签
$content = $this->closeTag($content, $this->ubb[$i]);
} else {
$content = $this->onceTag($content, $this->ubb[$i]);
}
}
return nl2br($content);
}
return nl2br($content);
}
/**
* 解析闭合标签,支持嵌套
* @param string $data 要解析的数据
* @param array $rule 解析规则
* @return string 解析后的内容
*/
private function closeTag($data, $rule = ''){
static $tag, $reg, $func, $count = 0;
if(is_string($data)){
list($tag, $reg[0], $reg[1], $func) = $rule;
do{
$data = preg_replace_callback("/({$reg[0]})(.*?)({$reg[1]})/is",
[$this, 'closeTag'], $data);
} while ($count && $count--); //递归解析,直到嵌套解析完毕
return $data;
} elseif(is_array($data)){
$num = count($data);
if(preg_match("/{$reg[0]}/is", $data[$num-2])){ //存在嵌套,进一步解析
$count = 1;
$data[$num-2] = preg_replace_callback("/({$reg[0]})(.*?)({$reg[1]})/is",
[$this, 'closeTag'], $data[$num-2] . $data[$num-1]);
return $data[1] . $data[$num-2];
} else { //不存在嵌套,直接解析内容
$parse = '_' . $func;
$data[$num-2] = trim($data[$num-2], "\r\n"); //去掉标签内容两端的换行符
return $this->$parse($tag, $data);
}
}
}
/**
* 解析闭合标签,支持嵌套
* @param string $data 要解析的数据
* @param array $rule 解析规则
* @return string 解析后的内容
*/
private function closeTag($data, $rule = '')
{
static $tag, $reg, $func, $count = 0;
if (is_string($data)) {
list($tag, $reg[0], $reg[1], $func) = $rule;
do {
$data = preg_replace_callback("/({$reg[0]})(.*?)({$reg[1]})/is",
[$this, 'closeTag'], $data);
} while ($count && $count--); //递归解析,直到嵌套解析完毕
return $data;
} elseif (is_array($data)) {
$num = count($data);
if (preg_match("/{$reg[0]}/is", $data[$num - 2])) {
//存在嵌套,进一步解析
$count = 1;
$data[$num - 2] = preg_replace_callback("/({$reg[0]})(.*?)({$reg[1]})/is",
[$this, 'closeTag'], $data[$num - 2] . $data[$num - 1]);
return $data[1] . $data[$num - 2];
} else {
//不存在嵌套,直接解析内容
$parse = '_' . $func;
$data[$num - 2] = trim($data[$num - 2], "\r\n"); //去掉标签内容两端的换行符
return $this->$parse($tag, $data);
}
}
}
/**
* 解析单标签
* @param string $data 要解析的数据
* @param array $rule 解析规则
* @return string 解析后的内容
*/
private function onceTag($data, $rule = ''){
list($tag, $reg, $func) = $rule;
return preg_replace_callback("/{$reg}/is", [$this, '_' . $func], $data);
}
/**
* 解析单标签
* @param string $data 要解析的数据
* @param array $rule 解析规则
* @return string 解析后的内容
*/
private function onceTag($data, $rule = '')
{
list($tag, $reg, $func) = $rule;
return preg_replace_callback("/{$reg}/is", [$this, '_' . $func], $data);
}
/**
* 解析img单标签
* @param array $data 解析数据
* @return string 解析后的标签
*/
private function _img($data){
$data[4] = $data[1];
return $this->_imgWidthAndHeight('', $data);
}
/**
* 解析img单标签
* @param array $data 解析数据
* @return string 解析后的标签
*/
private function _img($data)
{
$data[4] = $data[1];
return $this->_imgWidthAndHeight('', $data);
}
/**
* 解析url单标签
* @param array $data 解析数据
* @return string 解析后的标签
*/
private function _url($data){
$data[3] = $data[2];
$data[4] = $data[2] = $data[1];
return $this->_urlClass('', $data);
}
/**
* 解析url单标签
* @param array $data 解析数据
* @return string 解析后的标签
*/
private function _url($data)
{
$data[3] = $data[2];
$data[4] = $data[2] = $data[1];
return $this->_urlClass('', $data);
}
/**
* 解析没有属性的标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - 标签内容
* @return string 解析后的标签
*/
private function _tag($name, $data){
return "<{$name}>{$data[2]}</{$name}>";
}
/**
* 解析没有属性的标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - 标签内容
* @return string 解析后的标签
*/
private function _tag($name, $data)
{
return "<{$name}>{$data[2]}</{$name}>";
}
/**
* 解析代码
* @param string $name 标签名
* @param array $data 解析数据 [2] - 语言类型,[3] - 代码内容
* @return string 解析后的标签
*/
private function _code($name, $data){
$fix = ($name == 'pre') ? ['<pre>', '</pre>'] : ['', ''];
if(empty($data[2])){
$data = "{$fix[0]}<code>{$data[3]}</code>{$fix[1]}";
} else {
$data = "{$fix[0]}<code data-lang=\"{$data[2]}\">{$data[3]}</code>{$fix[1]}";
}
return $data;
}
/**
* 解析代码
* @param string $name 标签名
* @param array $data 解析数据 [2] - 语言类型,[3] - 代码内容
* @return string 解析后的标签
*/
private function _code($name, $data)
{
$fix = ('pre' == $name) ? ['<pre>', '</pre>'] : ['', ''];
if (empty($data[2])) {
$data = "{$fix[0]}<code>{$data[3]}</code>{$fix[1]}";
} else {
$data = "{$fix[0]}<code data-lang=\"{$data[2]}\">{$data[3]}</code>{$fix[1]}";
}
return $data;
}
/**
* 解析含有width属性的标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - width, [3] - 标签内容
* @return string 解析后的标签
*/
private function _width($name, $data){
if(empty($data[2])){
$data = "<{$name}>{$data[3]}</{$name}>";
} else {
$data = "<{$name} width=\"{$data[2]}\">{$data[3]}</{$name}>";
}
return $data;
}
/**
* 解析含有width属性的标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - width, [3] - 标签内容
* @return string 解析后的标签
*/
private function _width($name, $data)
{
if (empty($data[2])) {
$data = "<{$name}>{$data[3]}</{$name}>";
} else {
$data = "<{$name} width=\"{$data[2]}\">{$data[3]}</{$name}>";
}
return $data;
}
/**
* 解析含有width和height属性的标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - width, [3] - height, [4] - 标签内容
* @return string 解析后的标签
*/
private function _widthAndHeight($name, $data){
if(empty($data[2]) && empty($data[3])){
$data = "<{$name}>{$data[4]}</{$name}>";
} elseif(!empty($data[2]) && empty($data[3])) {
$data = "<{$name} width=\"{$data[2]}\">{$data[4]}</{$name}>";
} elseif(empty($data[2]) && !empty($data[3])) {
$data = "<{$name} height=\"{$data[3]}\">{$data[4]}</{$name}>";
} else {
$data = "<{$name} width=\"{$data[2]}\" height=\"{$data[3]}\">{$data[4]}</{$name}>";
}
return $data;
}
/**
* 解析含有width和height属性的标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - width, [3] - height, [4] - 标签内容
* @return string 解析后的标签
*/
private function _widthAndHeight($name, $data)
{
if (empty($data[2]) && empty($data[3])) {
$data = "<{$name}>{$data[4]}</{$name}>";
} elseif (!empty($data[2]) && empty($data[3])) {
$data = "<{$name} width=\"{$data[2]}\">{$data[4]}</{$name}>";
} elseif (empty($data[2]) && !empty($data[3])) {
$data = "<{$name} height=\"{$data[3]}\">{$data[4]}</{$name}>";
} else {
$data = "<{$name} width=\"{$data[2]}\" height=\"{$data[3]}\">{$data[4]}</{$name}>";
}
return $data;
}
/**
* 解析含有width和height属性的图片标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - width, [3] - height, [4] - 图片URL
* @return string 解析后的标签
*/
private function _imgWidthAndHeight($name, $data){
if(empty($data[2]) && empty($data[3])){
$data = "<img src=\"{$data[4]}\" />";
} elseif(!empty($data[2]) && empty($data[3])) {
$data = "<img width=\"{$data[2]}\" src=\"{$data[4]}\" />";
} elseif(empty($data[2]) && !empty($data[3])) {
$data = "<img height=\"{$data[3]}\" src=\"{$data[4]}\" />";
} else {
$data = "<img width=\"{$data[2]}\" height=\"{$data[3]}\" src=\"{$data[4]}\" />";
}
return $data;
}
/**
* 解析含有width和height属性的图片标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - width, [3] - height, [4] - 图片URL
* @return string 解析后的标签
*/
private function _imgWidthAndHeight($name, $data)
{
if (empty($data[2]) && empty($data[3])) {
$data = "<img src=\"{$data[4]}\" />";
} elseif (!empty($data[2]) && empty($data[3])) {
$data = "<img width=\"{$data[2]}\" src=\"{$data[4]}\" />";
} elseif (empty($data[2]) && !empty($data[3])) {
$data = "<img height=\"{$data[3]}\" src=\"{$data[4]}\" />";
} else {
$data = "<img width=\"{$data[2]}\" height=\"{$data[3]}\" src=\"{$data[4]}\" />";
}
return $data;
}
/**
* 解析含有class属性的标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - class, [3] - 标签内容
* @return string 解析后的标签
*/
private function _class($name, $data){
if(empty($data[2])){
$data = "<{$name}>{$data[3]}</{$name}>";
} else {
$data = "<{$name} class=\"{$data[2]}\">{$data[3]}</{$name}>";
}
return $data;
}
/**
* 解析含有class属性的标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - class, [3] - 标签内容
* @return string 解析后的标签
*/
private function _class($name, $data)
{
if (empty($data[2])) {
$data = "<{$name}>{$data[3]}</{$name}>";
} else {
$data = "<{$name} class=\"{$data[2]}\">{$data[3]}</{$name}>";
}
return $data;
}
/**
* 解析含有class属性的url标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - url, [3] - text
* @return string 解析后的标签
*/
private function _urlClass($name, $data){
empty($data[2]) && $data[2] = $data[4];
if(empty($data[3])){
$data = "<a href=\"{$data[2]}\">{$data[4]}</a>";
} else {
$data = "<a href=\"{$data[2]}\" class=\"{$data[3]}\">{$data[4]}</a>";
}
return $data;
}
/**
* 解析含有class属性的url标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - url, [3] - text
* @return string 解析后的标签
*/
private function _urlClass($name, $data)
{
empty($data[2]) && $data[2] = $data[4];
if (empty($data[3])) {
$data = "<a href=\"{$data[2]}\">{$data[4]}</a>";
} else {
$data = "<a href=\"{$data[2]}\" class=\"{$data[3]}\">{$data[4]}</a>";
}
return $data;
}
/**
* 解析含有class属性的email标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - class, [3] - email地址
* @return string 解析后的标签
*/
private function _emailClass($name, $data){
//不是正确的EMAIL则不解析
if(preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', $data[3]))
return $data[0];
/**
* 解析含有class属性的email标签
* @param string $name 标签名
* @param array $data 解析数据 [2] - class, [3] - email地址
* @return string 解析后的标签
*/
private function _emailClass($name, $data)
{
//不是正确的EMAIL则不解析
if (preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', $data[3])) {
return $data[0];
}
//编码email地址防治被采集
$email = $this->encodeEmailAddress($data[3]);
if(empty($data[2])){
$data = "<a href=\"{$email[0]}\">{$email[1]}</a>";
} else {
$data = "<a href=\"{$email[0]}\" class=\"{$data[2]}\">{$email[1]}</a>";
}
return $data;
}
//编码email地址防治被采集
$email = $this->encodeEmailAddress($data[3]);
/**
* 编码EMAIL地址可以防治部分采集软件
* @param string $addr EMAIL地址
* @return array 编码后的EMAIL地址 [0] - 带mailto, [1] - 不带mailto
*/
private function encodeEmailAddress($addr) {
$addr = "mailto:" . $addr;
$chars = preg_split('/(?<!^)(?!$)/', $addr);
$seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
foreach ($chars as $key => $char) {
$ord = ord($char);
# Ignore non-ascii chars.
if ($ord < 128) {
$r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
# roughly 10% raw, 45% hex, 45% dec
# '@' *must* be encoded. I insist.
if ($r > 90 && $char != '@') /* do nothing */;
else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
else $chars[$key] = '&#'.$ord.';';
}
}
$addr = implode('', $chars);
$text = implode('', array_slice($chars, 7)); # text without `mailto:`
if (empty($data[2])) {
$data = "<a href=\"{$email[0]}\">{$email[1]}</a>";
} else {
$data = "<a href=\"{$email[0]}\" class=\"{$data[2]}\">{$email[1]}</a>";
}
return $data;
}
return [$addr, $text];
}
/**
* 编码EMAIL地址可以防治部分采集软件
* @param string $addr EMAIL地址
* @return array 编码后的EMAIL地址 [0] - 带mailto, [1] - 不带mailto
*/
private function encodeEmailAddress($addr)
{
$addr = "mailto:" . $addr;
$chars = preg_split('/(?<!^)(?!$)/', $addr);
$seed = (int) abs(crc32($addr) / strlen($addr)); # Deterministic seed.
foreach ($chars as $key => $char) {
$ord = ord($char);
# Ignore non-ascii chars.
if ($ord < 128) {
$r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
# roughly 10% raw, 45% hex, 45% dec
# '@' *must* be encoded. I insist.
if ($r > 90 && '@' != $char) /* do nothing */;
elseif ($r < 45) {
$chars[$key] = '&#x' . dechex($ord) . ';';
} else {
$chars[$key] = '&#' . $ord . ';';
}
}
}
$addr = implode('', $chars);
$text = implode('', array_slice($chars, 7)); # text without `mailto:`
return [$addr, $text];
}
}

View File

@@ -12,32 +12,36 @@
namespace think;
// 内容解析类
class Transform {
static private $handler = [];
use think\Exception as Exception;
class Transform
{
private static $handler = [];
/**
* 初始化解析驱动
* @static
* @static
* @access private
* @param string $type 驱动类型
*/
static private function init($type){
if(!isset(self::$handler[$type])) {
$class = '\\think\\transform\\driver\\' . strtolower($type);
private static function init($type)
{
if (!isset(self::$handler[$type])) {
$class = '\\think\\transform\\driver\\' . strtolower($type);
self::$handler[$type] = new $class();
}
}
/**
* 编码内容
* @static
* @static
* @access public
* @param mixed $content 要编码的数据
* @param string $type 数据类型
* @param array $config XML配置参数JSON格式生成无此参数
* @return string 编码后的数据
*/
static public function encode($content, $type, array $config = []){
public static function encode($content, $type, array $config = [])
{
self::init($type);
return self::$handler[$type]->encode($content, $config);
}
@@ -50,7 +54,8 @@ class Transform {
* @param array $config XML配置参数JSON格式解码无此参数
* @return mixed 解码后的数据
*/
static public function decode($content, $type, $assoc = true, array $config = []){
public static function decode($content, $type, $assoc = true, array $config = [])
{
self::init($type);
return self::$handler[$type]->decode($content, $assoc, $config);
}
@@ -58,8 +63,9 @@ class Transform {
// 调用驱动类的方法
// Transform::xmlEncode('abc')
// Transform::jsonDecode('abc', true);
static public function __callStatic($method, $params){
if(empty($params[0])){
public static function __callStatic($method, $params)
{
if (empty($params[0])) {
return '';
}
@@ -68,11 +74,11 @@ class Transform {
switch (strtolower(substr($method, -6))) {
case 'encode':
$config = empty($params[1]) ? [] : $params[1];
$config = empty($params[1]) ? [] : $params[1];
return self::encode($params[0], $type, $config);
case 'decode':
$assoc = empty($params[1]) ? true : $params[1];
$config = empty($params[2]) ? [] : $params[2];
$config = empty($params[2]) ? [] : $params[2];
return self::decode($params[0], $type, $assoc, $config);
default:
throw new Exception("call to undefined method {$method}");

View File

@@ -11,12 +11,15 @@
namespace think\transform\driver;
class Json{
public function encode($data){
return json_encode($data, JSON_UNESCAPED_UNICODE);
}
class Json
{
public function encode($data)
{
return json_encode($data, JSON_UNESCAPED_UNICODE);
}
public function decode($data, $assoc = true){
return json_decode($data, $assoc);
}
public function decode($data, $assoc = true)
{
return json_decode($data, $assoc);
}
}

View File

@@ -11,16 +11,17 @@
namespace think\transform\driver;
class Xml{
class Xml
{
/**
* XML数据默认配置项
* @var array
*/
private $config = [
'root_name' => 'think', //根节点名称
'root_attr' => [], //根节点属性
'item_name' => 'item', //数字节点转换的名称
'item_key' => 'id', //数字节点转换的属性名
'root_attr' => [], //根节点属性
'item_name' => 'item', //数字节点转换的名称
'item_key' => 'id', //数字节点转换的属性名
];
/**
@@ -29,7 +30,8 @@ class Xml{
* @param array $config 数据配置项
* @return string 编码后的XML数据
*/
public function encode($data, array $config = []) {
public function encode($data, array $config = [])
{
//初始化配置
$config = array_merge($this->config, $config);
@@ -46,17 +48,18 @@ class Xml{
* @param array $config 数据配置项
* @return string 解码后的XML数据
*/
public function decode($str, $assoc = true, array $config = []){
public function decode($str, $assoc = true, array $config = [])
{
//初始化配置
$config = array_merge($this->config, $config);
//创建XML对象
$xml = new \SimpleXMLElement($str);
if($assoc){
if ($assoc) {
self::xml2data($xml, $data, $config['item_name'], $config['item_key']);
return $data;
}
return $xml;
}
@@ -69,16 +72,17 @@ class Xml{
* @param string $id 数字索引key转换为的属性名
* @return string
*/
static public function data2xml(SimpleXMLElement $xml, $data, $item = 'item', $id = 'id') {
public static function data2xml(SimpleXMLElement $xml, $data, $item = 'item', $id = 'id')
{
foreach ($data as $key => $value) {
//指定默认的数字key
if(is_numeric($key)){
if (is_numeric($key)) {
$id && $val = $key;
$key = $item;
$key = $item;
}
//添加子元素
if(is_array($value) || is_object($value)){
if (is_array($value) || is_object($value)) {
$child = $xml->addChild($key);
self::data2xml($child, $value, $item, $id);
} else {
@@ -99,15 +103,16 @@ class Xml{
* @param string $item 数字索引时的节点名称
* @param string $id 数字索引key转换为的属性名
*/
static public function xml2data(SimpleXMLElement $xml, &$data, $item = 'item', $id = 'id'){
public static function xml2data(SimpleXMLElement $xml, &$data, $item = 'item', $id = 'id')
{
foreach ($xml->children() as $items) {
$key = $items->getName();
$attr = $items->attributes();
if($key == $item && isset($attr[$id])){
if ($key == $item && isset($attr[$id])) {
$key = strval($attr[$id]);
}
if($items->count()){
if ($items->count()) {
self::xml2data($items, $val);
} else {
$val = strval($items);

View File

@@ -11,64 +11,71 @@
namespace think;
class Upload {
protected $config = [
'max_size' => -1, // 上传文件的最大值
'support_multi' => true, // 是否支持多文件上传
'allow_exts' => [], // 允许上传的文件后缀 留空不作后缀检查
'allow_types' => [], // 允许上传文件类型 留空不做检查
'thumb' => false, // 使用对上传图片进行缩略图处理
'thumb_max_width' => '',// 缩略图最大宽度
'thumb_max_height' => '',// 缩略图最大高度
'thumb_prefix' => 'thumb_',// 缩略图前缀
'thumb_suffix' => '',
'thumb_path' => '',// 缩略图保存路径
'thumb_file' => '',// 缩略图文件名
'thumb_ext' => '',// 缩略图扩展名
'thumb_remove_origin' => false,// 是否移除原图
'zip_images' => false,// 压缩图片文件上传
'auto_sub' => false,// 启用子目录保存文件
'sub_type' => 'hash',// 子目录创建方式 可以使用hash date custom
'sub_dir' => '', // 子目录名称 subType为custom方式后有效
'date_format' => 'Ymd',
'hash_level' => 1, // hash的目录层次
'save_path' => '',// 上传文件保存路径
'auto_check' => true, // 是否自动检查附件
'upload_replace' => false,// 存在同名是否覆盖
'save_rule' => 'uniqid',// 上传文件命名规则
'hash_type' => 'md5_file',// 上传文件Hash规则函数名
];
use think\Image;
class Upload
{
protected $config = [
'max_size' => -1, // 上传文件的最大值
'support_multi' => true, // 是否支持多文件上传
'allow_exts' => [], // 允许上传的文件后缀 留空不作后缀检查
'allow_types' => [], // 允许上传的文件类型 留空不做检查
'thumb' => false, // 使用对上传图片进行缩略图处理
'thumb_max_width' => '', // 缩略图最大宽度
'thumb_max_height' => '', // 缩略图最大高度
'thumb_prefix' => 'thumb_', // 缩略图前缀
'thumb_suffix' => '',
'thumb_path' => '', // 缩略图保存路径
'thumb_file' => '', // 缩略图文件名
'thumb_ext' => '', // 缩略图扩展名
'thumb_remove_origin' => false, // 是否移除原图
'zip_images' => false, // 压缩图片文件上传
'auto_sub' => false, // 启用子目录保存文件
'sub_type' => 'hash', // 子目录创建方式 可以使用hash date custom
'sub_dir' => '', // 子目录名称 subType为custom方式后有效
'date_format' => 'Ymd',
'hash_level' => 1, // hash的目录层次
'save_path' => '', // 上传文件保存路径
'auto_check' => true, // 是否自动检查附件
'upload_replace' => false, // 存在同名是否覆盖
'save_rule' => 'uniqid', // 上传文件命名规则
'hash_type' => 'md5_file', // 上传文件Hash规则函数名
];
// 错误信息
private $error = '';
// 上传成功的文件信息
private $uploadFileInfo ;
private $uploadFileInfo;
public function __get($name){
if(isset($this->config[$name])) {
public function __get($name)
{
if (isset($this->config[$name])) {
return $this->config[$name];
}
return null;
}
public function __set($name,$value){
if(isset($this->config[$name])) {
$this->config[$name] = $value;
public function __set($name, $value)
{
if (isset($this->config[$name])) {
$this->config[$name] = $value;
}
}
public function __isset($name){
public function __isset($name)
{
return isset($this->config[$name]);
}
/**
* 架构函数
* @access public
* @param array $config 上传参数
*/
public function __construct($config=[]) {
if(is_array($config)) {
$this->config = array_merge($this->config,$config);
public function __construct($config = [])
{
if (is_array($config)) {
$this->config = array_merge($this->config, $config);
}
}
@@ -79,54 +86,55 @@ class Upload {
* @param string $value 数据表名
* @return string
*/
protected function save($file) {
$filename = $file['save_path'].$file['savename'];
if(!$this->upload_replace && is_file($filename)) {
protected function save($file)
{
$filename = $file['save_path'] . $file['savename'];
if (!$this->upload_replace && is_file($filename)) {
// 不覆盖同名文件
$this->error = '文件已经存在!'.$filename;
$this->error = '文件已经存在!' . $filename;
return false;
}
// 如果是图像文件 检测文件格式
if( in_array(strtolower($file['extension']),['gif','jpg','jpeg','bmp','png','swf'])) {
$info = getimagesize($file['tmp_name']);
if(false === $info || ('gif' == strtolower($file['extension']) && empty($info['bits']))){
if (in_array(strtolower($file['extension']), ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
$info = getimagesize($file['tmp_name']);
if (false === $info || ('gif' == strtolower($file['extension']) && empty($info['bits']))) {
$this->error = '非法图像文件';
return false;
return false;
}
}
if(!move_uploaded_file($file['tmp_name'], $this->autoCharset($filename,'utf-8','gbk'))) {
if (!move_uploaded_file($file['tmp_name'], $this->autoCharset($filename, 'utf-8', 'gbk'))) {
$this->error = '文件上传保存错误!';
return false;
}
if($this->thumb && in_array(strtolower($file['extension']),['gif','jpg','jpeg','bmp','png'])) {
$image = getimagesize($filename);
if(false !== $image) {
if ($this->thumb && in_array(strtolower($file['extension']), ['gif', 'jpg', 'jpeg', 'bmp', 'png'])) {
$image = getimagesize($filename);
if (false !== $image) {
//是图像文件生成缩略图
$thumbWidth = explode(',',$this->thumb_max_width);
$thumbHeight = explode(',',$this->thumb_max_height);
$thumb_prefix = explode(',',$this->thumb_prefix);
$thumb_suffix = explode(',',$this->thumb_suffix);
$thumb_file = explode(',',$this->thumb_file);
$thumb_path = $this->thumb_path?$this->thumb_path:dirname($filename).'/';
$thumb_ext = $this->thumb_ext ? $this->thumb_ext : $file['extension']; //自定义缩略图扩展名
$thumbWidth = explode(',', $this->thumb_max_width);
$thumbHeight = explode(',', $this->thumb_max_height);
$thumb_prefix = explode(',', $this->thumb_prefix);
$thumb_suffix = explode(',', $this->thumb_suffix);
$thumb_file = explode(',', $this->thumb_file);
$thumb_path = $this->thumb_path ? $this->thumb_path : dirname($filename) . '/';
$thumb_ext = $this->thumb_ext ? $this->thumb_ext : $file['extension']; //自定义缩略图扩展名
// 生成图像缩略图
for($i=0,$len=count($thumbWidth); $i<$len; $i++) {
if(!empty($thumb_file[$i])) {
$thumbname = $thumb_file[$i];
}else{
$prefix = isset($thumb_prefix[$i])?$thumb_prefix[$i]:$thumb_prefix[0];
$suffix = isset($thumb_suffix[$i])?$thumb_suffix[$i]:$thumb_suffix[0];
$thumbname = $prefix.basename($filename,'.'.$file['extension']).$suffix;
for ($i = 0, $len = count($thumbWidth); $i < $len; $i++) {
if (!empty($thumb_file[$i])) {
$thumbname = $thumb_file[$i];
} else {
$prefix = isset($thumb_prefix[$i]) ? $thumb_prefix[$i] : $thumb_prefix[0];
$suffix = isset($thumb_suffix[$i]) ? $thumb_suffix[$i] : $thumb_suffix[0];
$thumbname = $prefix . basename($filename, '.' . $file['extension']) . $suffix;
}
Image::thumb($filename,$thumb_path.$thumbname.'.'.$thumb_ext,'',$thumbWidth[$i],$thumbHeight[$i],true);
Image::thumb($filename, $thumb_path . $thumbname . '.' . $thumb_ext, '', $thumbWidth[$i], $thumbHeight[$i], true);
}
if($this->thumb_remove_origin) {
if ($this->thumb_remove_origin) {
// 生成缩略图之后删除原图
unlink($filename);
}
}
}
if($this->zipImags) {
if ($this->zipImags) {
// TODO 对图片压缩包在线解压
}
@@ -139,66 +147,77 @@ class Upload {
* @param string $savePath 上传文件保存路径
* @return string
*/
public function upload($savePath ='') {
public function upload($savePath = '')
{
//如果不指定保存文件名,则由系统默认
if(empty($savePath))
if (empty($savePath)) {
$savePath = $this->save_path;
}
// 检查上传目录
if(!is_dir($savePath)) {
if (!is_dir($savePath)) {
// 检查目录是否编码后的
if(is_dir(base64_decode($savePath))) {
$savePath = base64_decode($savePath);
}else{
if (is_dir(base64_decode($savePath))) {
$savePath = base64_decode($savePath);
} else {
// 尝试创建目录
if(!mkdir($savePath)){
$this->error = '上传目录'.$savePath.'不存在';
if (!mkdir($savePath)) {
$this->error = '上传目录' . $savePath . '不存在';
return false;
}
}
}else {
if(!is_writeable($savePath)) {
$this->error = '上传目录'.$savePath.'不可写';
} else {
if (!is_writeable($savePath)) {
$this->error = '上传目录' . $savePath . '不可写';
return false;
}
}
$fileInfo = [];
$isUpload = false;
$fileInfo = [];
$isUpload = false;
// 获取上传的文件信息
// 对$_FILES数组信息处理
$files = $this->dealFiles($_FILES);
foreach($files as $key => $file) {
$files = $this->dealFiles($_FILES);
foreach ($files as $key => $file) {
//过滤无效的上传
if(!empty($file['name'])) {
if (!empty($file['name'])) {
//登记上传文件的扩展信息
if(!isset($file['key'])) $file['key'] = $key;
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
if (!isset($file['key'])) {
$file['key'] = $key;
}
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
// 自动检查附件
if($this->auto_check) {
if(!$this->check($file))
if ($this->auto_check) {
if (!$this->check($file)) {
return false;
}
}
//保存上传文件
if(!$this->save($file)) return false;
if(function_exists($this->hash_type)) {
$fun = $this->hash_type;
$file['hash'] = $fun($this->autoCharset($file['savepath'].$file['savename'],'utf-8','gbk'));
if (!$this->save($file)) {
return false;
}
if (function_exists($this->hash_type)) {
$fun = $this->hash_type;
$file['hash'] = $fun($this->autoCharset($file['savepath'] . $file['savename'], 'utf-8', 'gbk'));
}
//上传成功后保存文件信息,供其他地方调用
unset($file['tmp_name'],$file['error']);
unset($file['tmp_name'], $file['error']);
$fileInfo[] = $file;
$isUpload = true;
}
}
if($isUpload) {
if ($isUpload) {
$this->uploadFileInfo = $fileInfo;
return true;
}else {
$this->error = '没有选择上传文件';
} else {
$this->error = '没有选择上传文件';
return false;
}
}
@@ -210,60 +229,70 @@ class Upload {
* @param string $savePath 上传文件保存路径
* @return string
*/
public function uploadOne($file,$savePath=''){
public function uploadOne($file, $savePath = '')
{
//如果不指定保存文件名,则由系统默认
if(empty($savePath))
if (empty($savePath)) {
$savePath = $this->save_path;
}
// 检查上传目录
if(!is_dir($savePath)) {
if (!is_dir($savePath)) {
// 尝试创建目录
if(!mkdir($savePath,0777,true)){
$this->error = '上传目录'.$savePath.'不存在';
if (!mkdir($savePath, 0777, true)) {
$this->error = '上传目录' . $savePath . '不存在';
return false;
}
}else {
if(!is_writeable($savePath)) {
$this->error = '上传目录'.$savePath.'不可写';
} else {
if (!is_writeable($savePath)) {
$this->error = '上传目录' . $savePath . '不可写';
return false;
}
}
//过滤无效的上传
if(!empty($file['name'])) {
if (!empty($file['name'])) {
$fileArray = [];
if(is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i=0; $i<$count; $i++) {
foreach ($keys as $key)
$fileArray[$i][$key] = $file[$key][$i];
}
}else{
$fileArray[] = $file;
if (is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i = 0; $i < $count; $i++) {
foreach ($keys as $key) {
$fileArray[$i][$key] = $file[$key][$i];
}
}
} else {
$fileArray[] = $file;
}
$info = [];
foreach ($fileArray as $key=>$file){
$info = [];
foreach ($fileArray as $key => $file) {
//登记上传文件的扩展信息
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
// 自动检查附件
if($this->auto_check) {
if(!$this->check($file))
if ($this->auto_check) {
if (!$this->check($file)) {
return false;
}
}
//保存上传文件
if(!$this->save($file)) return false;
if(function_exists($this->hash_type)) {
$fun = $this->hash_type;
$file['hash'] = $fun($this->autoCharset($file['savepath'].$file['savename'],'utf-8','gbk'));
if (!$this->save($file)) {
return false;
}
unset($file['tmp_name'],$file['error']);
if (function_exists($this->hash_type)) {
$fun = $this->hash_type;
$file['hash'] = $fun($this->autoCharset($file['savepath'] . $file['savename'], 'utf-8', 'gbk'));
}
unset($file['tmp_name'], $file['error']);
$info[] = $file;
}
// 返回上传的文件信息
return $info;
}else {
$this->error = '没有选择上传文件';
} else {
$this->error = '没有选择上传文件';
return false;
}
}
@@ -274,25 +303,26 @@ class Upload {
* @param array $files 上传的文件变量
* @return array
*/
protected function dealFiles($files) {
$fileArray = [];
$n = 0;
foreach ($files as $key=>$file){
if(is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i=0; $i<$count; $i++) {
protected function dealFiles($files)
{
$fileArray = [];
$n = 0;
foreach ($files as $key => $file) {
if (is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i = 0; $i < $count; $i++) {
$fileArray[$n]['key'] = $key;
foreach ($keys as $_key){
foreach ($keys as $_key) {
$fileArray[$n][$_key] = $file[$_key][$i];
}
$n++;
}
}else{
$fileArray[$key] = $file;
} else {
$fileArray[$key] = $file;
}
}
return $fileArray;
return $fileArray;
}
/**
@@ -301,8 +331,9 @@ class Upload {
* @param string $errorNo 错误号码
* @return void
*/
protected function error($errorNo) {
switch($errorNo) {
protected function error($errorNo)
{
switch ($errorNo) {
case 1:
$this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
break;
@@ -324,7 +355,7 @@ class Upload {
default:
$this->error = '未知上传错误!';
}
return ;
return;
}
/**
@@ -333,23 +364,25 @@ class Upload {
* @param string $filename 数据
* @return string
*/
protected function getSaveName($filename) {
protected function getSaveName($filename)
{
$rule = $this->save_rule;
if(empty($rule)) {//没有定义命名规则,则保持文件名不变
if (empty($rule)) {
//没有定义命名规则,则保持文件名不变
$saveName = $filename['name'];
}else {
if(function_exists($rule)) {
} else {
if (function_exists($rule)) {
//使用函数生成一个唯一文件标识号
$saveName = $rule().".".$filename['extension'];
}else {
$saveName = $rule() . "." . $filename['extension'];
} else {
//使用给定的文件名作为标识号
$saveName = $rule.".".$filename['extension'];
$saveName = $rule . "." . $filename['extension'];
}
}
if($this->auto_sub) {
if ($this->auto_sub) {
// 使用子目录保存文件
$filename['savename'] = $saveName;
$saveName = $this->getSubName($filename).$saveName;
$saveName = $this->getSubName($filename) . $saveName;
}
return $saveName;
}
@@ -360,25 +393,26 @@ class Upload {
* @param array $file 上传的文件信息
* @return string
*/
protected function getSubName($file) {
switch($this->sub_type) {
protected function getSubName($file)
{
switch ($this->sub_type) {
case 'custom':
$dir = $this->sub_dir;
$dir = $this->sub_dir;
break;
case 'date':
$dir = date($this->date_format,time()).'/';
$dir = date($this->date_format, time()) . '/';
break;
case 'hash':
default:
$name = md5($file['savename']);
$dir = '';
for($i=0;$i<$this->hash_level;$i++) {
$dir .= $name{$i}.'/';
$name = md5($file['savename']);
$dir = '';
for ($i = 0; $i < $this->hash_level; $i++) {
$dir .= $name{$i} . '/';
}
break;
}
if(!is_dir($file['savepath'].$dir)) {
mkdir($file['savepath'].$dir,0777,true);
if (!is_dir($file['savepath'] . $dir)) {
mkdir($file['savepath'] . $dir, 0777, true);
}
return $dir;
}
@@ -389,8 +423,9 @@ class Upload {
* @param array $file 文件信息
* @return boolean
*/
protected function check($file) {
if($file['error']!== 0) {
protected function check($file)
{
if (0 !== $file['error']) {
//文件上传失败
//捕获错误代码
$this->error($file['error']);
@@ -398,24 +433,24 @@ class Upload {
}
//文件上传成功,进行自定义规则检查
//检查文件大小
if(!$this->checkSize($file['size'])) {
if (!$this->checkSize($file['size'])) {
$this->error = '上传文件大小不符!';
return false;
}
//检查文件Mime类型
if(!$this->checkType($file['type'])) {
if (!$this->checkType($file['type'])) {
$this->error = '上传文件MIME类型不允许';
return false;
}
//检查文件类型
if(!$this->checkExt($file['extension'])) {
$this->error ='上传文件类型不允许';
if (!$this->checkExt($file['extension'])) {
$this->error = '上传文件类型不允许';
return false;
}
//检查是否合法上传
if(!$this->checkUpload($file['tmp_name'])) {
if (!$this->checkUpload($file['tmp_name'])) {
$this->error = '非法上传文件!';
return false;
}
@@ -423,9 +458,10 @@ class Upload {
}
// 自动转换字符集 支持数组转换
protected function autoCharset($fContents, $from='gbk', $to='utf-8') {
$from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
protected function autoCharset($fContents, $from = 'gbk', $to = 'utf-8')
{
$from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
//如果编码相同或者非字符串标量则不转换
return $fContents;
@@ -445,22 +481,27 @@ class Upload {
* @param string $type 数据
* @return boolean
*/
protected function checkType($type) {
if(!empty($this->allow_types))
return in_array(strtolower($type),$this->allow_types);
protected function checkType($type)
{
if (!empty($this->allow_types)) {
return in_array(strtolower($type), $this->allow_types);
}
return true;
}
/**
* 检查上传的文件后缀是否合法
* @access protected
* @param string $ext 后缀名
* @return boolean
*/
protected function checkExt($ext) {
if(!empty($this->allow_exts))
return in_array(strtolower($ext),$this->allow_exts,true);
protected function checkExt($ext)
{
if (!empty($this->allow_exts)) {
return in_array(strtolower($ext), $this->allow_exts, true);
}
return true;
}
@@ -470,7 +511,8 @@ class Upload {
* @param integer $size 数据
* @return boolean
*/
protected function checkSize($size) {
protected function checkSize($size)
{
return !($size > $this->max_size) || (-1 == $this->max_size);
}
@@ -480,7 +522,8 @@ class Upload {
* @param string $filename 文件名
* @return boolean
*/
protected function checkUpload($filename) {
protected function checkUpload($filename)
{
return is_uploaded_file($filename);
}
@@ -490,8 +533,9 @@ class Upload {
* @param string $filename 文件名
* @return boolean
*/
protected function getExt($filename) {
return pathinfo($filename,PATHINFO_EXTENSION);
protected function getExt($filename)
{
return pathinfo($filename, PATHINFO_EXTENSION);
}
/**
@@ -499,7 +543,8 @@ class Upload {
* @access public
* @return array
*/
public function getUploadFileInfo() {
public function getUploadFileInfo()
{
return $this->uploadFileInfo;
}
@@ -508,7 +553,8 @@ class Upload {
* @access public
* @return string
*/
public function getErrorMsg() {
public function getErrorMsg()
{
return $this->error;
}
}

View File

@@ -11,19 +11,22 @@
namespace think;
class Validate {
class Validate
{
protected $validate = []; // 自动验证定义
protected $validate = []; // 自动验证定义
// 是否批处理验证
protected $patchValidate = false;
protected $error = '';
protected $patchValidate = false;
protected $error = '';
public function rule($rule){
$this->validate = $rule;
public function rule($rule)
{
$this->validate = $rule;
return $this;
}
public function getError(){
public function getError()
{
return $this->error;
}
@@ -34,30 +37,41 @@ class Validate {
* @param string $type 创建类型
* @return boolean
*/
public function valid($data,$rule=[]) {
$validate = $rule?$rule:$this->validate;
public function valid($data, $rule = [])
{
$validate = $rule ? $rule : $this->validate;
// 属性验证
if($validate) { // 如果设置了数据自动验证则进行数据验证
if($this->patchValidate) { // 重置验证错误信息
if ($validate) {
// 如果设置了数据自动验证则进行数据验证
if ($this->patchValidate) {
// 重置验证错误信息
$this->error = [];
}
foreach($validate as $key=>$val) {
foreach ($validate as $key => $val) {
// 验证因子定义格式
// array(field,rule,message,condition,type,params)
// 判断是否需要执行验证
if(0==strpos($val[2],'{%') && strpos($val[2],'}'))
// 支持提示信息的多语言 使用 {%语言定义} 方式
$val[2] = L(substr($val[2],2,-1));
$val[3] = isset($val[3])?$val[3]:0;
$val[4] = isset($val[4])?$val[4]:'regex';
if (0 == strpos($val[2], '{%') && strpos($val[2], '}'))
// 支持提示信息的多语言 使用 {%语言定义} 方式
{
$val[2] = L(substr($val[2], 2, -1));
}
$val[3] = isset($val[3]) ? $val[3] : 0;
$val[4] = isset($val[4]) ? $val[4] : 'regex';
// 判断验证条件
if( 1 == $val[3] || (2 == $val[3] && '' != trim($data[$val[0]])) || (0 == $val[3] && isset($data[$val[0]])) ) {
if(false === $this->_validationField($data,$val))
if (1 == $val[3] || (2 == $val[3] && '' != trim($data[$val[0]])) || (0 == $val[3] && isset($data[$val[0]]))) {
if (false === $this->_validationField($data, $val)) {
return false;
}
}
}
// 批量验证的时候最后返回错误
if(!empty($this->error)) return false;
if (!empty($this->error)) {
return false;
}
}
return true;
}
@@ -70,16 +84,17 @@ class Validate {
* @param array $val 验证因子
* @return boolean
*/
protected function _validationField($data,$val) {
if(false === $this->_validationFieldItem($data,$val)){
if($this->patchValidate) {
$this->error[$val[0]] = $val[2];
}else{
$this->error = $val[2];
protected function _validationField($data, $val)
{
if (false === $this->_validationFieldItem($data, $val)) {
if ($this->patchValidate) {
$this->error[$val[0]] = $val[2];
} else {
$this->error = $val[2];
return false;
}
}
return ;
return;
}
/**
@@ -89,25 +104,30 @@ class Validate {
* @param array $val 验证因子
* @return boolean
*/
protected function _validationFieldItem($data,$val) {
switch(strtolower(trim($val[4]))) {
case 'callback':// 调用方法进行验证
$args = isset($val[5])?(array)$val[5]:[];
if(is_string($val[0]) && strpos($val[0], ','))
protected function _validationFieldItem($data, $val)
{
switch (strtolower(trim($val[4]))) {
case 'callback': // 调用方法进行验证
$args = isset($val[5]) ? (array) $val[5] : [];
if (is_string($val[0]) && strpos($val[0], ',')) {
$val[0] = explode(',', $val[0]);
if(is_array($val[0])){
}
if (is_array($val[0])) {
// 支持多个字段验证
foreach($val[0] as $field)
foreach ($val[0] as $field) {
$_data[$field] = $data[$field];
}
array_unshift($args, $_data);
}else{
} else {
array_unshift($args, $data[$val[0]]);
}
return call_user_func_array($val[1], $args);
case 'confirm': // 验证两个字段是否相同
return $data[$val[0]] == $data[$val[1]];
default: // 检查附加规则
return $this->check($data[$val[0]],$val[1],$val[4]);
default: // 检查附加规则
return $this->check($data[$val[0]], $val[1], $val[4]);
}
}
@@ -119,46 +139,55 @@ class Validate {
* @param string $type 验证方式 默认为正则验证
* @return boolean
*/
public function check($value,$rule,$type='regex'){
$type = strtolower(trim($type));
switch($type) {
public function check($value, $rule, $type = 'regex')
{
$type = strtolower(trim($type));
switch ($type) {
case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组
case 'notin':
$range = is_array($rule)? $rule : explode(',',$rule);
return $type == 'in' ? in_array($value ,$range) : !in_array($value ,$range);
$range = is_array($rule) ? $rule : explode(',', $rule);
return 'in' == $type ? in_array($value, $range) : !in_array($value, $range);
case 'between': // 验证是否在某个范围
case 'notbetween': // 验证是否不在某个范围
if (is_array($rule)){
$min = $rule[0];
$max = $rule[1];
}else{
list($min,$max) = explode(',',$rule);
case 'notbetween': // 验证是否不在某个范围
if (is_array($rule)) {
$min = $rule[0];
$max = $rule[1];
} else {
list($min, $max) = explode(',', $rule);
}
return $type == 'between' ? $value>=$min && $value<=$max : $value<$min || $value>$max;
return 'between' == $type ? $value >= $min && $value <= $max : $value < $min || $value > $max;
case 'equal': // 验证是否等于某个值
case 'notequal': // 验证是否等于某个值
return $type == 'equal' ? $value == $rule : $value != $rule;
case 'notequal': // 验证是否等于某个值
return 'equal' == $type ? $value == $rule : $value != $rule;
case 'length': // 验证长度
$length = mb_strlen($value,'utf-8'); // 当前数据长度
if(strpos($rule,',')) { // 长度区间
list($min,$max) = explode(',',$rule);
$length = mb_strlen($value, 'utf-8'); // 当前数据长度
if (strpos($rule, ',')) {
// 长度区间
list($min, $max) = explode(',', $rule);
return $length >= $min && $length <= $max;
}else{// 指定长度
} else {
// 指定长度
return $length == $rule;
}
case 'expire':
list($start,$end) = explode(',',$rule);
if(!is_numeric($start)) $start = strtotime($start);
if(!is_numeric($end)) $end = strtotime($end);
list($start, $end) = explode(',', $rule);
if (!is_numeric($start)) {
$start = strtotime($start);
}
if (!is_numeric($end)) {
$end = strtotime($end);
}
return NOW_TIME >= $start && NOW_TIME <= $end;
case 'ip_allow': // IP 操作许可验证
return in_array($_SERVER['REMOTE_ADDR'],explode(',',$rule));
return in_array($_SERVER['REMOTE_ADDR'], explode(',', $rule));
case 'ip_deny': // IP 操作禁止验证
return !in_array($_SERVER['REMOTE_ADDR'],explode(',',$rule));
return !in_array($_SERVER['REMOTE_ADDR'], explode(',', $rule));
case 'regex':
default: // 默认使用正则验证 可以使用验证类中定义的验证名称
default: // 默认使用正则验证 可以使用验证类中定义的验证名称
// 检查附加规则
return $this->regex($value,$rule);
return $this->regex($value, $rule);
}
}
@@ -169,21 +198,24 @@ class Validate {
* @param string $rule 验证规则
* @return boolean
*/
public function regex($value,$rule) {
public function regex($value, $rule)
{
$validate = [
'require' => '/.+/',
'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
'currency' => '/^\d+(\.\d+)?$/',
'number' => '/^\d+$/',
'zip' => '/^\d{6}$/',
'integer' => '/^[-\+]?\d+$/',
'double' => '/^[-\+]?\d+(\.\d+)?$/',
'english' => '/^[A-Za-z]+$/',
'require' => '/.+/',
'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
'currency' => '/^\d+(\.\d+)?$/',
'number' => '/^\d+$/',
'zip' => '/^\d{6}$/',
'integer' => '/^[-\+]?\d+$/',
'double' => '/^[-\+]?\d+(\.\d+)?$/',
'english' => '/^[A-Za-z]+$/',
];
// 检查是否有内置的正则表达式
if(isset($validate[strtolower($rule)]))
$rule = $validate[strtolower($rule)];
return preg_match($rule,$value)===1;
if (isset($validate[strtolower($rule)])) {
$rule = $validate[strtolower($rule)];
}
return preg_match($rule, $value) === 1;
}
}