rabin 1 年之前
父节点
当前提交
a098fb3cf7
共有 76 个文件被更改,包括 3332 次插入13897 次删除
  1. 14 0
      LICENSE
  2. 20 4
      README.md
  3. 61 30
      boot.php
  4. 0 25
      composer.json
  5. 0 0
      config/README.md
  6. 22 0
      config/env/localhost.php
  7. 62 0
      config/html/default.html
  8. 29 0
      config/lang/en.php
  9. 28 0
      config/lang/zh-cn.php
  10. 31 0
      config/setting.php
  11. 92 0
      config/web/plant.nginx.conf
  12. 404 0
      dever
  13. 0 147
      dever_old.php
  14. 0 0
      package/README.md
  15. 541 0
      src/Ares333/Curl.php
  16. 916 0
      src/Ares333/Toolkit.php
  17. 0 494
      src/Dever/Cache/Handle.php
  18. 0 39
      src/Dever/Cache/Store.php
  19. 0 126
      src/Dever/Cache/Store/Memcache.php
  20. 0 185
      src/Dever/Cache/Store/Redis.php
  21. 10 22
      src/Dever/Config.php
  22. 0 195
      src/Dever/Data/Elastic/Connect.php
  23. 0 703
      src/Dever/Data/Elastic/Store.php
  24. 0 51
      src/Dever/Data/Migration.php
  25. 0 574
      src/Dever/Data/Model.php
  26. 0 577
      src/Dever/Data/Model/Condition.php
  27. 0 980
      src/Dever/Data/Model/Handle.php
  28. 0 239
      src/Dever/Data/Model/Link.php
  29. 0 41
      src/Dever/Data/Model/Opt.php
  30. 0 550
      src/Dever/Data/Model/Request.php
  31. 0 104
      src/Dever/Data/Mongo/Connect.php
  32. 0 494
      src/Dever/Data/Mongo/Store.php
  33. 0 225
      src/Dever/Data/Mysql/Connect.php
  34. 0 402
      src/Dever/Data/Mysql/Store.php
  35. 0 202
      src/Dever/Data/Pdo/Connect.php
  36. 0 503
      src/Dever/Data/Pdo/Store.php
  37. 0 857
      src/Dever/Data/Sql.php
  38. 0 755
      src/Dever/Data/Store - 副本.php
  39. 0 734
      src/Dever/Data/Store.php
  40. 0 562
      src/Dever/Data/Store/Pdo.php
  41. 68 31
      src/Dever/Debug.php
  42. 0 14
      src/Dever/Exceptions.php
  43. 18 0
      src/Dever/Helper/Arr.php
  44. 53 0
      src/Dever/Helper/Cmd.php
  45. 269 0
      src/Dever/Helper/Curl.php
  46. 148 0
      src/Dever/Helper/Date.php
  47. 1 5
      src/Dever/Helper/Env.php
  48. 1 1
      src/Dever/Helper/Lang.php
  49. 15 50
      src/Dever/Helper/Math.php
  50. 42 0
      src/Dever/Helper/Path.php
  51. 127 0
      src/Dever/Helper/Redis.php
  52. 3 3
      src/Dever/Helper/Rule.php
  53. 49 155
      src/Dever/Helper/Str.php
  54. 0 1
      src/Dever/Import.php
  55. 43 73
      src/Dever/Log.php
  56. 17 5
      src/Dever/Model.php
  57. 9 8
      src/Dever/Output.php
  58. 0 164
      src/Dever/Pagination/Html.php
  59. 0 303
      src/Dever/Pagination/Paginator.php
  60. 5 66
      src/Dever/Path.php
  61. 1 1
      src/Dever/Project.php
  62. 23 24
      src/Dever/Route.php
  63. 131 201
      src/Dever/Secure.php
  64. 0 5
      src/Dever/Server.php
  65. 0 64
      src/Dever/Server/Rpc.php
  66. 0 298
      src/Dever/Server/Swoole.php
  67. 0 79
      src/Dever/Server/Udp.php
  68. 11 4
      src/Dever/Sql.php
  69. 1 1
      src/Dever/Store/Base.php
  70. 3 4
      src/Dever/Store/Pdo.php
  71. 0 134
      src/Dever/String/Encrypt.php
  72. 0 113
      src/Dever/Support/Command.php
  73. 0 229
      src/Dever/Support/Date.php
  74. 0 317
      src/Dever/Support/Excel.php
  75. 0 1724
      src/Dever/Support/Img.php
  76. 64 0
      src/Dever/View.php

+ 14 - 0
LICENSE

@@ -0,0 +1,14 @@
+Apache License
+Copyright 2016-2017 Dever(dever.cc)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.

+ 20 - 4
README.md

@@ -2,10 +2,10 @@ DeverPHP 2.0
 
 ## 主要特性
 
-* 极简轻量
-* 高效开发
-* 极速访问
-* 重复使用
+* 轻量
+* 极简
+* 高效
+* 人性
 
 ## 文档
 
@@ -26,3 +26,19 @@ ThinkPHP遵循Apache2开源协议发布,并提供免费使用。
 DeverPHP® 商标和著作权所有者为北京时空之翼网络科技有限公司。
 
 更多细节参阅 [LICENSE.txt](LICENSE.txt)
+
+
+# 名称
+	'name' => 'Dever元生态系统',
+	# 版本配置
+	'version' => '1.0.0 Beta',
+	# 框架名称
+	'framework_name' => 'Dever生态系统 初代核心',
+	# 基本描述
+	'desc' => '高门槛 / 低代码 / 多次元 / 生态化',
+	# copyright
+	'copyright' => '© 2019-2021 dever.cc,Inc. Licensed under MIT license.',
+	# github
+	'github' => 'https://github.com/dever-main/framework',
+	# web
+	'web' => 'http://www.dever.cc/',

+ 61 - 30
dever.php → boot.php

@@ -1,40 +1,36 @@
 <?php
+header('Content-Type: text/html; charset=utf-8');date_default_timezone_set("PRC");define('DEVER_TIME', $_SERVER['REQUEST_TIME']);define('DEVER_PATH', dirname(__FILE__) . DIRECTORY_SEPARATOR);
+Dever::run();
 class Dever
 {
     public static $data = array();
-    private static $define = array();
-    public static $string = 'Dever\\String\\Helper';
-    public static $date = 'Dever\\Support\\Date';
-    public static $env = 'Dever\\String\\Env';
-    public static $path = 'Dever\\Path';
-    public static $page = 'Dever\\Paginator';
     public static function run()
     {
+        spl_autoload_register(array('Dever', 'loadClass'));
         $route = Dever\Route::get();
         Dever\Debug::init();
         Dever\Project::register();
-        Dever\Output::success(self::load($route['l'], DEVER_APP_NAME, 'api'));
-    }
-    public static function __callStatic($name, $param = array())
-    {
-        if (isset(self::$define[$name])) {
-            if (is_array(self::$define[$name])) {
-                $class = self::$define[$name][0];
-                $method = self::$define[$name][1];
-            } else {
-                 $class = self::$define[$name];
-                 $method = $name;
-            }
-            if (is_object($class)) {
-                return $class->$method(...$param);
-            } else {
-                return $class::$method(...$param);
+        if (isset(self::config('setting')['cache'])) {
+            $index = DEVER_APP_NAME . DIRECTORY_SEPARATOR . $route['l'];
+            if (isset(self::config('setting')['cache'][$index])) {
+                $expire = self::config('setting')['cache'][$index];
+                if (isset($route['shell'])) {
+                    unset($route['shell']);
+                }
+                $key = md5(DEVER_APP_NAME . http_build_query($route));
+                if ($result = self::cache($key)) {
+                    return Dever\Output::success($result);
+                }
             }
         }
+        $result = Dever\Output::success(self::load($route['l'], DEVER_APP_NAME, 'api'));
+        if (isset($expire)) {
+            self::cache($key, $result, $expire);
+        }
     }
-    public static function reg($method, $function)
+    public static function loadClass($class)
     {
-        self::$define[$method] = $function;
+        include DEVER_PATH . 'src/' . str_replace('\\', '/', $class) . '.php';
     }
     public static function load($class, $app = '', $path = 'lib')
     {
@@ -94,18 +90,41 @@ class Dever
     {
         return Dever\Log::add(...func_get_args());
     }
-    public static function lang()
+    public static function debug()
     {
-        return Dever\Lang::get(...func_get_args());
-    }
-    public static function rule()
-    {
-        return Dever\String\Regular::rule(...func_get_args());
+        return Dever\Debug::add(...func_get_args());
     }
     public static function session()
     {
         return Dever\Session::oper(...func_get_args());
     }
+    public static function view()
+    {
+        return Dever\View::show(...func_get_args());
+    }
+    public static function path()
+    {
+        return Dever\Path::get(...func_get_args());
+    }
+    public static function curl()
+    {
+        $curl = new Dever\Helper\Curl();
+        return $curl->log(true)->load(...func_get_args());
+    }
+    public static function cache($key, $value = false)
+    {
+        if (isset(self::config('setting')['redis'])) {
+            if ($value) {
+                if ($value == 'delete') {
+                    return \Dever\Helper\Redis::delete($key);
+                }
+                return \Dever\Helper\Redis::set($key, self::json_encode($value));
+            } else {
+                return self::json_decode(\Dever\Helper\Redis::get($key));
+            }
+        }
+        return false;
+    }
     public static function shell($value)
     {
         return Dever::check(Dever\Route::input('shell'), $value);
@@ -150,4 +169,16 @@ class Dever
         }
         return sprintf("%.".$num."f", $number);
     }
+    public static function uuid()
+    {
+        mt_srand((double)microtime() * 10000);
+        $charid = strtoupper(self::id());
+        $hyphen = chr(45);
+        return chr(123).substr($charid, 0, 8).$hyphen.substr($charid, 8, 4).$hyphen.substr($charid,12, 4).$hyphen.substr($charid,16, 4).$hyphen.substr($charid,20,12).chr(125);
+    }
+    public static function id()
+    {
+        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
+        return substr($charid, 0, 8) . substr($charid, 8, 4) . substr($charid, 12, 4) . substr($charid, 16, 4) . substr($charid, 20, 12);
+    }
 }

+ 0 - 25
composer.json

@@ -1,25 +0,0 @@
-{
-    "name": "dever-main/framework",
-    "type": "framework",
-    "description": "dever framework",
-    "keywords": ["framework","library"],
-    "homepage": "https://github.com/dever-main/framework",
-    "license": "MIT",
-    "authors": [
-        {
-            "name": "Rabin",
-            "email": "2934170@qq.com"
-        }
-    ],
-    "require": {
-        "php": ">=5.0.0"
-    },
-    "autoload": {
-        "files": [
-            "dever.php"
-        ],
-        "psr-4": {
-            "Dever\\": "src/Dever/"
-        }
-    }
-}

+ 0 - 0
config/README.md


+ 22 - 0
config/env/localhost.php

@@ -0,0 +1,22 @@
+<?php
+return array
+(
+    'db' => array
+    (
+        'type' => 'Pdo',
+        'host' => 'web-mysql',
+        'port' => '3306',
+        'name' => 'dever2test',
+        'user' => 'root',
+        'pwd' => '123456',
+    ),
+    'db1' => array
+    (
+        'type' => 'Pdo',
+        'host' => 'web-mysql',
+        'port' => '3306',
+        'name' => 'dever2test2',
+        'user' => 'root',
+        'pwd' => '123456',
+    ),
+);

+ 62 - 0
config/html/default.html

@@ -0,0 +1,62 @@
+
+<!DOCTYPE html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
+<title>无法打开页面-Dever</title>
+
+<style type="text/css">
+body,code,dd,div,dl,dt,fieldset,form,h1,h2,h3,h4,h5,h6,input,legend,li,ol,p,pre,td,textarea,th,ul{margin:0;padding:0}
+body{font:14px/1.5 'Microsoft YaHei','微软雅黑',Helvetica,Sans-serif;min-width:1200px;background:#f0f1f3;}
+:focus{outline:0}
+h1,h2,h3,h4,h5,h6,strong{font-weight:700}
+a{color:#428bca;text-decoration:none}
+a:hover{text-decoration:underline}
+.error-page{background:#f0f1f3;padding:80px 0 180px}
+.error-page-container{position:relative;z-index:1}
+.error-page-main{position:relative;background:#f9f9f9;margin:0 auto;width:617px;-ms-box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:50px 50px 70px}
+.error-page-main:before{content:'';display:block;height:7px;position:absolute;top:-7px;width:100%;left:0}
+.error-page-main h3{font-size:24px;font-weight:400;border-bottom:1px solid #d0d0d0}
+.error-page-main h3 strong{font-size:54px;font-weight:400;margin-right:20px}
+.error-page-main h4{font-size:20px;font-weight:400;color:#333}
+.error-page-actions{font-size:0;z-index:100}
+.error-page-actions div{font-size:14px;display:inline-block;padding:30px 0 0 10px;width:50%;-ms-box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;color:#838383}
+.error-page-actions ol{list-style:decimal;padding-left:20px}
+.error-page-actions li{line-height:2.5em}
+.error-page-actions:before{content:'';display:block;position:absolute;z-index:-1;bottom:17px;left:50px;width:200px;height:10px;-moz-box-shadow:4px 5px 31px 11px #999;-webkit-box-shadow:4px 5px 31px 11px #999;box-shadow:4px 5px 31px 11px #999;-moz-transform:rotate(-4deg);-webkit-transform:rotate(-4deg);-ms-transform:rotate(-4deg);-o-transform:rotate(-4deg);transform:rotate(-4deg)}
+.error-page-actions:after{content:'';display:block;position:absolute;z-index:-1;bottom:17px;right:50px;width:200px;height:10px;-moz-box-shadow:4px 5px 31px 11px #999;-webkit-box-shadow:4px 5px 31px 11px #999;box-shadow:4px 5px 31px 11px #999;-moz-transform:rotate(4deg);-webkit-transform:rotate(4deg);-ms-transform:rotate(4deg);-o-transform:rotate(4deg);transform:rotate(4deg)}
+</style>
+
+</head>
+<body>
+
+<div class="error-page">
+    <div class="error-page-container">
+        <div class="error-page-main">
+            <h3>
+                <strong><?php echo $name?></strong><a href="javascript:;" title=<?php echo $html?>>无法打开页面</a>
+            </h3>
+            <div class="error-page-actions">
+                <div>
+                    <h4>可能原因:</h4>
+                    <ol>
+                        <li>网络信号差</li>
+                        <li>找不到请求的页面</li>
+                        <li>输入的网址不正确</li>
+                    </ol>
+                </div>
+                <div>
+                    <h4>可以尝试:</h4>
+                    <ul>
+                        <li><a href="<?php echo $host?>">返回首页</a></li>
+                        <li><a href="javascript:history.back(-1)">返回上一页</a></li>
+                        <li><a href="http://www.dever.cc/" target="_blank">到官网提出您的问题</a></li>
+                    </ul>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>
+
+</body>
+</html>

+ 29 - 0
config/lang/en.php

@@ -0,0 +1,29 @@
+<?php
+
+return array
+(
+	'error page' => 'Unable to open page',
+	'request tainting' => 'request_tainting',
+
+	'project not exists' => 'Project "{0}" does not exist',
+	'app not exists' => 'DeverApp {0} does not exist',
+	'route not exists' => 'Route does not exist',
+	'dom not exists' => 'DOM "{0}" does not exist',
+	'file not exists' => 'File "{0}" does not exist',
+	'class not exists' => 'Object "{0}" does not exist',
+	'path not exists' => 'Path "{0}" does not exist',
+	'method not exists' => 'Method {1} in {0} does not exist',
+
+	# api
+	'api not exists' => 'API "{0}" does not exist',
+	'api key not exists' => 'Configuration {0} in API does not exist',
+	'api param not exists' => 'Parameter does not exist',
+	'api signature not exists' => 'Signature verification error',
+	'api signature not repeat' => 'Please do not submit repeatedly',
+
+	# 数据库
+	'database not exists' => 'Database {0} does not exist',
+	'database config not exists' => 'Database configuration "{0}" does not exist',
+	'database error' => 'The parameter {0} is empty or does not match the rule:{1}',
+	'database maxlen' => '[{0}] cannot be longer than {1} characters',
+);

+ 28 - 0
config/lang/zh-cn.php

@@ -0,0 +1,28 @@
+<?php
+return array
+(
+	'error page' => '无法打开页面',
+	'request tainting' => 'request_tainting',
+
+	'project not exists' => '项目"{0}"不存在',
+	'app not exists' => '应用"{0}"不存在',
+	'route not exists' => '路由"{0}"不存在',
+	'dom not exists' => 'dom"{0}"不存在',
+	'file not exists' => '文件"{0}"不存在',
+	'class not exists' => '对象"{0}"不存在',
+	'path not exists' => '目录"{0}"不存在',
+	'method not exists' => '{0}中的方法{1}不存在',
+
+	# api
+	'api not exists' => 'api"{0}"不存在',
+	'api key not exists' => 'api中的配置{0}不存在',
+	'api param not exists' => 'api参数不存在',
+	'api signature not exists' => 'signature校验错误',
+	'api signature not repeat' => '请不要重复提交',
+
+	# 数据库
+	'database not exists' => '数据库{0}不存在',
+	'database config not exists' => '数据库配置{0}不存在',
+	'database error' => '参数{0}为空,或者不匹配该规则:{1}',
+	'database maxlen' => '[{0}]的长度不能超过{1}位字符',
+);

+ 31 - 0
config/setting.php

@@ -0,0 +1,31 @@
+<?php
+return array
+(
+    'token' => 'dever',
+    'lang' => 'zh-cn',
+    'lang_pack' => array('zh-cn' => '简体中文', 'en' => '英文'),
+    'route' => false,
+    'log' => array('type' => 'file', 'host' => 'host', 'port' => 'port'),
+    'shell' => 'debug',
+    //'session' => array('host' => '', 'port' => '', 'path' => '', 'cookie' => ''),
+    'database' => array
+    (
+        'opt' => true,
+        //'default' => array($env['db'], $env['db1'], 'type' => 'Pdo'),
+        'default' => $env['db'],
+        'db1' => $env['db1'],
+
+        # 分区设置
+        'partition' => array
+        (
+            # 类型:database 按照库拆分 table 按照表拆分 field 按照字段拆分 Dever::session('database', 1)可是设置值
+            'database' => 'date("Y")',
+            'table' => 'date("Ym")',
+            # 字段类型需要定义相对应的字段
+            //'field' => 'date("Y-m-d 23:60:60", strtotime("-1 day"))',
+            'field' => 'date("Y-m-d 23:60:60")',
+        ),
+    ),
+
+    # 模板配置
+);

+ 92 - 0
config/web/plant.nginx.conf

@@ -0,0 +1,92 @@
+server {
+    server_name yubin.bid www.yubin.bid manage.yubin.bid forum.yubin.bid passport.yubin.bid upload.yubin.bid;
+
+    listen 80;
+
+    autoindex on;
+
+    set $charset utf-8;
+
+    charset $charset;
+
+    set $rootdir /data/web/yubin.bid/web/application/plant;
+    set $project www;
+
+    if ( $host ~* "^([^\.]+)\.yubin\.bid" ) {
+        set $project $1;
+    }
+
+    if ( $project ~* www ) {
+        set $project main;
+    }
+
+    set $rewrite yes;
+
+    if ( $request_uri ~* (assets\/|crossdomain\.xml) ) {
+        set $rewrite no;
+        set $rootdir /data/web/yubin.bid/web/package;
+    }
+
+    set $rootdir $rootdir/$project;
+    root $rootdir;
+    index index.php index.html;
+
+
+    if ($rewrite ~* yes) {
+        rewrite ^/(.*) /index.php/$1 last;
+    }
+
+    location ~ /(assets\/|crossdomain\.xml)
+    {
+        try_files $uri $uri/ /index.html;
+    }
+
+
+    location / {
+        fastcgi_split_path_info ^(.+\.php)(/.+)$;
+        # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
+
+        # With php5-cgi alone:
+        #fastcgi_pass 127.0.0.1:9000;
+        # With php5-fpm:
+        fastcgi_pass unix:/var/run/php5-fpm.sock;
+        fastcgi_index index.php;
+        include fastcgi_params;
+    }
+}
+
+
+server {
+    server_name file.yubin.bid assets.yubin.bid;
+
+    listen 80;
+
+    autoindex on;
+
+    set $charset utf-8;
+
+    charset $charset;
+
+    set $rootdir /data/web/yubin.bid/web/data;
+    set $project upload;
+
+    if ( $host ~* "^([^\.]+)\.yubin\.bid" ) {
+        set $project $1;
+    }
+
+    if ( $project ~* file ) {
+        set $project upload;
+    }
+
+    set $rootdir $rootdir/$project;
+    root $rootdir;
+    index index.html;
+    location / {
+                # First attempt to serve request as file, then
+                # as directory, then fall back to displaying a 404.
+                try_files $uri $uri/ =404;
+                # Uncomment to enable naxsi on this location
+                # include /etc/nginx/naxsi.rules
+    }
+
+}

+ 404 - 0
dever

@@ -0,0 +1,404 @@
+#!/usr/bin/env php
+<?php
+define('PATH', dirname(__FILE__) . DIRECTORY_SEPARATOR);
+class Dever
+{
+    protected static $package = 'http://dever.shemic.com/';
+    protected static $command = array();
+    protected static $check = false;
+
+    public static function handle()
+    {
+        global $argc, $argv;
+
+        if (isset($argv) && isset($argv[1])) {
+            self::out('loading...');
+            $method = 'method_' . $argv[1];
+            if (!method_exists(__CLASS__, $method)) {
+                self::error();
+            }
+            if (isset($argv[3])) {
+                unset($argv[0]);
+                unset($argv[1]);
+                $name = $argv[2];
+                unset($argv[2]);
+                self::$method($name, $argv);
+            } elseif (isset($argv[2])) {
+                self::$method($argv[2]);
+            } else {
+                self::$method();
+            }
+
+            self::exe();
+        } else {
+            self::error();
+        }
+    }
+
+    protected static function input($text, $default = '')
+    {
+        if (is_array($text)) {
+            $text = implode("\n", $text);
+        }
+
+        self::out($text);
+
+        $stdin = fopen('php://stdin', 'r');
+        $shell = trim(fgets($stdin, 100));
+
+        return $shell ? $shell : $default;
+    }
+
+    protected static function out($text)
+    {
+        echo $text . "\n";
+    }
+
+    protected static function error()
+    {
+        self::out('error');
+        die;
+    }
+
+    protected static function notice()
+    {
+        self::out('您的php不支持system,请联系空间商或管理员开启system。');
+        die;
+    }
+
+    public static function command($command)
+    {
+        array_push(self::$command, $command);
+    }
+
+    public static function exe()
+    {
+        if (!self::check()) {
+            self::notice();
+        }
+
+        if (self::$command) {
+            system(implode(' && ', self::$command));
+        }
+        echo "Finished!\n";
+    }
+
+    protected static function check()
+    {
+        if (self::$check) {
+            return true;
+        }
+        if (!function_exists('system')) {
+            return false;
+        }
+
+        return true;
+    }
+
+    protected static function method_init($type = 'main')
+    {
+        self::command('sudo cp -R dever /usr/bin/dever');
+        self::command('sudo chmod +x /usr/bin/dever');
+        if ($type == 'composer') {
+            //$HOME
+            $composer = '/usr/bin/composer';
+            //$shell = 'sudo curl -sS http://packagist.cn/composer/installer | sudo php -d detect_unicode=Off';
+            self::command('sudo curl http://getcomposer.org/installer | sudo php -d detect_unicode=Off');
+            self::command('sudo mv composer.phar ' . $composer);
+            self::command('sudo chmod +x ' . $composer);
+            self::command('composer install --optimize-autoloader');
+        } else {
+            self::method_install('init');
+        }
+    }
+
+    protected static function method_up($type = 'main')
+    {
+        if ($type == 'composer') {
+            self::command('composer update --optimize-autoloader');
+        } else {
+            self::method_install('init');
+        }
+    }
+
+    protected static function method_opt()
+    {
+        self::command('composer dump-autoload --optimize');
+    }
+
+    protected static function method_git()
+    {
+        self::command('sudo apt-get install git-core');
+    }
+
+    protected static function method_pack($name, $path = '')
+    {
+        if ($name == 'init') {
+            $path = array
+                (
+                'build/',
+                'config/',
+                'boot.php',
+                'web/data/assets/index.html',
+                'web/data/cache/index.html',
+                'web/data/compile/index.html',
+                'web/data/database/index.html',
+                'web/data/manage/index.html',
+                'web/data/node/index.html',
+                'web/data/project/index.html',
+                'web/data/sql/index.html',
+                'web/data/upload/index.html',
+                'web/data/index.html',
+                'web/package/boot.php',
+                'web/package/index.html',
+                'web/application/boot.php',
+                'web/application/index.html',
+            );
+            $path = implode(' ', $path);
+        } else {
+            if (!$path) {
+                $path = $name;
+            }
+
+            if (is_array($path)) {
+                $method = 1;
+                if (isset($path[3]) && $path[3] == '-p') {
+                    unset($path[3]);
+                    $method = 2;
+                }
+
+                $temp = $path;
+                $path = '';
+                foreach ($temp as $k => $v) {
+                    if ($method == 2) {
+                        $n = explode('/', $v);
+                        $m = count($n) - 2;
+                        $n = $n[$m];
+
+                        if (!is_dir(PATH . 'web/data/assets/' . $n)) {
+                            $n = 'default';
+                        }
+
+                        $template = $v . 'template';
+
+                        if (!is_dir(PATH . $template)) {
+                            $template = $v . 'main/template';
+                        }
+
+                        $e = ' web/data/assets/' . $n . ' web/data/compile/' . $n . ' --exclude=' . $template;
+                    } else {
+                        $e = ' --exclude=' . $v . 'template';
+                    }
+
+                    $path .= ' ' . $v . $e;
+                }
+            }
+        }
+
+        self::command('tar -czf install/' . $name . '.tar.gz ' . $path . ' --exclude-vcs');
+    }
+
+    protected static function method_init_laravel()
+    {
+        self::command('composer create-project laravel/laravel --prefer-dist');
+    }
+
+    protected static function method_create()
+    {
+        self::method_install('create');
+    }
+
+    protected static function method_mysql()
+    {
+        $text = array
+            (
+            '请输入命令以执行相应操作:'
+            , 'backup:备份mysql'
+            , 'restore:恢复mysql'
+            , '请在输入命令之后按回车键',
+
+        );
+
+        $shell = self::input($text);
+
+        switch ($shell) {
+            case 'backup':
+                Mysql::backup();
+                break;
+            case 'restore':
+                Mysql::restore();
+                break;
+            default:
+                echo "未定义的方法";
+                break;
+        }
+    }
+
+    protected static function method_install($value)
+    {
+        $value .= '.tar.gz';
+        if (self::check()) {
+            self::command('wget -c ' . self::$package . $value);
+            self::command('tar -zxvf ' . $value);
+            self::command('rm -rf ' . $value);
+
+            if ($value == 'composer') {
+                self::method_init($value);
+            }
+        } elseif (class_exists('PharData')) {
+            self::$check = true;
+            $path = dirname(__FILE__) . '/';
+            file_put_contents($path . $value, file_get_contents(self::$package . $value));
+            $phar = new PharData($value);
+            $phar->extractTo($path, null, true);
+            unlink($path . $value);
+        } else {
+            self::notice();
+        }
+    }
+
+    private static function copy($src, $dst, $path)
+    {
+        if (function_exists('system')) {
+            system('cp -R ' . $src . ' ' . $dst);
+        } else {
+            $path = str_replace(array('/', '..'), '', $path);
+            $dst = $dst . $path;
+
+            if (!is_dir($dst)) {
+                mkdir($dst);
+            }
+
+            $dir = opendir($src);
+
+            while (false !== ($file = readdir($dir))) {
+                if (($file != '.') && ($file != '..')) {
+                    if (is_dir($src . '/' . $file)) {
+                        $this->copyDir($src . '/' . $file, $dst . '/' . $file);
+                    } else {
+                        copy($src . '/' . $file, $dst . '/' . $file);
+                    }
+                }
+            }
+            closedir($dir);
+        }
+    }
+
+    protected static function method_build($path = 'vendor')
+    {
+        //$exts = ['php','js','css','html'];
+        $exts = array('php', 'js', 'css', 'html');
+        $dir = dirname(__FILE__) . '/build/';
+
+        $path && system('cp -R ' . $path . ' ' . $dir);
+
+        $file = 'dever.phar';
+
+        $phar = new Phar($dir . $file, FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME, $file);
+
+        $phar->startBuffering();
+
+        if ($path) {
+            foreach ($exts as $ext) {
+                $phar->buildFromDirectory($dir, '/\.' . $ext . '$/');
+            }
+        }
+
+        $index = 'boot.php';
+        $phar->buildFromIterator
+            (
+            new ArrayIterator
+            (
+                array
+                (
+                    $index => $dir . $index,
+                )
+            )
+        );
+        //$phar->delete('build.php');
+        $phar->setStub($phar->createDefaultStub($index, $index));
+        $phar->compressFiles(Phar::GZ);
+        $phar->stopBuffering();
+        //system('cp -R ' . $dir . $file . ' ' . $file);
+        $path && system('rm -rf ' . $dir . $path);
+    }
+}
+
+class Create extends Dever
+{
+
+}
+
+class Mysql extends Dever
+{
+    protected static function common()
+    {
+        $info['host'] = self::input('请输入mysql的主机地址:默认为localhost', 'localhost');
+        $info['username'] = self::input('请输入mysql的账号:默认为root', 'root');
+        $info['password'] = self::input('请输入mysql的密码:默认为空', '');
+        $info['database'] = self::input('请输入mysql的数据库名:');
+
+        if (!$info['host'] || !$info['username'] || !$info['password'] || !$info['database']) {
+            self::out('请输入正确的数据库信息!');die;
+        }
+
+        $info['file'] = PATH . 'web/data/sql/' . $info['database'];
+
+        $info['shell'] = ' -u' . $info['username'] . ' -p' . $info['password'] . ' -h' . $info['host'] . ' ';
+
+        return $info;
+    }
+
+    public static function backup()
+    {
+        $info = self::common();
+
+        $info['table'] = self::input('请输入mysql的表名(不输入则备份整个' . $info['database'] . '数据库):');
+        $info['type'] = self::input('请输入备份类型:1为备份全部,2为备份结构,3为备份数据');
+
+        $info['shell'] = 'mysqldump ' . $info['shell'];
+
+        if ($info['type'] == 2) {
+            $info['shell'] .= ' -d ' . $info['database'];
+        } elseif ($info['type'] == 3) {
+            $info['shell'] .= ' -t ' . $info['database'];
+        } else {
+            $info['shell'] .= ' ' . $info['database'];
+        }
+
+        if ($info['table']) {
+            $info['shell'] .= ' ' . $info['table'];
+            $info['file'] .= '.' . $info['table'];
+        }
+
+        $info['file'] .= '.sql';
+
+        $info['shell'] .= ' > ' . $info['file'];
+
+        self::command($info['shell']);
+
+        self::out('操作成功,输出路径:' . $info['file']);
+    }
+
+    public static function restore()
+    {
+        $info = self::common();
+
+        $info['new'] = self::input('请输入要恢复的全新数据库:为空则使用上边填的数据库', $info['database']);
+
+        $create_table = 'mysqladmin ' . $info['shell'] . ' create ' . $info['new'];
+
+        $info['shell'] = 'mysql ' . $info['shell'] . ' ' . $info['new'];
+
+        $info['file'] .= '.sql';
+
+        $info['shell'] .= ' < ' . $info['file'];
+
+        self::exe($create_table);
+        self::command($info['shell']);
+
+        self::out('操作成功,您已成功恢复' . $info['file'] . '里的数据');
+    }
+}
+
+Dever::handle();

+ 0 - 147
dever_old.php

@@ -1,147 +0,0 @@
-<?php
-class Dever
-{
-    public static $data = array();
-    private static $define = array();
-    public static function run()
-    {
-        if (Dever\Config::get('setting')['debug']) {
-            Dever\Debug::report();
-        }
-        $route = Dever\Route::get();
-        Dever\Project::register();
-        Dever\Output::success(self::load($route['l'], DEVER_APP_NAME, 'api'));
-    }
-    public static function __callStatic($name, $param = array())
-    {
-        if (isset(self::$define[$name])) {
-            if (is_array(self::$define[$name])) {
-                $class = self::$define[$name][0];
-                $method = self::$define[$name][1];
-            } else {
-                 $class = self::$define[$name];
-                 $method = $name;
-            }
-            if (is_object($class)) {
-                return $class->$method(...$param);
-            } else {
-                return $class::$method(...$param);
-            }
-        }
-    }
-    public static function reg($method, $function)
-    {
-        self::$define[$method] = $function;
-    }
-    public static function load($class, $app = '', $path = 'lib')
-    {
-        if (!$app) {
-            $app = DEVER_APP_NAME;
-        }
-        $index = $app . $path . $class;
-        if (empty(Dever\Import::$instance[$index])) {
-            Dever\Import::$instance[$index] = new Dever\Import($class, $app, $path);
-        }
-        return Dever\Import::$instance[$index]->loadDevelop();
-    }
-    public static function config($key, $app = '', $path = 'config')
-    {
-        return Dever\Config::get($key, $app, $path);
-    }
-    public static function apply($file, $app, $path = 'lib')
-    {
-        return Library::get()->apply($file, $app, $path);
-    }
-    public static function success($data, $uuid = false, $code = 0)
-    {
-        return Dever\Output::success($data, $uuid, $code);
-    }
-    public static function error($msg, $param = array(), $code = 1)
-    {
-        return Dever\Output::error($msg, $param, $code);
-    }
-    public static function out($result)
-    {
-        return Dever\Output::out($result);
-    }
-    public static function input($key = false, $lang = '', $condition = '', $value = '')
-    {
-        return Dever\Route::input($key, $lang, $condition, $value);
-    }
-    public static function url($uri = false, $param = array())
-    {
-        return Dever\Route::url($uri, $param);
-    }
-    public static function project($app)
-    {
-        return Dever\Project::load($app);
-    }
-    public static function log($msg, $type = 1)
-    {
-        return Dever\Log::add($msg, $type);
-    }
-    public static function lang($key = 'host', $param = array())
-    {
-        return Dever\Lang::get($key, $param);
-    }
-    public static function rule($method, $fix = '/', $rule = '')
-    {
-        return Dever\String\Regular::rule($method, $fix, $rule);
-    }
-    public static function session($key, $value = false, $timeout = 3600, $type = 'cookie', $encode = true)
-    {
-        return Dever\Session::oper($key, $value, $timeout, $type, $encode);
-    }
-    public static function string()
-    {
-        return Dever\String\Helper;
-    }
-    public static function env()
-    {
-        return Dever\String\Env;
-    }
-    public static function path()
-    {
-        return Dever\Path;
-    }
-    public static function check($var, $find)
-    {
-        if (is_array($var)) {
-            $var = implode(',', $var);
-        }
-        $var = ',' . $var . ',';
-        $find = ',' . $find . ',';
-        return strpos($var, $find) !== false;
-    }
-    public static function json_encode($value)
-    {
-        $value = json_encode($value, JSON_UNESCAPED_UNICODE + JSON_FORCE_OBJECT);
-        return $value;
-    }
-    public static function json_decode($value)
-    {
-        return json_decode($value, true);
-    }
-    public static function array_order($array, $key, $sort)
-    {
-        $reorder = array_column($array, $key);
-        array_multisort($reorder, $sort, $array);
-        return $array;
-    }
-    public static function number($number, $num = 2, $type = 1)
-    {
-        if (is_array($number)) {
-            foreach ($number[0] as $k => $v) {
-                $number[1][$v] = self::number($number[1][$v], $num, $type);
-            }
-            return $number[1];
-        }
-        if ($type == 2) {
-            return number_format($number, $num);
-        }
-        if ($type == 3) {
-            return round($number, $num);
-        }
-        return sprintf("%.".$num."f", $number);
-    }
-}

+ 0 - 0
package/README.md


+ 541 - 0
src/Ares333/Curl.php

@@ -0,0 +1,541 @@
+<?php /** @noinspection PhpUnused */
+
+namespace Ares333\Curl;
+
+/**
+ * The best curl-multi library.
+ *
+ * @author Ares
+ */
+class Curl
+{
+
+    public $maxThread = 10;
+
+    // Max try times on curl error
+    public $maxTry = 0;
+
+    // Global CURLOPT_*
+    public $opt = array();
+
+    // Global config.
+    public $cache = array(
+        'enable' => false,
+        /**
+         * The level of compression.
+         * Can be given as 0 for no compression up to 9 for maximum compression.
+         * 6 is a good choice.
+         */
+        'compress' => 0,
+        'dir' => null,
+        'expire' => 86400,
+        // Different post data different cache file when enabled.
+        'verifyPost' => false
+    );
+
+    // stack or queue
+    public $taskPoolType = 'queue';
+
+    // Emitted when new tasks are needed.
+    public $onTask;
+
+    // Emitted on IO event.At least 1 second interval.
+    public $onInfo;
+
+    // Emitted on curl error.
+    public $onFail;
+
+    // Emitted on IO event.
+    public $onEvent;
+
+    protected $_mh;
+
+    protected $_taskPool = array();
+
+    // Task pool with higher priority.
+    protected $_taskPoolAhead = array();
+
+    protected $_taskRunning = array();
+
+    // Failed tasks retrying.
+    protected $_taskFailed = array();
+
+    protected $_stop = false;
+
+    // Running info.
+    protected $_info = array(
+        'all' => array(
+            'downloadSpeed' => 0,
+            'bodySize' => 0,
+            'headerSize' => 0,
+            // Active requests count
+            'activeNum' => 0,
+            // Finished requests count on the queue
+            'queueNum' => 0,
+            // Finished tasks count including failed tasks and tasks using cache.
+            'finishNum' => 0,
+            // Cache used count
+            'cacheNum' => 0,
+            // Count of tasks failed after retry
+            'failNum' => 0,
+            // Count of tasks added to the poll
+            'taskNum' => 0,
+            // $this->taskRunning count.taskRunning >= active + queue
+            'taskRunningNum' => 0,
+            // $this->taskPool count
+            'taskPoolNum' => 0,
+            // $this->taskFail count
+            'taskFailNum' => 0
+        ),
+        'running' => array()
+    );
+
+    protected $_onInfoLastTime = 0;
+
+    protected $_downloadSpeedStartTime;
+
+    protected $_downloadSpeedTotalSize = 0;
+
+    protected $_downloadSpeedList = array();
+
+    /**
+     * Add a task to the taskPool
+     *
+     * @param array $item
+     *            array $item[opt] CURLOPT_* for current task
+     *            mixed $item[args] Args for callbacks
+     *            array $item[cache]
+     * @param mixed $onSuccess
+     *            Callback for response
+     * @param mixed $onFail
+     *            Callback for curl error
+     * @param bool $ahead
+     * @return self
+     */
+    public function add(array $item, $onSuccess = null, $onFail = null, $ahead = null)
+    {
+        if (! isset($ahead)) {
+            $ahead = false;
+        }
+        if (! isset($item['opt'])) {
+            $item['opt'] = array();
+        }
+        if (! isset($item['args'])) {
+            $item['args'] = null;
+        }
+        if (! isset($item['cache'])) {
+            $item['cache'] = array();
+        }
+        if (! isset($item['opt'][CURLOPT_URL])) {
+            $item['opt'][CURLOPT_URL] = '';
+        }
+        $item['opt'][CURLOPT_URL] = trim($item['opt'][CURLOPT_URL]);
+        // replace space with + to avoid some curl problems
+        $item['opt'][CURLOPT_URL] = str_replace(' ', '+', $item['opt'][CURLOPT_URL]);
+        $parse = parse_url($item['opt'][CURLOPT_URL]);
+        $keys = array(
+            'scheme',
+            'host',
+            'port',
+            'user',
+            'pass',
+            'path',
+            'query',
+            'fragment'
+        );
+        foreach ($keys as $v) {
+            if (! isset($parse[$v])) {
+                $parse[$v] = '';
+            }
+        }
+        if ('' !== $parse['user']) {
+            $parse['user'] .= ':';
+            $parse['pass'] .= '@';
+        }
+        if ('' !== $parse['port']) {
+            $parse['host'] .= ':';
+        }
+        if ('' !== $parse['query']) {
+            $parse['path'] .= '?';
+        }
+        $parse['path'] = preg_replace('/\/+/', '/', $parse['path']);
+        strtolower($parse['scheme']);
+        strtolower($parse['host']);
+        $item['opt'][CURLOPT_URL] = $parse['scheme'] . '://' . $parse['user'] . $parse['pass'] . $parse['host'] .
+            $parse['port'] . $parse['path'] . $parse['query'];
+        $task = array();
+        $task['args'] = $item['args'];
+        $task['opt'] = $item['opt'];
+        $task['cache'] = $item['cache'];
+        $task['onSuccess'] = $onSuccess;
+        $task['onFail'] = $onFail;
+        $task['tried'] = 0;
+        $task['ch'] = null;
+        // $task['fileMeta'] is used for download cache and __wakeup
+        if (isset($task['opt'][CURLOPT_FILE])) {
+            $task['fileMeta'] = stream_get_meta_data($task['opt'][CURLOPT_FILE]);
+        } else {
+            $task['fileMeta'] = array();
+        }
+        // add
+        if (true == $ahead) {
+            $this->_taskPoolAhead[] = $task;
+        } else {
+            $this->_taskPool[] = $task;
+        }
+        $this->_info['all']['taskNum'] ++;
+        return $this;
+    }
+
+    /**
+     *
+     * @return array[] tasks
+     */
+    public function stop()
+    {
+        $this->_stop = true;
+        $tasks = array();
+        foreach (array(
+            '_taskPoolAhead',
+            '_taskRunning',
+            '_taskPool'
+        ) as $v) {
+            foreach ($this->$v as $k1 => $v1) {
+                if (isset($v1['opt'][CURLOPT_FILE]) && is_resource($v1['opt'][CURLOPT_FILE])) {
+                    fclose($v1['opt'][CURLOPT_FILE]);
+                    if (is_file($v1['fileMeta']['uri'])) {
+                        unlink($v1['fileMeta']['uri']);
+                    }
+                }
+                if (is_resource($v1['ch'])) {
+                    curl_multi_remove_handle($this->_mh, $v1['ch']);
+                    curl_close($v1['ch']);
+                }
+                unset($this->{$v}[$k1]);
+                $tasks[] = $v1;
+            }
+        }
+        $this->_downloadSpeedStartTime = null;
+        $this->_onInfoLastTime = 0;
+        $this->_downloadSpeedTotalSize = 0;
+        $this->_downloadSpeedList = array();
+        $this->_info['all']['downloadSpeed'] = 0;
+        $this->_info['all']['activeNum'] = 0;
+        $this->_info['all']['queueNum'] = 0;
+        return $tasks;
+    }
+
+    public function start()
+    {
+        $this->_stop = false;
+        $this->_mh = curl_multi_init();
+        $this->runTask();
+        do {
+            $this->exec();
+            $this->onInfo();
+            curl_multi_select($this->_mh);
+            if (isset($this->onEvent)) {
+                call_user_func($this->onEvent, $this);
+            }
+            if ($this->_stop) {
+                break;
+            }
+            while (false != ($curlInfo = curl_multi_info_read($this->_mh, $this->_info['all']['queueNum']))) {
+                $ch = $curlInfo['handle'];
+                $task = $this->_taskRunning[(int) $ch];
+                $info = curl_getinfo($ch);
+                $this->_info['all']['bodySize'] += $info['size_download'];
+                $this->_info['all']['headerSize'] += $info['header_size'];
+                $param = array();
+                $param['info'] = $info;
+                $param['curl'] = $this;
+                if ($curlInfo['result'] == CURLE_OK) {
+                    if (! isset($task['opt'][CURLOPT_FILE])) {
+                        $param['body'] = curl_multi_getcontent($ch);
+                        if (isset($task['opt'][CURLOPT_HEADER])) {
+                            $param = array_merge($param, $this->parseResponse($param['body']));
+                        }
+                    }
+                }
+                $curlError = curl_error($ch);
+                curl_multi_remove_handle($this->_mh, $ch);
+                curl_close($ch);
+                if (isset($task['opt'][CURLOPT_FILE])) {
+                    fclose($task['opt'][CURLOPT_FILE]);
+                }
+                if ($curlInfo['result'] == CURLE_OK) {
+                    $this->onProcess($task, $param);
+                }
+                // Handle error
+                if ($curlInfo['result'] !== CURLE_OK) {
+                    if ($task['tried'] >= $this->maxTry) {
+                        $param['errorCode'] = $curlInfo['result'];
+                        $param['errorMsg'] = $curlError;
+                        if (isset($task['onFail'])) {
+                            call_user_func($task['onFail'], $param, $task['args']);
+                        } elseif (isset($this->onFail)) {
+                            call_user_func($this->onFail, $param, $task['args']);
+                        } else {
+                            user_error("Curl error($curlInfo[result]) $info[url]", E_USER_WARNING);
+                        }
+                        $this->_info['all']['failNum'] ++;
+                    } else {
+                        $task['tried'] ++;
+                        $this->_taskFailed[] = $task;
+                        $this->_info['all']['taskNum'] ++;
+                    }
+                }
+                unset($this->_taskRunning[(int) $ch]);
+                $this->_info['all']['finishNum'] ++;
+                $this->_downloadSpeedTotalSize += $info['size_download'] + $info['header_size'];
+                $this->runTask();
+                $this->exec();
+                $this->onInfo();
+                if (isset($this->onEvent)) {
+                    call_user_func($this->onEvent, $this);
+                }
+                if ($this->_stop) {
+                    break 2;
+                }
+            }
+        } while ($this->_info['all']['activeNum'] || $this->_info['all']['queueNum'] || ! empty($this->_taskFailed) ||
+            ! empty($this->_taskRunning) || ! empty($this->_taskPool));
+        $this->onInfo(true);
+        curl_multi_close($this->_mh);
+        $this->_mh = null;
+    }
+
+    public function parseResponse($response)
+    {
+        $res = array();
+        preg_match_all("/HTTP\/.+(?=\r\n\r\n)/Usm", $response, $res['header']);
+        $res['header'] = $res['header'][0];
+        $pos = 0;
+        foreach ($res['header'] as $v) {
+            $pos += strlen($v) + 4;
+        }
+        $res['body'] = substr($response, $pos);
+        return $res;
+    }
+
+    /**
+     * Call $this->onInfo
+     *
+     * @param bool $isLast
+     *            Is last output?
+     */
+    protected function onInfo($isLast = false)
+    {
+        $now = time();
+        if (! isset($this->_downloadSpeedStartTime)) {
+            $this->_downloadSpeedStartTime = $now;
+        }
+        if (($isLast || $now - $this->_onInfoLastTime > 0) && isset($this->onInfo)) {
+            $this->_info['all']['taskPoolNum'] = count($this->_taskPool);
+            $this->_info['all']['taskPoolNum'] += count($this->_taskPoolAhead);
+            $this->_info['all']['taskRunningNum'] = count($this->_taskRunning);
+            $this->_info['all']['taskFailNum'] = count($this->_taskFailed);
+            // running
+            $this->_info['running'] = array();
+            foreach ($this->_taskRunning as $k => $v) {
+                $this->_info['running'][$k] = curl_getinfo($v['ch']);
+            }
+            if ($now - $this->_downloadSpeedStartTime > 0) {
+                if (count($this->_downloadSpeedList) > 10) {
+                    array_shift($this->_downloadSpeedList);
+                }
+                $this->_downloadSpeedList[] = round(
+                    $this->_downloadSpeedTotalSize / ($now - $this->_downloadSpeedStartTime));
+                $this->_info['all']['downloadSpeed'] = round(
+                    array_sum($this->_downloadSpeedList) / count($this->_downloadSpeedList));
+            }
+            if ($now - $this->_downloadSpeedStartTime > 3) {
+                $this->_downloadSpeedTotalSize = 0;
+                $this->_downloadSpeedStartTime = $now;
+            }
+            call_user_func($this->onInfo, $this->_info, $this, $isLast);
+            $this->_onInfoLastTime = $now;
+        }
+    }
+
+    protected function exec()
+    {
+        while (curl_multi_exec($this->_mh, $this->_info['all']['activeNum']) === CURLM_CALL_MULTI_PERFORM) {
+            continue;
+        }
+    }
+
+    protected function runTask()
+    {
+        $c = $this->maxThread - count($this->_taskRunning);
+        while ($c > 0) {
+            $task = null;
+            // search failed first
+            if (! empty($this->_taskFailed)) {
+                $task = array_pop($this->_taskFailed);
+            } else {
+                // onTask
+                if (empty($this->_taskPool) && empty($this->_taskPoolAhead) && isset($this->onTask)) {
+                    call_user_func($this->onTask, $this);
+                }
+                if (! empty($this->_taskPoolAhead)) {
+                    $task = array_shift($this->_taskPoolAhead);
+                } elseif (! empty($this->_taskPool)) {
+                    if ($this->taskPoolType == 'stack') {
+                        $task = array_pop($this->_taskPool);
+                    } else {
+                        $task = array_shift($this->_taskPool);
+                    }
+                }
+            }
+            $cache = null;
+            if (isset($task)) {
+                $cache = $this->cache($task);
+                if (null !== $cache) {
+                    // download task
+                    if (isset($task['opt'][CURLOPT_FILE])) {
+                        if (flock($task['opt'][CURLOPT_FILE], LOCK_EX)) {
+                            fwrite($task['opt'][CURLOPT_FILE], $cache['body']);
+                            flock($task['opt'][CURLOPT_FILE], LOCK_UN);
+                        }
+                        fclose($task['opt'][CURLOPT_FILE]);
+                        unset($cache['body']);
+                    }
+                    $cache['curl'] = $this;
+                    $this->onProcess($task, $cache);
+                    $this->_info['all']['cacheNum'] ++;
+                    $this->_info['all']['finishNum'] ++;
+                    $this->onInfo();
+                    if (isset($this->onEvent)) {
+                        call_user_func($this->onEvent, $this);
+                    }
+                    if ($this->_stop) {
+                        break;
+                    }
+                } else {
+                    $task = $this->initTask($task);
+                    $this->_taskRunning[(int) $task['ch']] = $task;
+                    curl_multi_add_handle($this->_mh, $task['ch']);
+                }
+            } else {
+                break;
+            }
+            if (null == $cache) {
+                $c --;
+            }
+        }
+    }
+
+    /**
+     * Process response
+     *
+     * @param array $task
+     * @param array $param
+     */
+    protected function onProcess($task, $param)
+    {
+        $userRes = array();
+        if (isset($task['onSuccess'])) {
+            $userRes = call_user_func($task['onSuccess'], $param, $task['args']);
+        }
+        if (isset($userRes['cache'])) {
+            $task['cache'] = array_merge($task['cache'], $userRes['cache']);
+        }
+        // write cache
+        if (! isset($param['cache'])) {
+            $this->cache($task, $param);
+        }
+    }
+
+    /**
+     *
+     * @param string $url
+     * @param string|array $post
+     * @return string
+     */
+    public function getCacheFile($url, $post = null)
+    {
+        $suffix = '';
+        if (isset($post)) {
+            if (is_array($post)) {
+                ksort($post);
+                $post = http_build_query($post);
+            }
+            $suffix .= $post;
+        }
+        $key = md5($url . $suffix);
+        return substr($key, 0, 3) . '/' . substr($key, 3, 3) . '/' . substr($key, 6);
+    }
+
+    /**
+     * Set or get file cache.
+     *
+     * @param $task
+     * @param array|null $data
+     * @return mixed
+     */
+    protected function cache($task, $data = null)
+    {
+        $config = array_merge($this->cache, $task['cache']);
+        if (! $config['enable']) {
+            return null;
+        }
+        if (! isset($config['dir'])) {
+            user_error('cache dir is not defined', E_USER_WARNING);
+            return null;
+        }
+        $url = $task['opt'][CURLOPT_URL];
+        $post = null;
+        if (true == $config['verifyPost'] && ! empty($task['opt'][CURLOPT_POSTFIELDS])) {
+            $post = $task['opt'][CURLOPT_POSTFIELDS];
+        }
+        $file = rtrim($config['dir'], '/') . '/';
+        $file .= $this->getCacheFile($url, $post);
+        if (! isset($data)) {
+            if (file_exists($file)) {
+                $time = time();
+                $mtime = filemtime($file);
+                if ($time - $mtime < $config['expire']) {
+                    return unserialize(gzuncompress(file_get_contents($file)));
+                }
+            }
+        } else {
+            if (! isset($data['cache'])) {
+                $data['cache'] = array();
+            }
+            $data['cacheFile'] = $file;
+            unset($data['curl']);
+            $dir = dirname($file);
+            $dir1 = dirname($dir);
+            if (! is_dir($dir1)) {
+                mkdir($dir1);
+            }
+            if (! is_dir($dir)) {
+                mkdir($dir);
+            }
+            // Cache response from downloaded file.
+            if (isset($task['fileMeta']['uri'])) {
+                $data['body'] = file_get_contents($task['fileMeta']['uri']);
+            }
+            file_put_contents($file, gzcompress(serialize($data), $config['compress']), LOCK_EX);
+        }
+        return null;
+    }
+
+    /**
+     *
+     * @param array $task
+     * @return array
+     */
+    protected function initTask($task)
+    {
+        $task['ch'] = curl_init();
+        $opt = $this->opt;
+        foreach ($task['opt'] as $k => $v) {
+            $opt[$k] = $v;
+        }
+        curl_setopt_array($task['ch'], $opt);
+        $task['opt'] = $opt;
+        return $task;
+    }
+}

+ 916 - 0
src/Ares333/Toolkit.php

@@ -0,0 +1,916 @@
+<?php /** @noinspection PhpUnused */
+
+namespace Ares333\Curl;
+
+/**
+ * Toolkit for Curl
+ */
+class Toolkit
+{
+
+    // Curl instance
+    protected $_curl;
+
+    function setCurl(Curl $curl = null)
+    {
+        $this->_curl = $curl;
+        if (! isset($this->_curl)) {
+            $this->_curl = new Curl();
+            $this->_curl->opt = array(
+                CURLINFO_HEADER_OUT => true,
+                CURLOPT_HEADER => true,
+                CURLOPT_CONNECTTIMEOUT => 10,
+                CURLOPT_TIMEOUT => 30,
+                CURLOPT_AUTOREFERER => true,
+                CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_FOLLOWLOCATION => true,
+                CURLOPT_SSL_VERIFYHOST => false,
+                CURLOPT_SSL_VERIFYPEER => false,
+                CURLOPT_MAXREDIRS => 5
+            );
+            // default fail callback
+            $this->_curl->onFail = array(
+                $this,
+                'onFail'
+            );
+            // default info callback
+            $this->_curl->onInfo = array(
+                $this,
+                'onInfo'
+            );
+        }
+    }
+
+    /**
+     * Output curl error information
+     *
+     * @param array $error
+     */
+    function onFail($error)
+    {
+        $msg = "Curl error ($error[errorCode]). $error[errorMsg], url=" . $error['info']['url'];
+        if ($this->_curl->onInfo == array(
+            $this,
+            'onInfo'
+        )) {
+            $this->onInfo($msg . "\n");
+        } else {
+            echo "\n$msg\n\n";
+        }
+    }
+
+    /**
+     *
+     * Add delayed and formatted output or output with running information.
+     *
+     * @param array|string $info
+     *            array('all'=>array(),'running'=>array())
+     */
+    function onInfo($info)
+    {
+        $isLast = null;
+        if (func_num_args() == 3) {
+            $isLast = func_get_arg(2);
+        }
+        static $meta = array(
+            'downloadSpeed' => array(
+                0,
+                'SPD'
+            ),
+            'downloadSize' => array(
+                0,
+                'DWN'
+            ),
+            'finishNum' => array(
+                0,
+                'FNH'
+            ),
+            'cacheNum' => array(
+                0,
+                'CACHE'
+            ),
+            'taskRunningNum' => array(
+                0,
+                'RUN'
+            ),
+            'activeNum' => array(
+                0,
+                'ACTIVE'
+            ),
+            'taskPoolNum' => array(
+                0,
+                'POOL'
+            ),
+            'queueNum' => array(
+                0,
+                'QUEUE'
+            ),
+            'taskNum' => array(
+                0,
+                'TASK'
+            ),
+            'failNum' => array(
+                0,
+                'FAIL'
+            )
+        );
+        static $isFirst = true;
+        static $buffer = '';
+        if (is_string($info)) {
+            $buffer .= $info;
+            return;
+        }
+        $all = $info['all'];
+        $all['downloadSpeed'] = round($all['downloadSpeed'] / 1024) . 'KB';
+        $all['downloadSize'] = round(($all['headerSize'] + $all['bodySize']) / 1024 / 1024) . "MB";
+        // clean
+        foreach (array_keys($meta) as $v) {
+            if (! array_key_exists($v, $all)) {
+                unset($meta[$v]);
+            }
+        }
+        $content = '';
+        $lenPad = 2;
+        $caption = '';
+        foreach (array(
+            'meta'
+        ) as $name) {
+            foreach ($$name as $k => $v) {
+                if (! isset($all[$k])) {
+                    continue;
+                }
+                if (mb_strlen($all[$k]) > $v[0]) {
+                    $v[0] = mb_strlen($all[$k]);
+                }
+                if (PHP_OS == 'Linux') {
+                    if (mb_strlen($v[1]) > $v[0]) {
+                        $v[0] = mb_strlen($v[1]);
+                    }
+                    $caption .= sprintf('%-' . ($v[0] + $lenPad) . 's', $v[1]);
+                    $content .= sprintf('%-' . ($v[0] + $lenPad) . 's', $all[$k]);
+                } else {
+                    $format = '%-' . ($v[0] + strlen($v[1]) + 1 + $lenPad) . 's';
+                    $content .= sprintf($format, $v[1] . ':' . $all[$k]);
+                }
+                ${$name}[$k] = $v;
+            }
+        }
+        $str = '';
+        if (PHP_OS == 'Linux') {
+            if ($isFirst) {
+                $str .= "\n";
+                $isFirst = false;
+            }
+            $str .= "\33[A\r\33[K" . $caption . "\n\r\33[K" . rtrim($content);
+        } else {
+            $str .= "\r" . rtrim($content);
+        }
+        echo $str;
+        if ($isLast) {
+            echo "\n";
+        }
+        if ('' !== $buffer) {
+            if ($isLast) {
+                echo trim($buffer) . "\n";
+            } else {
+                echo "\n" . trim($buffer) . "\n\n";
+            }
+            $buffer = '';
+        }
+    }
+
+    /**
+     * Html encoding transform
+     *
+     * @param string $html
+     * @param string $in
+     *            detect automatically if not set
+     * @param string $out
+     *            default UTF-8
+     * @param string $mode
+     *            auto|iconv|mb_convert_encoding
+     * @return string
+     */
+    function htmlEncode($html, $in = null, $out = null, $mode = 'auto')
+    {
+        $valid = array(
+            'auto',
+            'iconv',
+            'mb_convert_encoding'
+        );
+        if (! isset($out)) {
+            $out = 'UTF-8';
+        }
+        if (! in_array($mode, $valid)) {
+            user_error('invalid mode, mode=' . $mode, E_USER_ERROR);
+        }
+        $if = function_exists('mb_convert_encoding');
+        $if = $if && ($mode == 'auto' || $mode == 'mb_convert_encoding');
+        $func = null;
+        if (function_exists('iconv') && ($mode == 'auto' || $mode == 'iconv')) {
+            $func = 'iconv';
+        } elseif ($if) {
+            $func = 'mb_convert_encoding';
+        } else {
+            user_error('encode failed, php extension not found', E_USER_ERROR);
+        }
+        $pattern = '/(<meta[^>]*?charset=(["\']?))([a-z\d_\-]*)(\2[^>]*?>)/is';
+        if (! isset($in)) {
+            $n = preg_match($pattern, $html, $in);
+            if ($n > 0) {
+                $in = $in[3];
+            } else {
+                if (function_exists('mb_detect_encoding')) {
+                    $in = mb_detect_encoding($html);
+                } else {
+                    $in = null;
+                }
+            }
+        }
+        if (isset($in)) {
+            $old = error_reporting(error_reporting() & ~ E_NOTICE);
+            $html = call_user_func($func, $in, $out . '//IGNORE', $html);
+            error_reporting($old);
+            $html = preg_replace($pattern, "\\1$out\\4", $html, 1);
+        } else {
+            user_error('source encoding is unknown', E_USER_ERROR);
+        }
+        return $html;
+    }
+
+    /**
+     * content between start and end
+     *
+     * @param string $str
+     * @param string $start
+     * @param string $end
+     * @param bool $greed
+     * @return string
+     */
+    function between($str, $start, $end = null, $greed = true)
+    {
+        if (isset($start)) {
+            $pos1 = strpos($str, $start);
+        } else {
+            $pos1 = 0;
+        }
+        if (isset($end)) {
+            if ($greed) {
+                $pos2 = strrpos($str, $end);
+            } else {
+                $pos2 = strpos($str, $end, $pos1);
+            }
+        } else {
+            $pos2 = strlen($str);
+        }
+        if (false === $pos1 || false === $pos2 || $pos2 < $pos1) {
+            return '';
+        }
+        $len = strlen($start);
+        return substr($str, $pos1 + $len, $pos2 - $pos1 - $len);
+    }
+
+    /**
+     *
+     * @param string $url
+     * @return boolean
+     */
+    function isUrl($url)
+    {
+        $url = ltrim($url);
+        return in_array(substr($url, 0, 7), array(
+            'http://',
+            'https:/'
+        ));
+    }
+
+    /**
+     * Clean up and format
+     *
+     * @param string $url
+     * @return string|null
+     */
+    function formatUrl($url)
+    {
+        if (! $this->isUrl($url)) {
+            return null;
+        }
+        $url = trim($url);
+        $url = str_replace(' ', '+', $url);
+        $parse = parse_url($url);
+        strtolower($parse['scheme']);
+        strtolower($parse['host']);
+        return $this->buildUrl($parse);
+    }
+
+    /**
+     *
+     * @param array $parse
+     * @return string
+     */
+    function buildUrl(array $parse)
+    {
+        $keys = array(
+            'scheme',
+            'host',
+            'port',
+            'user',
+            'pass',
+            'path',
+            'query',
+            'fragment'
+        );
+        foreach ($keys as $v) {
+            if (! isset($parse[$v])) {
+                $parse[$v] = '';
+            }
+        }
+        if ('' !== $parse['scheme']) {
+            $parse['scheme'] .= '://';
+        }
+        if ('' !== $parse['user']) {
+            $parse['user'] .= ':';
+            $parse['pass'] .= '@';
+        }
+        if ('' !== $parse['port']) {
+            $parse['host'] .= ':';
+        }
+        if ('' !== $parse['query']) {
+            $parse['path'] .= '?';
+            // sort
+            $query = array();
+            parse_str($parse['query'], $query);
+            asort($query);
+            $parse['query'] = http_build_query($query);
+        }
+        if ('' !== $parse['fragment']) {
+            $parse['query'] .= '#';
+        }
+        $parse['path'] = preg_replace('/\/+/', '/', $parse['path']);
+        return $parse['scheme'] . $parse['user'] . $parse['pass'] . $parse['host'] . $parse['port'] . $parse['path'] .
+            $parse['query'] . $parse['fragment'];
+    }
+
+    /**
+     *
+     * @param string $uri
+     * @param string $urlCurrent
+     *            Should be final url which was redirected by 3xx http code.
+     * @return string|null
+     */
+    function uri2url($uri, $urlCurrent)
+    {
+        if (empty($uri)) {
+            return $urlCurrent;
+        }
+        if ($this->isUrl($uri)) {
+            return $uri;
+        }
+        if (! $this->isUrl($urlCurrent)) {
+            return null;
+        }
+        // uri started with ?,#
+        if (0 === strpos($uri, '#') || 0 === strpos($uri, '?')) {
+            if (false !== ($pos = strpos($urlCurrent, '#'))) {
+                $urlCurrent = substr($urlCurrent, 0, $pos);
+            }
+            if (false !== ($pos = strpos($urlCurrent, '?'))) {
+                $urlCurrent = substr($urlCurrent, 0, $pos);
+            }
+            return $urlCurrent . $uri;
+        }
+        if (0 === strpos($uri, './')) {
+            $uri = substr($uri, 2);
+        }
+        $urlDir = $this->url2dir($urlCurrent);
+        if (0 === strpos($uri, '/')) {
+            $path = parse_url($urlDir, PHP_URL_PATH);
+            if (isset($path)) {
+                $len = 0 - strlen($path);
+            } else {
+                $len = strlen($urlDir);
+            }
+            return substr($urlDir, 0, $len) . $uri;
+        } else {
+            return $urlDir . $uri;
+        }
+    }
+
+    /**
+     *
+     * @param string $url
+     * @param string $urlCurrent
+     *            Should be final url which was redirected by 3xx http code.
+     * @return string|null
+     */
+    function url2uri($url, $urlCurrent)
+    {
+        if (! $this->isUrl($url)) {
+            return null;
+        }
+        $urlDir = $this->url2dir($urlCurrent);
+        $parse1 = parse_url($url);
+        $parse2 = parse_url($urlDir);
+        if (! array_key_exists('port', $parse1)) {
+            $parse1['port'] = null;
+        }
+        if (! array_key_exists('port', $parse2)) {
+            $parse2['port'] = null;
+        }
+        $eq = true;
+        foreach (array(
+            'scheme',
+            'host',
+            'port'
+        ) as $v) {
+            if (isset($parse1[$v]) && isset($parse2[$v])) {
+                if ($parse1[$v] != $parse2[$v]) {
+                    $eq = false;
+                    break;
+                }
+            }
+        }
+        $path = null;
+        if ($eq) {
+            $len = strlen($urlDir) - strlen(parse_url($urlDir, PHP_URL_PATH));
+            // relative path
+            $path1 = substr($url, $len + 1);
+            $path2 = substr($urlDir, $len + 1);
+            $arr1 = explode('/', $path1);
+            $arr2 = explode('/', $path2);
+            foreach ($arr1 as $k => $v) {
+                if (empty($v)) {
+                    continue;
+                }
+                if (array_key_exists($k, $arr2) && $v == $arr2[$k]) {
+                    unset($arr1[$k], $arr2[$k]);
+                } else {
+                    break;
+                }
+            }
+            $path = '';
+            foreach ($arr2 as $v) {
+                if (empty($v)) {
+                    continue;
+                }
+                $path .= '../';
+            }
+            $path .= implode('/', $arr1);
+        }
+        return $path;
+    }
+
+    /**
+     *
+     * @param string $url
+     *            Should be final url which was redirected by 3xx http code.
+     * @return string|null
+     */
+    function url2dir($url)
+    {
+        if (! $this->isUrl($url)) {
+            return null;
+        }
+        $parse = parse_url($url);
+        $urlDir = $url;
+        if (isset($parse['path'])) {
+            if ('/' != substr($urlDir, - 1)) {
+                $urlDir = dirname($urlDir) . '/';
+            }
+        } else {
+            if ('/' != substr($urlDir, - 1)) {
+                $urlDir .= '/';
+            }
+        }
+        return $urlDir;
+    }
+
+    /**
+     * Combine a base URL and a relative URL to produce a new
+     * absolute URL.
+     * The base URL is often the URL of a page,
+     * and the relative URL is a URL embedded on that page.
+     *
+     * This function implements the "absolutize" algorithm from
+     * the RFC3986 specification for URLs.
+     *
+     * This function supports multi-byte characters with the UTF-8 encoding,
+     * per the URL specification.
+     *
+     * Parameters:
+     * baseUrl the absolute base URL.
+     *
+     * url the relative URL to convert.
+     *
+     * Return values:
+     * An absolute URL that combines parts of the base and relative
+     * URLs, or FALSE if the base URL is not absolute or if either
+     * URL cannot be parsed.
+     *
+     *
+     * @param $url
+     * @param $urlCurrent
+     * @return bool|string
+     * @noinspection SpellCheckingInspection
+     */
+    function url2absolute($url, $urlCurrent)
+    {
+        // If relative URL has a scheme, clean path and return.
+        $r = $this->splitUrl($url);
+        if ($r === FALSE)
+            return FALSE;
+        if (! empty($r['scheme'])) {
+            if (! empty($r['path']) && $r['path'][0] == '/')
+                $r['path'] = $this->urlRemoveDotSegments($r['path']);
+            return $this->joinUrl($r);
+        }
+
+        // Make sure the base URL is absolute.
+        $b = $this->splitUrl($urlCurrent);
+        if ($b === FALSE || empty($b['scheme']) || empty($b['host']))
+            return FALSE;
+        $r['scheme'] = $b['scheme'];
+
+        // If relative URL has an authority, clean path and return.
+        if (isset($r['host'])) {
+            if (! empty($r['path']))
+                $r['path'] = $this->urlRemoveDotSegments($r['path']);
+            return $this->joinUrl($r);
+        }
+        unset($r['port']);
+        unset($r['user']);
+        unset($r['pass']);
+
+        // Copy base authority.
+        $r['host'] = $b['host'];
+        if (isset($b['port']))
+            $r['port'] = $b['port'];
+        if (isset($b['user']))
+            $r['user'] = $b['user'];
+        if (isset($b['pass']))
+            $r['pass'] = $b['pass'];
+
+        // If relative URL has no path, use base path
+        if (empty($r['path'])) {
+            if (! empty($b['path']))
+                $r['path'] = $b['path'];
+            if (! isset($r['query']) && isset($b['query']))
+                $r['query'] = $b['query'];
+            return $this->joinUrl($r);
+        }
+
+        // If relative URL path doesn't start with /, merge with base path
+        if ($r['path'][0] != '/') {
+            $base = mb_strrchr($b['path'], '/', TRUE, 'UTF-8');
+            if ($base === FALSE)
+                $base = '';
+            $r['path'] = $base . '/' . $r['path'];
+        }
+        $r['path'] = $this->urlRemoveDotSegments($r['path']);
+        return $this->joinUrl($r);
+    }
+
+    /**
+     * Filter out "." and ".." segments from a URL's path and return
+     * the result.
+     *
+     * This function implements the "remove_dot_segments" algorithm from
+     * the RFC3986 specification for URLs.
+     *
+     * This function supports multi-byte characters with the UTF-8 encoding,
+     * per the URL specification.
+     *
+     * Parameters:
+     * path the path to filter
+     *
+     * Return values:
+     * The filtered path with "." and ".." removed.
+     *
+     * @param $path
+     * @return string
+     */
+    function urlRemoveDotSegments($path)
+    {
+        // multi-byte character explode
+        $inSeg = preg_split('!/!u', $path);
+        $outSeg = array();
+        foreach ($inSeg as $seg) {
+            if ($seg == '' || $seg == '.')
+                continue;
+            if ($seg == '..')
+                array_pop($outSeg);
+            else
+                array_push($outSeg, $seg);
+        }
+        $outPath = implode('/', $outSeg);
+        if ($path[0] == '/')
+            $outPath = '/' . $outPath;
+        // compare last multi-byte character against '/'
+        if ($outPath != '/' && (mb_strlen($path) - 1) == mb_strrpos($path, '/', 'UTF-8'))
+            $outPath .= '/';
+        return $outPath;
+    }
+
+    /**
+     * This function parses an absolute or relative URL and splits it
+     * into individual components.
+     *
+     * RFC3986 specifies the components of a Uniform Resource Identifier (URI).
+     * A portion of the ABNFs are repeated here:
+     *
+     * URI-reference = URI
+     * / relative-ref
+     *
+     * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
+     *
+     * relative-ref = relative-part [ "?" query ] [ "#" fragment ]
+     *
+     * hier-part = "//" authority path-abempty
+     * / path-absolute
+     * / path-rootless
+     * / path-empty
+     *
+     * relative-part = "//" authority path-abempty
+     * / path-absolute
+     * / path-noscheme
+     * / path-empty
+     *
+     * authority = [ userinfo "@" ] host [ ":" port ]
+     *
+     * So, a URL has the following major components:
+     *
+     * scheme
+     * The name of a method used to interpret the rest of
+     * the URL. Examples: "http", "https", "mailto", "file'.
+     *
+     * authority
+     * The name of the authority governing the URL's name
+     * space. Examples: "example.com", "user@example.com",
+     * "example.com:80", "user:password@example.com:80".
+     *
+     * The authority may include a host name, port number,
+     * user name, and password.
+     *
+     * The host may be a name, an IPv4 numeric address, or
+     * an IPv6 numeric address.
+     *
+     * path
+     * The hierarchical path to the URL's resource.
+     * Examples: "/index.htm", "/scripts/page.php".
+     *
+     * query
+     * The data for a query. Examples: "?search=google.com".
+     *
+     * fragment
+     * The name of a secondary resource relative to that named
+     * by the path. Examples: "#section1", "#header".
+     *
+     * An "absolute" URL must include a scheme and path. The authority, query,
+     * and fragment components are optional.
+     *
+     * A "relative" URL does not include a scheme and must include a path. The
+     * authority, query, and fragment components are optional.
+     *
+     * This function splits the $url argument into the following components
+     * and returns them in an associative array. Keys to that array include:
+     *
+     * "scheme" The scheme, such as "http".
+     * "host" The host name, IPv4, or IPv6 address.
+     * "port" The port number.
+     * "user" The user name.
+     * "pass" The user password.
+     * "path" The path, such as a file path for "http".
+     * "query" The query.
+     * "fragment" The fragment.
+     *
+     * One or more of these may not be present, depending upon the URL.
+     *
+     * Optionally, the "user", "pass", "host" (if a name, not an IP address),
+     * "path", "query", and "fragment" may have percent-encoded characters
+     * decoded. The "scheme" and "port" cannot include percent-encoded
+     * characters and are never decoded. Decoding occurs after the URL has
+     * been parsed.
+     *
+     * Parameters:
+     * url the URL to parse.
+     *
+     * decode an optional boolean flag selecting whether
+     * to decode percent encoding or not. Default = TRUE.
+     *
+     * Return values:
+     * the associative array of URL parts, or FALSE if the URL is
+     * too malformed to recognize any parts.
+     *
+     *
+     * @param $url
+     * @param bool $decode
+     * @return array|bool
+     * @noinspection SpellCheckingInspection
+     */
+    protected function splitUrl($url, $decode = TRUE)
+    {
+        // Character sets from RFC3986.
+        $xunressub = 'a-zA-Z\d\-._~\!$&\'()*+,;=';
+        $xpchar = $xunressub . ':@%';
+
+        // Scheme from RFC3986.
+        $xscheme = '([a-zA-Z][a-zA-Z\d+-.]*)';
+
+        // User info (user + password) from RFC3986.
+        $xuserinfo = '(([' . $xunressub . '%]*)' . '(:([' . $xunressub . ':%]*))?)';
+
+        // IPv4 from RFC3986 (without digit constraints).
+        $xipv4 = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})';
+
+        // IPv6 from RFC2732 (without digit and grouping constraints).
+        $xipv6 = '(\[([a-fA-F\d.:]+)\])';
+
+        // Host name from RFC1035. Technically, must start with a letter.
+        // Relax that restriction to better parse URL structure, then
+        // leave host name validation to application.
+        $xhost_name = '([a-zA-Z\d-.%]+)';
+
+        // Authority from RFC3986. Skip IP future.
+        $xhost = '(' . $xhost_name . '|' . $xipv4 . '|' . $xipv6 . ')';
+        $xport = '(\d*)';
+        $xauthority = '((' . $xuserinfo . '@)?' . $xhost . '?(:' . $xport . ')?)';
+
+        // Path from RFC3986. Blend absolute & relative for efficiency.
+        $xslash_seg = '(/[' . $xpchar . ']*)';
+        $xpath_authabs = '((//' . $xauthority . ')((/[' . $xpchar . ']*)*))';
+        $xpath_rel = '([' . $xpchar . ']+' . $xslash_seg . '*)';
+        $xpath_abs = '(/(' . $xpath_rel . ')?)';
+        $xapath = '(' . $xpath_authabs . '|' . $xpath_abs . '|' . $xpath_rel . ')';
+
+        // Query and fragment from RFC3986.
+        $xqueryfrag = '([' . $xpchar . '/?' . ']*)';
+
+        // URL.
+        $xurl = '^(' . $xscheme . ':)?' . $xapath . '?' . '(\?' . $xqueryfrag . ')?(#' . $xqueryfrag . ')?$';
+
+        // Split the URL into components.
+        $m = array();
+        if (! preg_match('!' . $xurl . '!', $url, $m))
+            return false;
+
+        $parts = array();
+        if (! empty($m[2]))
+            $parts['scheme'] = strtolower($m[2]);
+
+        if (! empty($m[7])) {
+            if (isset($m[9]))
+                $parts['user'] = $m[9];
+            else
+                $parts['user'] = '';
+        }
+        if (! empty($m[10]))
+            $parts['pass'] = $m[11];
+
+        if (! empty($m[13]))
+            $h = $parts['host'] = $m[13];
+        else if (! empty($m[14]))
+            $parts['host'] = $m[14];
+        else if (! empty($m[16]))
+            $parts['host'] = $m[16];
+        else if (! empty($m[5]))
+            $parts['host'] = '';
+        if (! empty($m[17]))
+            $parts['port'] = $m[18];
+
+        if (! empty($m[19]))
+            $parts['path'] = $m[19];
+        else if (! empty($m[21]))
+            $parts['path'] = $m[21];
+        else if (! empty($m[25]))
+            $parts['path'] = $m[25];
+
+        if (! empty($m[27]))
+            $parts['query'] = $m[28];
+        if (! empty($m[29]))
+            $parts['fragment'] = $m[30];
+
+        if (! $decode)
+            return $parts;
+        if (! empty($parts['user']))
+            $parts['user'] = rawurldecode($parts['user']);
+        if (! empty($parts['pass']))
+            $parts['pass'] = rawurldecode($parts['pass']);
+        if (! empty($parts['path']))
+            $parts['path'] = rawurldecode($parts['path']);
+        if (isset($h))
+            $parts['host'] = rawurldecode($parts['host']);
+        if (! empty($parts['query']))
+            $parts['query'] = rawurldecode($parts['query']);
+        if (! empty($parts['fragment']))
+            $parts['fragment'] = rawurldecode($parts['fragment']);
+        return $parts;
+    }
+
+    /**
+     * This function joins together URL components to form a complete URL.
+     *
+     * RFC3986 specifies the components of a Uniform Resource Identifier (URI).
+     * This function implements the specification's "component recomposition"
+     * algorithm for combining URI components into a full URI string.
+     *
+     * The $parts argument is an associative array containing zero or
+     * more of the following:
+     *
+     * "scheme" The scheme, such as "http".
+     * "host" The host name, IPv4, or IPv6 address.
+     * "port" The port number.
+     * "user" The user name.
+     * "pass" The user password.
+     * "path" The path, such as a file path for "http".
+     * "query" The query.
+     * "fragment" The fragment.
+     *
+     * The "port", "user", and "pass" values are only used when a "host"
+     * is present.
+     *
+     * The optional $encode argument indicates if appropriate URL components
+     * should be percent-encoded as they are assembled into the URL. Encoding
+     * is only applied to the "user", "pass", "host" (if a host name, not an
+     * IP address), "path", "query", and "fragment" components. The "scheme"
+     * and "port" are never encoded. When a "scheme" and "host" are both
+     * present, the "path" is presumed to be hierarchical and encoding
+     * processes each segment of the hierarchy separately (i.e., the slashes
+     * are left alone).
+     *
+     * The assembled URL string is returned.
+     *
+     * Parameters:
+     * parts an associative array of strings containing the
+     * individual parts of a URL.
+     *
+     * encode an optional boolean flag selecting whether
+     * to do percent encoding or not. Default = true.
+     *
+     * Return values:
+     * Returns the assembled URL string. The string is an absolute
+     * URL if a scheme is supplied, and a relative URL if not. An
+     * empty string is returned if the $parts array does not contain
+     * any of the needed values.
+     *
+     *
+     * @param $parts
+     * @param bool $encode
+     * @return string
+     * @noinspection SpellCheckingInspection
+     */
+    protected function joinUrl($parts, $encode = TRUE)
+    {
+        if ($encode) {
+            if (isset($parts['user']))
+                $parts['user'] = rawurlencode($parts['user']);
+            if (isset($parts['pass']))
+                $parts['pass'] = rawurlencode($parts['pass']);
+            if (isset($parts['host']) && ! preg_match('!^(\[[\da-f.:]+]])|([\da-f.:]+)$!ui', $parts['host']))
+                $parts['host'] = rawurlencode($parts['host']);
+            if (! empty($parts['path']))
+                $parts['path'] = preg_replace('!%2F!ui', '/', rawurlencode($parts['path']));
+            if (isset($parts['query']))
+                $parts['query'] = rawurlencode($parts['query']);
+            if (isset($parts['fragment']))
+                $parts['fragment'] = rawurlencode($parts['fragment']);
+        }
+
+        $url = '';
+        if (! empty($parts['scheme']))
+            $url .= $parts['scheme'] . ':';
+        if (isset($parts['host'])) {
+            $url .= '//';
+            if (isset($parts['user'])) {
+                $url .= $parts['user'];
+                if (isset($parts['pass']))
+                    $url .= ':' . $parts['pass'];
+                $url .= '@';
+            }
+            if (preg_match('!^[\da-f]*:[\da-f.:]+$!ui', $parts['host']))
+                $url .= '[' . $parts['host'] . ']'; // IPv6
+            else
+                $url .= $parts['host']; // IPv4 or name
+            if (isset($parts['port']))
+                $url .= ':' . $parts['port'];
+            if (! empty($parts['path']) && $parts['path'][0] != '/')
+                $url .= '/';
+        }
+        if (! empty($parts['path']))
+            $url .= $parts['path'];
+        if (isset($parts['query']))
+            $url .= '?' . $parts['query'];
+        if (isset($parts['fragment']))
+            $url .= '#' . $parts['fragment'];
+        return $url;
+    }
+
+    /**
+     *
+     * @return Curl
+     */
+    function getCurl()
+    {
+        return $this->_curl;
+    }
+}

+ 0 - 494
src/Dever/Cache/Handle.php

@@ -1,494 +0,0 @@
-<?php namespace Dever\Cache;
-
-# 2019-04-23更新,为了新需求比较乱,后续优化
-use Dever;
-use Dever\Cache\Store;
-use Dever\Loader\Config;
-use Dever\Output\Debug;
-use Dever\Routing\Input;
-
-class Handle
-{
-    /**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * store
-     *
-     * @var object
-     */
-    protected $store;
-
-    /**
-     * config
-     *
-     * @var array
-     */
-    protected $config;
-
-    /**
-     * expire
-     *
-     * @var int
-     */
-    protected $expire;
-
-    /**
-     * type
-     *
-     * @var string
-     */
-    protected $type;
-
-    /**
-     * get
-     * @param string $key
-     * @param array $data
-     * @param int $expire
-     * @param string $type
-     *
-     * @return Dever\Cache\Handle;
-     */
-    public static function load($key = false, $data = false, $expire = 0, $type = 'data', $page = false)
-    {
-        $cache = Config::get('cache')->cAll;
-        if (empty($cache[$type])) {
-            return false;
-        }
-        $handle = self::getInstance($type, $cache[$type]);
-
-        if (is_string($data) && $data == 'delete') {
-            return $handle->delete($key);
-        } elseif ($data) {
-            return $handle->set($key, $data, $expire, $page);
-        }
-        return $handle->get($key, $page);
-    }
-
-    /**
-     * counter
-     * @param string $key
-     * @param array $data
-     * @param int $expire
-     * @param string $type
-     *
-     * @return Dever\Cache\Handle;
-     */
-    public static function counter($key = false, $data = false, $callback = false, $type = 'data', $page = false)
-    {
-        $cache = Config::get('cache')->cAll;
-        if (empty($cache[$type])) {
-            return false;
-        }
-        $handle = self::getInstance($type, $cache[$type]);
-
-        $value = $handle->get($key, $page);
-        if ($data == false) {
-            return $value;
-        }
-        if (!$value) {
-            if ($callback) {
-                $num = $callback();
-                $data = $data + $num;
-            }
-            return $handle->set($key, $data, 0, $page);
-        }
-        return $handle->incr($key, $data);
-    }
-
-    /**
-     * getInstance
-     *
-     * @return Dever\Cache\Handle;
-     */
-    public static function getInstance($type = 'mysql', $expire = 3600)
-    {
-        if (empty(self::$instance[$type])) {
-            self::$instance[$type] = new self($expire, $type);
-        }
-
-        return self::$instance[$type];
-    }
-
-    /**
-     * closeAll
-     *
-     * @return mixed
-     */
-    public static function closeAll()
-    {
-        return;
-        if (self::$instance) {
-            foreach (self::$instance as $k => $v) {
-                self::$instance[$k]->close();
-                self::$instance[$k] = null;
-                unset(self::$instance[$k]);
-            }
-        }
-    }
-
-    public function __construct($expire = 3600, $type = 'mysql')
-    {
-        $this->expire = $expire;
-        $this->type = $type;
-
-        if (!$this->config) {
-            $this->config = Config::get('cache')->cAll;
-        }
-    }
-
-    public function close()
-    {
-        if ($this->store) {
-            $this->store->close();
-        }
-    }
-
-    public function store($key)
-    {
-        if ($this->store) {
-            return true;
-        }
-
-        if ($this->none($key)) {
-            return false;
-        }
-
-        if (isset($this->config['store']) && $this->config['store']) {
-            $this->store = Store::getInstance($this->config['type'], $this);
-
-            foreach ($this->config['store'] as $k => $v) {
-                if (empty($v['expire'])) {
-                    $v['expire'] = $this->expire;
-                }
-                $this->store->connect($v);
-            }
-
-            return true;
-        }
-
-        return false;
-    }
-
-    /**
-     * get
-     *
-     * @return mixd
-     */
-    public function get($key, $page = true)
-    {
-        $param = isset($this->config['shell']) ? $this->config['shell'] : 'clearcache';
-        if (Input::shell($param)) {
-            //$this->delete($key);
-            return false;
-        }
-
-        $cache = Config::get('base')->cacheGetData;
-        if (isset($cache[$key])) {
-            return $cache[$key];
-        }
-
-        if ($page) {
-            if (!$this->init($key)) {
-                return false;
-            }
-        }
-
-        /*
-        if (!$this->init($key)) {
-            return false;
-        }
-        */
-
-        if (!$this->store($key)) {
-            return false;
-        }
-
-        $data = $this->store->get($key);
-        //$data = json_decode(base64_decode($data), true);
-        if (strstr($data, 'serialize_')) {
-            $data = str_replace('serialize_', '', $data);
-            $data = unserialize($data);
-        }
-        
-        $this->log('get', $key, $data, $this->expire($key));
-
-        $page_key = 'page_' . $key;
-        if ($page && $page_data = $this->store->get($page_key)) {
-            $page_data = unserialize($page_data);
-            Dever::$global['page'] = $page_data;
-            $this->log('get', $page_key, $page_data, $this->expire($page_key));
-        }
-
-        Config::get('base')->setArray('cacheGetData', $key, $data);
-
-        return $data;
-    }
-
-    /**
-     * set
-     *
-     * @return mixd
-     */
-    public function set($key, $value, $expire = 0, $page = true)
-    {
-        $cache = Config::get('base')->cacheSetData;
-        if (isset($cache[$key])) {
-            return $cache[$key];
-        }
-
-        $state = true;
-        if ($page) {
-            $state = $this->init($key);
-            if (!$state) {
-                return false;
-            }
-        }
-        /*
-        $state = $this->init($key);
-        if (!$state) {
-            return false;
-        }
-        */
-
-        if (!$this->store($key)) {
-            return false;
-        }
-
-        if ($expire == 0) {
-            if ($state > 1) {
-                $expire = $state;
-            } else {
-                $expire = $this->expire;
-            }
-        }
-
-        $this->expire($key, $expire);
-        $this->log('set', $key, $value, $expire);
-        //$value = base64_encode(json_encode($value));
-        if (is_array($value)) {
-            $value = 'serialize_' . serialize($value);
-        }
-
-        if ($page && isset(Dever::$global['page']) && Dever::$global['page']) {
-            $page_key = 'page_' . $key;
-            $this->store->set($page_key, serialize(Dever::$global['page']), $expire);
-            $this->log('set', $page_key, Dever::$global['page'], $expire);
-        }
-        
-        Config::get('base')->setArray('cacheSetData', $key, true);
-        return $this->store->set($key, $value, $expire);
-    }
-
-    /**
-     * incr
-     *
-     * @return mixd
-     */
-    public function incr($key, $value)
-    {
-        $state = $this->init($key);
-        if (!$state) {
-            return false;
-        }
-
-        if (!$this->store($key)) {
-            return false;
-        }
-
-        $this->log('incr', $key, $value);
-        
-        return $this->store->incr($key, $value);
-    }
-
-    /**
-     * hGet
-     *
-     * @return mixd
-     */
-    public function hGet($key, $hkey = '', $exists = false)
-    {
-        $param = isset($this->config['shell']) ? $this->config['shell'] : 'clearcache';
-        if (Input::shell($param)) {
-            //$this->delete($key);
-            return false;
-        }
-
-        if (!$this->init($key)) {
-            return false;
-        }
-
-        if (!$this->store($key)) {
-            return false;
-        }
-
-        if ($hkey) {
-            if ($exists) {
-                $data = $this->store->hExists($key, $hkey);
-                return $data;
-            } else {
-                $data = $this->store->hGet($key, $hkey);
-            }
-        } else {
-            if ($exists) {
-                $data = $this->store->hKeys($key);
-                return $data;
-            }
-            $data = $this->store->hGet($key);
-        }
-
-        if ($data === false) {
-            $data = false;
-        } else {
-            $data = unserialize($data);
-        }
-
-        $this->log('hGet', $key . ':' . $hkey, $data, $this->expire($key));
-
-        return $data;
-    }
-
-    /**
-     * hSet
-     *
-     * @return mixd
-     */
-    public function hSet($key, $hkey, $value, $expire = 0)
-    {
-        $state = $this->init($key);
-        if (!$state) {
-            return false;
-        }
-
-        if (!$this->store($key)) {
-            return false;
-        }
-
-        if ($expire == 0) {
-            if ($state > 1) {
-                $expire = $state;
-            } else {
-                $expire = $this->expire;
-            }
-        }
-
-        $this->expire($key, $expire);
-        $this->log('hSet', $key . ':' . $hkey, $value, $expire);
-        $value = serialize($value);
-        
-        return $this->store->hSet($key, $hkey, $value, $expire);
-    }
-
-    /**
-     * delete
-     *
-     * @return mixd
-     */
-    public function delete($key, $hkey = false)
-    {
-        $state = $this->store($key);
-        if (!$state) {
-            return false;
-        }
-        $this->log('delete', $key, 1);
-        if ($hkey) {
-            return $this->store->hDel($key, $hkey);
-        }
-        return $this->store->delete($key);
-    }
-
-    /**
-     * init
-     *
-     * @return mixed
-     */
-    protected function init($key)
-    {
-        if ($this->type == 'route' && isset(Dever::config('base')->clearCache[$this->type])) {
-            return false;
-        }
-        $state = 1;
-
-        if (isset($this->config[$this->type . 'Key'])) {
-            foreach ($this->config[$this->type . 'Key'] as $k => $v) {
-                if (strpos($key, $k) !== false) {
-                    $state = $v;
-                }
-            }
-        }
-
-        if (!$state && strstr($key, 'route_')) {
-            Dever::config('base')->setArray('clearCache', $this->type, 1);
-        }
-
-        return $state;
-    }
-
-    /**
-     * none
-     *
-     * @return mixed
-     */
-    protected function none($key)
-    {
-        if (isset($this->config[$this->type . 'None'])) {
-            foreach ($this->config[$this->type . 'None'] as $k => $v) {
-                if (strpos($key, $v) !== false) {
-                    return true;
-                }
-            }
-        }
-
-        return false;
-    }
-
-    /**
-     * expire
-     *
-     * @return mixed
-     */
-    protected function expire($key, $expire = false)
-    {
-        if (isset($this->config['expire']) && $this->config['expire']) {
-            $key .= '_expire';
-            if ($expire > 0) {
-                //$expire = $expire * 2;
-                $this->store->set($key, DEVER_TIME + $expire, $expire);
-            } else {
-                $expire = $this->store->get($key);
-                if ($expire) {
-                    $num = $expire - DEVER_TIME;
-                    return '将于' . date('Y-m-d H:i:s', $expire) . '失效(' . $num . 's)';
-                }
-            }
-        }
-        return false;
-    }
-
-    /**
-     * log
-     *
-     * @return mixed
-     */
-    public function log($method, $key = false, $value = false, $expire = 0)
-    {
-        $expire = $expire ? $expire : $this->expire;
-        $log = array();
-        $log['method'] = $method;
-        $log['key'] = $key;
-        if ($value) {
-            if (!Input::shell('all') && is_array($value)) {
-                $value = count($value) . ' records';
-            }
-            $log['value'] = $value;
-        }
-        if ($expire >= 0) {
-            $log['expire'] = $expire;
-        }
-        Debug::log($log, 'cache');
-    }
-}

+ 0 - 39
src/Dever/Cache/Store.php

@@ -1,39 +0,0 @@
-<?php namespace Dever\Cache;
-
-/*
-interface StoreInterFace
-{
-	public function __construct();
-	public function connect($config);
-	public function get($key);
-	public function set($key, $value, $expire);
-	public function delete($key);
-	public function close();
-}
-*/
-
-class Store
-{
-	/**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-	/**
-     * getInstance
-     *
-     * @return Dever\Cache\Handle;
-     */
-    public static function getInstance($type = 'redis', $handle)
-    {
-        if (empty(self::$instance[$type])) {
-            $class = 'Dever\\Cache\\Store\\' . ucfirst($type);
-            self::$instance[$type] = new $class();
-            $handle->log('connect', $type);
-        }
-
-        return self::$instance[$type];
-    }
-}

+ 0 - 126
src/Dever/Cache/Store/Memcache.php

@@ -1,126 +0,0 @@
-<?php namespace Dever\Cache\Store;
-
-use Dever\Cache\Store;
-
-//class Memcache implements Store
-class Memcache
-{
-    private $class;
-    private $expire;
-
-    public function __construct()
-    {
-        if (class_exists('\Memcached', false)) {
-            $this->class = new \Memcached;
-        } else {
-            $this->class = new \Memcache;
-        }
-    }
-
-    public function connect($config)
-    {
-        if (isset($config["host"])) {
-            $this->expire = $config['expire'];
-
-            $this->class->addServer($config["host"], $config["port"], $config["weight"]);
-        }
-    }
-
-    public function get($key)
-    {
-        if (!$this->class) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $result = $this->class->get($key);
-
-        return $result;
-    }
-
-    public function set($key, $value, $expire = 0)
-    {
-        if (!$this->class) {
-            return false;
-        }
-
-        if (!is_string($key)) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $expire = $expire > 0 ? $expire : $this->expire;
-
-        if (!class_exists('\Memcached', false)) {
-            $result = $this->class->set($key, $value, MEMCACHE_COMPRESSED, $expire);
-        } else {
-            $result = $this->class->set($key, $value, $expire);
-        }
-
-        return $result;
-    }
-
-    public function incr($key, $value)
-    {
-        if (!$this->class) {
-            return false;
-        }
-
-        if (!is_string($key)) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $result = $this->class->increment($key, $value);
-
-        return $result;
-    }
-
-    public function hGet($key, $hkey = false)
-    {
-        return false;
-    }
-
-    public function hSet($key, $hkey, $value, $expire = 0)
-    {
-        return false;
-    }
-
-    public function delete($key)
-    {
-        if (!$this->class) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        if ($this->class->delete($key, 0)) {
-            return true;
-        }
-        return false;
-    }
-
-    public function close()
-    {
-        return;
-        /*
-        if (!$this->class) {
-            return false;
-        }
-
-        if ($this->class->close()) {
-            return true;
-        }
-        */
-        return false;
-    }
-
-    private function key($key)
-    {
-        return 'v1_' . $key;
-        return DEVER_APP_NAME . '_' . $key;
-    }
-}

+ 0 - 185
src/Dever/Cache/Store/Redis.php

@@ -1,185 +0,0 @@
-<?php namespace Dever\Cache\Store;
-
-use Dever\Cache\Store;
-
-class Redis
-{
-    private $redis;
-    private $expire;
-
-    public function __construct()
-    {
-        $this->redis = new \Redis;
-    }
-
-    public function connect($config)
-    {
-        if (isset($config["host"])) {
-            $this->expire = $config['expire'];
-
-            $this->redis->pconnect($config["host"], $config["port"]);
-            if (isset($config['password']) && $config['password']) {
-                $this->redis->auth($config['password']);
-            }
-        }
-    }
-
-    public function getRedis()
-    {
-        return $this->redis;
-    }
-
-    public function get($key)
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $result = $this->redis->get($key);
-
-        return $result;
-    }
-
-    public function set($key, $value, $expire = 0)
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        if (!is_string($key)) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $expire = $expire > 0 ? $expire : $this->expire;
-
-        $result = $this->redis->set($key, $value, $expire);
-
-        return $result;
-    }
-
-    public function incr($key, $value)
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        if (!is_string($key)) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $result = $this->redis->incr($key, $value);
-
-        return $result;
-    }
-
-    public function hGet($key, $hkey = false)
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        if ($hkey) {
-            $result = $this->redis->hGet($key, $hkey);
-        } else {
-            $result = $this->redis->hGetAll($key);
-        }
-        return $result;
-    }
-
-    public function hDel($key, $hkey)
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $result = $this->redis->hDel($key, $hkey);
-        return $result;
-    }
-
-    public function hExists($key, $hkey)
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $result = $this->redis->hExists($key, $hkey);
-        return $result;
-    }
-
-    public function hKeys($key)
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $result = $this->redis->hKeys($key);
-        return $result;
-    }
-
-    public function hSet($key, $hkey, $value, $expire = 0)
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        if (!is_string($key)) {
-            return false;
-        }
-
-        $key = $this->key($key);
-
-        $expire = $expire > 0 ? $expire : $this->expire;
-
-        $result = $this->redis->hSet($key, $hkey, $value);
-
-        return $result;
-    }
-
-    public function delete($key)
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        if (!is_array($key)) {
-            $key = $this->key($key);
-        }
-
-        if ($this->redis->delete($key, 0)) {
-            return true;
-        }
-        return false;
-    }
-
-    public function close()
-    {
-        if (!$this->redis) {
-            return false;
-        }
-
-        if ($this->redis->close()) {
-            return true;
-        }
-        return false;
-    }
-
-    private function key($key)
-    {
-        return 'v1_' . $key;
-        return DEVER_APP_NAME . '_' . $key;
-    }
-}

+ 10 - 22
src/Dever/Config.php

@@ -2,42 +2,30 @@
 class Config
 {
     protected static $data = array();
-    public static function get($key, $app = '', $path = 'config')
+    public static function get($key)
     {
-        if (!$app) {
-            $app = DEVER_APP_NAME;
-        }
-        $index = $app . '_' . $path . '_' . $key;
-        if (empty(self::$data[$index])) {
-            if ($app == DEVER_APP_NAME) {
-                $base = DEVER_APP_PATH;
-            } else {
-                $app = Project::load($app);
-                $base = $app['path'];
-            }
+        if (empty(self::$data[$key])) {
+            $path = DEVER_PROJECT_PATH . 'config' . DIRECTORY_SEPARATOR;
             $env = self::env($path);
-            self::$data[$index] = array();
-            $config = array($base, DEVER_PROJECT_PATH, DEVER_PATH);
-            foreach ($config as $k => $v) {
-                $file = $v . $path . DIRECTORY_SEPARATOR . $key . '.php';
-                if (is_file($file)) {
-                    self::$data[$index] = array_merge(include($file), self::$data[$index]);
-                }
+            $file = $path . $key . '.php';
+            self::$data[$key] = array();
+            if (is_file($file)) {
+                self::$data[$key] = include($file);
             }
         }
-        return self::$data[$index];
+        return self::$data[$key];
     }
     protected static function env($path)
     {
         if (empty($_SERVER['DEVER_ENV_NAME'])) {
-            if (isset($_SERVER['SERVER_NAME']) && $_SERVER['SERVER_NAME'] != '127.0.0.1') {
+            if (isset($_SERVER['SERVER_NAME'])) {
                 $_SERVER['DEVER_ENV_NAME'] = $_SERVER['SERVER_NAME'];
             } else {
                 $_SERVER['DEVER_ENV_NAME'] = 'localhost';
             }
         }
         if (empty($_SERVER['DEVER_ENV_PATH'])) {
-            $_SERVER['DEVER_ENV_PATH'] = DEVER_PROJECT_PATH . $path . DIRECTORY_SEPARATOR . 'env' . DIRECTORY_SEPARATOR;
+            $_SERVER['DEVER_ENV_PATH'] = $path . 'env' . DIRECTORY_SEPARATOR;
         }
         $file = $_SERVER['DEVER_ENV_PATH'] . $_SERVER['DEVER_ENV_NAME'] . '.php';
         if (is_file($file)) {

+ 0 - 195
src/Dever/Data/Elastic/Connect.php

@@ -1,195 +0,0 @@
-<?php namespace Dever\Data\Elastic;
-
-use Dever\Output\Debug;
-use Dever\Http\Curl;
-
-class Connect
-{
-    /**
-     * handle
-     *
-     * @var object
-     */
-    private $handle;
-
-    /**
-     * curl
-     *
-     * @var object
-     */
-    private $curl;
-
-    /**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * getInstance
-     *
-     * @return Dever\Data\Mongo\Connect;
-     */
-    public static function getInstance($config)
-    {
-        $key = $config['host'] . $config['database'];
-        if (empty(self::$instance[$key])) {
-            self::$instance[$key] = new self();
-            self::$instance[$key]->init($config);
-        }
-
-        return self::$instance[$key];
-    }
-
-    /**
-     * init
-     *
-     * @return mixd
-     */
-    private function init($config)
-    {
-        if (strpos($config['host'], ':') !== false) {
-            $this->host = $config['host'];
-        } else {
-            $this->host = $config['host'] . ':' . $config['port'];
-        }
-
-        $this->host = 'http://' . $this->host . '/';
-        $this->handle = $this->host . $config['database'] . '/';
-        $this->curl = new Curl();
-        if (isset($config['username'])) {
-            $setting['UserPWD'] = $config['username'];
-            if (isset($config['password'])) {
-                $setting['UserPWD'] .= ':' . $config['password'];
-            }
-            $this->curl->setting($setting);
-        }
-
-        Debug::log('elastic ' . $config['host'] . ' connected', $config['type']);
-    }
-
-    /**
-     * __destruct
-     *
-     * @return mixd
-     */
-    public function __destruct()
-    {
-        $this->close();
-    }
-
-    /**
-     * handle
-     *
-     * @return object
-     */
-    public function handle($url = '_status', $type = 'get', $param = array(), $state = true)
-    {
-        $url = $this->handle . $url;
-        if (strpos($url, '/scroll')) {
-            $url = $this->host . '_search/scroll';
-        }
-        $this->curl->load($url, $param, $type, true);
-        $result = $this->curl->result(false);
-        if (!$state) {
-            return;
-        }
-        $result = json_decode($result, true);
-        if (isset($result['_scroll_id'])) {
-            $oper = new \Dever\Session\Oper(DEVER_PROJECT, 'cookie');
-            $oper->add('es_scroll', $result['_scroll_id'], 3600);
-        }
-        if (isset($result['hits'])) {
-            $return = array();
-            $return['total'] = $result['hits']['total'];
-            $return['data'] = array();
-            if (isset($param['aggs']) && isset($result['aggregations'])) {
-                $return['data'] = $this->aggregations($result['aggregations']);
-            }
-            if (!$return['data'] && $return['total'] > 0) {
-                foreach ($result['hits']['hits'] as $k => $v) {
-                    $return['data'][$k] = $this->hits($v);
-                }
-            }
-            
-            return $return;
-        }
-
-        if (isset($result['error'])) {
-            $msg = $result['error']['root_cause'][0]['reason'];
-            if ($msg != 'no such index' && strpos($msg, 'unknown setting') === false) {
-                Debug::wait($msg, 'Dever NOSQL DB Error!');
-            } else {
-                return array();
-            }
-        }
-
-        if (isset($result['_id'])) {
-            return $result['_id'];
-        }
-        return $result;
-    }
-
-    /**
-     * hits
-     *
-     * @return mixd
-     */
-    public function hits($v)
-    {
-        $return = $v['_source'];
-        if (isset($return['@timestamp'])) {
-            $return['cdate'] = $return['@timestamp'];
-            unset($return['@timestamp']);
-        }
-        if (isset($v['_score'])) {
-            $return['score'] = $v['_score'];
-        }
-        if (!isset($v['_source']['id']) && isset($v['_id'])) {
-            $return['id'] = $v['_id'];
-        }
-
-        if (isset($v['_source']['add'])) {
-            $return = array_merge($return, $v['_source']['add']);
-            unset($return['add']);
-        }
-
-        if (isset($v['highlight'])) {
-            foreach ($v['highlight'] as $i => $j) {
-                $return['s_' . $i] = $j[0];
-            }
-        }
-        return $return;
-    }
-
-    /**
-     * aggregations
-     *
-     * @return mixd
-     */
-    public function aggregations($aggs)
-    {
-        $return = array();
-        foreach ($aggs as $k => $v) {
-            if (isset($v['buckets'])) {
-                foreach ($v['buckets'] as $i => $j) {
-                    $return[$i] = $j;
-                    $return[$i][$k] = $j['key'];
-                    unset($return[$i]['key']);
-                }
-            }
-        }
-        return $return;
-    }
-
-    /**
-     * close
-     *
-     * @return mixd
-     */
-    public function close()
-    {
-        $this->handle = null;
-    }
-}

+ 0 - 703
src/Dever/Data/Elastic/Store.php

@@ -1,703 +0,0 @@
-<?php namespace Dever\Data\Elastic;
-
-use Dever\Data\Store as Base;
-use Dever\Routing\Input;
-
-class Store extends Base
-{
-    /**
-     * record
-     *
-     * @var array
-     */
-    protected $record;
-
-    /**
-     * init
-     *
-     * @return mixd
-     */
-    public function init()
-    {
-        return;
-    }
-
-    /**
-     * connect
-     *
-     * @return mixd
-     */
-    public function connect($config)
-    {
-        return Connect::getInstance($config);
-    }
-
-    /**
-     * setTable
-     *
-     * @return mixd
-     */
-    public function setTable($table)
-    {
-        $this->table = $table;
-    }
-
-    /**
-     * setTable
-     *
-     * @return mixd
-     */
-    public function createTable($struct)
-    {
-        if ($struct) {
-            $properties = $this->getProperties($struct);
-            if ($properties) {
-                $param['mappings'][$this->alias]['properties'] = $properties;
-            }
-        }
-
-        if (isset($this->config['setting'])) {
-            $param['settings'] = $this->config['setting'];
-        }
-
-        $this->value['method'] = '?pretty';
-        $this->exe('', 'put', $param, false);
-    }
-
-    /**
-     * getProperties
-     *
-     * @return array
-     */
-    private function getProperties($struct)
-    {
-        $properties = array();
-        foreach ($struct as $k => $v) {
-            if (isset($v['type'])) {
-                if ($k == 'cdate') {
-                    $properties['@timestamp']['type'] = 'date';
-                } elseif (strpos($v['type'], 'int') !== false) {
-                    $properties[$k]['type'] = 'long';
-                } elseif (strpos($v['type'], 'char') !== false) {
-                    $properties[$k]['type'] = 'string';
-                } elseif (strpos($v['type'], 'text') !== false) {
-                    $properties[$k]['type'] = 'text';
-                    $properties[$k]['store'] = 'false';
-                    if (isset($this->config['analyzer']) && isset($v['search']) && strstr($v['search'], 'fulltext')) {
-                        $properties[$k]['term_vector'] = 'with_positions_offsets';
-                        $properties[$k]['analyzer'] = $this->config['analyzer'];
-                        $properties[$k]['search_analyzer'] = $this->config['analyzer'];
-                        $properties[$k]['include_in_all'] = 'true';
-                    } else {
-                        $properties[$k]['type'] = 'string';
-                        $properties[$k]['index'] = 'not_analyzed';
-                    }
-                }
-
-                if (isset($v['group'])) {
-                    $properties[$k]['copy_to'] = $v['group'];
-                }
-            }
-        }
-
-        return $properties;
-    }
-
-    /**
-     * getIndex
-     *
-     * @return mixed
-     */
-    public function getIndex($version, $index)
-    {
-        return true;
-    }
-
-    /**
-     * alter table
-     *
-     * @return mixed
-     */
-    public function alter($alter, $struct = array(), $name = '')
-    {
-        return true;
-    }
-
-    /**
-     * query table
-     *
-     * @return mixed
-     */
-    public function query($url = '_status', $type = 'get')
-    {
-        return $this->exe($url, $type);
-    }
-
-    /**
-     * exe
-     *
-     * @return mixed
-     */
-    public function exe($url = '_status', $type = 'get', $param = array(), $state = true)
-    {
-        $this->register();
-        $url = $this->alias . '/' . $url;
-        if (isset($this->value['method'])) {
-            $url = $this->value['method'];
-        }
-        return $this->read->handle($url, $type, $param, $state);
-    }
-
-    /**
-     * insert the default value
-     *
-     * @return mixed
-     */
-    public function getInserts($value)
-    {
-        $col = explode(',', $value['col']);
-        $value = explode(',', $value['value']);
-
-        foreach ($col as $k => $v) {
-            if ($v == 'cdate') {
-                $v = '@timestamp';
-            }
-            $this->value['add'][$v] = $value[$k];
-            $this->insert();
-        }
-
-        $this->log($value, 'inserts');
-
-        $data = include $file;
-
-        $data['insert'] = $value;
-
-        return $data;
-    }
-
-    /**
-     * all
-     *
-     * @return array
-     */
-    public function all($col)
-    {
-        $key = false;
-        if (strpos($col, '|') !== false) {
-            $array = explode('|', $col);
-            $key = $array[1];
-            $col = $array[0];
-        }
-        $data = $this->select($col);
-
-        $result = array();
-
-        if ($data && isset($key)) {
-            foreach ($data as $k => $v) {
-                if (isset($v[$key])) {
-                    if (isset($array[3]) && isset($v[$array[2]])) {
-                        $result[$v[$key]][$v[$array[2]]] = $v;
-                    } elseif (isset($array[2]) && isset($v[$array[2]])) {
-                        $result[$v[$key]] = $v[$array[2]];
-                    } elseif (isset($array[2])) {
-                        $result[$v[$key]][] = $v;
-                    } else {
-                        $result[$v[$key]] = $v;
-                    }
-                } else {
-                    $result[] = $v;
-                }
-            }
-        } else {
-            $result = $data;
-        }
-
-        return $result;
-    }
-
-    /**
-     * one
-     *
-     * @return array
-     */
-    public function one($col = '')
-    {
-        $data = $this->select($col);
-        if ($data && isset($data[0]) && $data[0]) {
-            return $data[0];
-        }
-        return array();
-    }
-
-    /**
-     * count
-     *
-     * @return array
-     */
-    public function count($col = 'clear')
-    {
-        return $this->select($col, true);
-    }
-
-    /**
-     * insert
-     *
-     * @return int
-     */
-    public function insert()
-    {
-        $id = '';
-        if (isset($this->value['add']['id'])) {
-            $id = $this->value['add']['id'];
-        }
-        $state = $this->exe($id, 'post', $this->value['add']);
-
-        $this->log($this->value, 'insert');
-
-        $this->value = array();
-
-        return $state;
-    }
-
-    /**
-     * update
-     *
-     * @return int
-     */
-    public function update()
-    {
-        $set = $this->value['set'];
-        unset($this->value['set']);
-        $this->value['set']['script']['inline'] = implode(';', $this->value['script']);
-        $this->value['set']['script']['params'] = $set;
-
-        if (isset($this->value['where']['id']) && is_numeric($this->value['where']['id']) && $this->value['where']['id'] > 0) {
-            $state = $this->exe($this->value['where']['id'] . '/_update/', 'post', $this->value['set']);
-        } else {
-            if (isset($this->value['search'])) {
-                $this->value['set'] = array_merge($this->value['set'], $this->value['search']);
-            }
-            $state = $this->exe('_update_by_query/', 'post', $this->value['set']);
-        }
-
-        $this->log($this->value, 'update');
-
-        $this->value = array();
-
-        return $state;
-    }
-
-    /**
-     * delete
-     *
-     * @return int
-     */
-    public function delete()
-    {
-        $id = $this->value['where']['id'];
-
-        $state = $this->exe($id, 'delete');
-
-        $this->log($this->value, 'delete');
-
-        $this->value = array();
-
-        return $state;
-    }
-
-    /**
-     * select
-     *
-     * @return array
-     */
-    private function select($col = '', $record = false)
-    {
-        if (isset($this->record) && $this->record) {
-            return $this->record;
-        }
-
-        if ($col && $col != '*' && $col != 'clear') {
-            $this->value['search']['_source'] = explode(',', $col);
-        }
-
-        if (!isset($this->value['search'])) {
-            $this->value['search'] = array();
-        } else {
-            $this->highlight();
-        }
-
-        if (!isset($this->value['search']['sort'])) {
-            $this->value['search']['sort'] = array
-            (
-                '@timestamp' => array('order' => 'desc'),
-            );
-        }
-
-        $return = $this->exe('_search/?pretty', 'post', $this->value['search']);
-        if (!isset($return['data'])) {
-            return array();
-        }
-
-        $this->record = false;
-
-        $this->log($this->value, 'select');
-        if ($col != 'clear') {
-            $this->value = array();
-        }
-
-        if ($record) {
-            $this->record = $return['data'];
-            return $return['total'];
-        }
-        return $return['data'];
-    }
-
-    /**
-     * highlight
-     *
-     * @return object
-     */
-    private function highlight()
-    {
-        if (isset($this->config['highlight'])) {
-            if (is_array($this->config['highlight'])) {
-                $this->value['search']['highlight'] = $this->config['highlight'];
-            }
-        } else {
-            //$object = (object) array();
-            $object['fragment_size'] = 10000000;
-            $object['number_of_fragments'] = 1;
-            $this->value['search']['highlight'] = array
-            (
-                'pre_tags' => array('<em class="dever_highlight">'),
-                'post_tags' => array('</em>'),
-                'fields' => array('desc' => $object),
-            );
-        }
-    }
-
-    /**
-     * join
-     *
-     * @return object
-     */
-    public function join($param)
-    {
-        return $this;
-    }
-
-    /**
-     * __call
-     *
-     * @return object
-     */
-    public function __call($method, $param)
-    {
-        if (is_array($param[0]) && $method != 'group') {
-            foreach ($param[0] as $k => $v) {
-                if ($method == 'order') {
-                    $this->call($method, array($k, $v));
-                } else {
-                    $this->call($method, $v);
-                }
-            }
-        } else {
-            $this->call($method, $param);
-        }
-
-        return $this;
-    }
-
-    /**
-     * call
-     *
-     * @return mixd
-     */
-    private function call($method, $param)
-    {
-        if (is_array($param) && isset($param[0])) {
-            $func = 'convert_' . $method;
-            if ($param[0] == 'cdate') {
-                $param[0] = '@timestamp';
-            }
-            if (method_exists($this, $func)) {
-                $this->$func($param);
-            }
-            if (isset($param[1])) {
-                $this->value[$method][$param[0]] = $param[1];
-            }
-        } else {
-            $this->value[$method] = $param;
-        }
-    }
-
-    /**
-     * convert_order
-     *
-     * @return mixed
-     */
-    private function convert_set($param)
-    {
-        if (empty($param[2])) {
-            $param[2] = '=';
-        }
-        if (strpos($param[2], 'ctx.')) {
-            $this->value['script'][] = $param[2];
-        } else {
-            $this->value['script'][] = 'ctx._source.' . $param[0] . $param[2] . 'params.' . $param[0];
-        }
-    }
-
-    /**
-     * convert_order
-     *
-     * @return mixed
-     */
-    private function convert_order($param)
-    {
-        if ($param[0] == 'id') {
-            $param[0] = '_score';
-        }
-        $this->value['search']['sort'] = array
-        (
-            $param[0] => array('order' => $param[1]),
-        );
-
-        //$this->value['search']['sort'] = array('_doc');
-    }
-
-    /**
-     * convert_limit
-     *
-     * @return mixed
-     */
-    private function convert_limit($param)
-    {
-        if (is_string($param[0]) && strpos($param[0], ',') !== false) {
-            $param = explode(',', $param[0]);
-        }
-
-        $this->value['search']['from'] = $param[0];
-        $this->value['search']['size'] = $param[1];
-
-        $scroll = Input::get('es_scroll');
-        if ($scroll) {
-            if ($param[0] == 0) {
-                $this->value['method'] = $this->alias . '/_search?scroll=5m';
-            } else {
-                $oper = new \Dever\Session\Oper(DEVER_PROJECT, 'cookie');
-                $scroll = $oper->get('es_scroll');
-                $this->value['method'] = '_search/scroll';
-                $this->value['search'] = array
-                (
-                    'scroll' => '5m',
-                    'scroll_id' => $scroll,
-                );
-            }
-        }
-    }
-
-    /**
-     * convert_group
-     *
-     * @return mixed
-     */
-    private function convert_group($param)
-    {
-        //'group' => array('name', array('child' => array('cdate'))),
-        $group = $param[0];
-        if (is_string($group)) {
-            
-            $keyword = $this->group_aggs_keyword($group);
-            $this->value['search']['aggs'][$group]['terms'] = array
-            (
-                'field' => $keyword,
-                'order' => array('_count' => 'desc'),
-                //'min_doc_count' => 2,
-                //'execution_hint' => 'map',
-            );
-
-            if (isset($this->value['search']['size'])) {
-                $this->value['search']['aggs'][$group]['terms']['size'] = $this->value['search']['size'];
-            }
-
-            if (isset($param[1]) && $param[1]) {
-                if (isset($param[1]['aggs'])) {
-                    $this->value['search']['aggs'][$group]['aggs'] = $param[1]['aggs'];
-                    unset($param[1]['aggs']);
-                } elseif (isset($param[1]['child'])) {
-                    $aggs = array();
-                    if (isset($param[1]['child_size'])) {
-                        $child_size = $param[1]['child_size'];
-                        unset($param[1]['child_size']);
-                    }
-                    foreach ($param[1]['child'] as $k => $v) {
-                        if (is_array($v)) {
-                            $aggs[$key][$k] = $v;
-                        } else {
-                            $key = $v;
-                            $k = 'terms';
-                            $v = $this->group_aggs_keyword($v);
-                            $aggs[$key][$k]['field'] = $v;
-                            if (isset($child_size)) {
-                                $aggs[$key][$k]['size'] = $child_size;
-                            }
-                        }
-                    }
-                    $this->value['search']['aggs'][$group]['aggs'] = $aggs;
-                    unset($param[1]['child']);
-                }
-                $this->value['search']['aggs'][$group]['terms'] = array_merge($this->value['search']['aggs'][$group]['terms'], $param[1]);
-            }
-            //$this->value['search']['size'] = 0;
-        } else {
-            $this->value['search']['aggs'] = $group;
-        }
-        
-        
-        //$map['properties'][$group]['type'] = 'text';
-        //$map['properties'][$group]['fielddata'] = true;
-        //$this->exe('_mapping', 'put', $map);
-        //print_r($this->value);
-    }
-
-    /**
-     * group_aggs_keyword
-     *
-     * @return string
-     */
-    private function group_aggs_keyword($group)
-    {
-        if (strpos($group, '.')) {
-            $keyword = $group;
-        } else {
-            $keyword = $group;
-        }
-
-        return $keyword;
-    }
-
-    /**
-     * convert_where
-     *
-     * @return mixed
-     */
-    private function convert_where($param)
-    {
-        //print_r($param);die;
-        $type = 'bool';
-        $method = '';
-        if (isset($param[2])) {
-            $method = $param[2];
-        }
-
-        if (!isset($param[3])) {
-            $param[3] = 'and';
-        }
-        $bool = $this->bool($param[3]);
-        if (!isset($this->value['search']['query'][$type][$bool])) {
-            $this->value['search']['query'][$type][$bool] = array();
-        }
-        $index = count($this->value['search']['query'][$type][$bool]);
-        $this->value['search']['query'][$type][$bool][$index] = $this->value($param[0], $param[1], $method);
-    }
-
-    /**
-     * value
-     */
-    private function value($key, $value, $method)
-    {
-        if ($key == 'id') {
-            $key = '_id';
-        }
-        $result = array();
-        if (!$method) {
-            $result['match_phrase'][$key]['query'] = $value;
-            //$result['match_phrase'][$key]['analyzer'] = 'not_analyzed';
-            $result['match_phrase'][$key]['slop'] = 1;
-        } elseif ($method && $method == 'like') {
-            $result['query_string']['default_field'] = $key;
-            $result['query_string']['query'] = $value;
-        } else {
-            $method = $this->method($method, $key, $value);
-            $result[$method[0]][$key] = $method[1];
-        }
-
-        return $result;
-    }
-
-    /**
-     * bool
-     */
-    private function bool($value)
-    {
-        if (stripos($value, 'or') !== false) {
-            return 'should';
-        } elseif (stripos($value, 'not') !== false) {
-            return 'must_not';
-        } else {
-            return 'must';
-        }
-    }
-    
-    /**
-     * method
-     */
-    private function method($method, $key, $value)
-    {
-        /*
-        if ($key == '@timestamp') {
-            $value = date('c', $value);
-        }
-        */
-        switch ($method) {
-            case 'like':
-                $method = 'wildcard';
-                $value = $value . '*';
-                break;
-            case 'in':
-                $method = 'terms';
-                $value = explode(',', $value);
-                break;
-            case 'nin':
-                $method = 'terms';
-                $value = explode(',', $value);
-                break;
-            case '>':
-                $method = 'range';
-                $range['gt'] = $value;
-                $value = $range;
-                break;
-            case '>=':
-                $method = 'range';
-                $range['gte'] = $value;
-                $value = $range;
-                break;
-            case '<':
-                $method = 'range';
-                $range['lt'] = $value;
-                $value = $range;
-                break;
-            case '<=':
-                $method = 'range';
-                $range['lte'] = $value;
-                $value = $range;
-                break;
-            case '==':
-            case '=':
-                $method = 'range';
-                $range['gte'] = $value;
-                $range['lte'] = $value;
-                $value = $range;
-                break;
-            case '!=':
-                $method = 'range';
-                $range['gt'] = $value;
-                $range['lt'] = $value;
-                $value = $range;
-                break;
-        }
-        
-        return array($method, $value);
-    }
-}

+ 0 - 51
src/Dever/Data/Migration.php

@@ -1,51 +0,0 @@
-<?php namespace Dever\Data;
-
-use Dever;
-
-class Migration
-{
-    protected $num;
-    protected $class;
-    protected $method;
-    protected $type;
-
-    public function __construct($num = 1000)
-    {
-        $this->num = $num;
-    }
-
-    public function action($class, $method, $type, $num = false)
-    {
-        $limit = 0;
-        $this->num = $num > 0 ? $num : $this->num;
-        $this->class = $class;
-        $this->method = $method;
-        $this->type = $type;
-        while($this->handle($limit, $this->num))
-        {
-            $limit += $num;
-        }
-
-        return $limit;
-    }
-
-    private function handle($limit, $num)
-    {
-        $param['limit'] = array($num, $limit);
-
-        $data = Dever::load($this->type, $param);
-
-        if(!$data)
-        {
-            return false;
-        }
-
-        $method = $this->method;
-        foreach($data as $k => $v)
-        {
-            $this->class->$method($v);
-        }
-
-        return true;
-    }
-}

+ 0 - 574
src/Dever/Data/Model.php

@@ -1,574 +0,0 @@
-<?php
-/**
- * This file is part of Dever.
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the MIT-LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @author    rabin<rabin@shemic.com>
- * @copyright rabin<rabin@shemic.com>
- * @link      http://www.dever.cc/
- * @license   http://www.opensource.org/licenses/mit-license.php MIT License
- */
-namespace Dever\Data;
-
-use Dever;
-use Dever\Config;
-use Dever\Project;
-use Dever\Import;
-use Dever\Output;
-use Dever\Route;
-use Dever\String\Helper;
-/**
- * Class Model
- * @package Dever
- */
-class Model
-{
-    /**
-     * @var array
-     */
-    public $config;
-
-    /**
-     * @var array
-     */
-    protected $data;
-
-    /**
-     * @var string
-     */
-    protected $index;
-
-    /**
-     * @var string
-     */
-    protected $table;
-
-    /**
-     * @var string
-     */
-    const TABLE = 'table/';
-
-    /**
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * @var string
-     */
-    protected static $key;
-
-    /**
-     * load
-     * @param string $table
-     * @param string $app
-     * @return mixed
-     */
-    public static function load($table, $app = '')
-    {
-        list($table, $index, $method) = self::table($table);
-        $key = $table . '_' . $index . '_' . $key;
-        if (empty(static::$instance[$key])) {
-            static::$instance[$key] = new static($table, $index);
-        }
-        if ($method) {
-            return static::$instance[$key]->$method($param);
-        }
-        return static::$instance[$key];
-    }
-
-    /**
-     * table
-     * @param array $param
-     * @return array
-     */
-    public static function table($table)
-    {
-        $index = $method = '';
-        self::$key = $table;
-        if (strpos($table, '-')) {
-            list($table, $method) = explode('-', $table);
-        }
-        if (strpos($table, ':')) {
-            list($table, $index) = explode(':', $table);
-        }
-        return array($table, $index, $method);
-    }
-
-    /**
-     * closeAll
-     */
-    public static function closeAll()
-    {
-        if (static::$instance) {
-            foreach (static::$instance as $k => $v) {
-                static::$instance[$k] = null;
-                unset(static::$instance[$k]);
-            }
-        }
-    }
-
-    /**
-     * __construct
-     * @param string $table
-     * @param string $index
-     */
-    public function __construct($table, $index = '')
-    {
-        $this->table = $table;
-        $this->index = $index;
-        if (!$this->table) {
-            $this->config['name'] = 'table';
-            $this->config['project'] = '';
-            $this->config['db'] = '';
-        } else {
-            $this->loadConfig();
-        }
-    }
-
-    /**
-     * loadConfig
-     */
-    protected function loadConfig()
-    {
-        list($project, $table) = explode('/', $this->table);
-        $this->config['project'] = Project::load($project);
-        if (!$project) {
-            $path = '';
-            $this->config['link'] = true;
-        } else {
-            $path = $project['path'] . self::TABLE;
-            $this->config['link'] = false;
-        }
-
-        if ($this->index) {
-            $path .= $this->index . '/';
-            $this->config['db_prefix'] = $this->config['db'] = $this->index;
-        } else {
-            $this->config['db'] = $projectName;
-        }
-
-        $file = $path . $table . '.php';
-        echo $file;die;
-        
-        if (is_file($file)) {
-            $this->config = $this->loadFile($file);
-        } else {
-            $this->config['name'] = $tableName;
-        }
-        $this->config['project'] = $project;
-    }
-
-    private function loadFile($file)
-    {
-        $config = include $file;
-        if (isset($config['struct']) && isset($config['lang']) && $config['lang'] && $pack =Config::get('setting')->lang_pack) {
-            foreach ($config['lang'] as $lang) {
-                if (isset($config['struct'][$lang])) {
-                    foreach (Config::get('setting')->lang_pack as $key => $value) {
-                        if (Config::get('setting')->lang != $key) {
-                            $config['struct'][$key . '_' . $lang] = $config['struct'][$lang];
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * db
-     *
-     * @return mixd
-     */
-    private function db()
-    {
-        return Model\Database::get($this->config['db']);
-    }
-
-    /**
-     * query
-     *
-     * @return mixd
-     */
-    public function query($sql, $data = array(), $method = '')
-    {
-        if (strstr($sql, '{project}')) {
-            if (isset($this->config['struct'])) {
-                $sql = Helper::replace('{project}', $this->config['project']['name'], $sql);
-            } else {
-                $sql = Helper::replace('{project}_', '', $sql);
-            }
-        }
-        $this->sql = Helper::replace('{table}', $this->getTableName(), $sql);
-        return $this->db()->exe($this->sql, $data, $method);
-    }
-
-    /**
-     * getTableName
-     *
-     * @return mixd
-     */
-    private function getTableName()
-    {
-        $prefix = '';
-        if (defined('DEVER_PROJECT')) {
-            $prefix = DEVER_PROJECT . '_';
-        }
-        if (isset($this->config['struct'])) {
-            return $prefix . $this->config['project']['name'] . '_' . $this->config['name'];
-        } else {
-            return $this->config['name'];
-        }
-    }
-
-    /**
-     * fetch
-     *
-     * @return mixd
-     */
-    public function fetch($sql, $data = array(), $cache = false)
-    {
-        return $this->fetchAll($sql, $data, false, $cache, 'fetch');
-    }
-
-    /**
-     * setTable
-     *
-     * @return mixd
-     */
-    private function setTable($sql)
-    {
-        $table = $sql;
-        //$this->db()->setTable($table);
-    }
-
-    /**
-     * fetchAll
-     *
-     * @return mixd
-     */
-    public function fetchAll($sql, $data = array(), $page = array(), $cache = false, $method = 'fetchAll')
-    {
-        $this->setTable($sql);
-
-        if (!$cache && !empty(Config::get('cache')->mysql)) {
-            $cache = 'getSql_' . md5($sql . serialize($data));
-            if ($page && $p = Input::get('page')) {
-                $cache .= '_p' . $p;
-            }
-        }
-
-        if ($cache) {
-            $result = $this->db()->cache($cache);
-            if ($result) {
-                return $result;
-            }
-        }
-
-        if ($page) {
-            $result = $this->page($page, $sql, $data);
-        } else {
-            $result = $this->query($sql, $data)->$method();
-        }
-        
-        if ($cache) {
-            $this->db()->cache($cache, $result);
-        } else {
-            $this->db()->log($this->sql, $data, $result);
-        }
-
-        return $result;
-    }
-
-    /**
-     * rowCount
-     *
-     * @return mixd
-     */
-    public function rowCount($sql, $data = array())
-    {
-        return $result = $this->query($sql, $data)->rowcount();
-    }
-
-    /**
-     * lastId
-     *
-     * @return mixd
-     */
-    public function lastId($sql, $data = array())
-    {
-        return $result = $this->query($sql, $data)->id();
-    }
-
-    /**
-     * page
-     *
-     * @return array
-     */
-    public function page($config = array(), $sql = false, $data = array())
-    {
-        return $this->db()->getPageBySql($config, $sql, $data, $this);
-    }
-
-    /**
-     * index
-     *
-     * @return array
-     */
-    public function index($index)
-    {
-        return $this->db()->index($index);
-    }
-
-    /**
-     * transaction begin
-     *
-     * @return array
-     */
-    public function begin()
-    {
-        return $this->db()->begin();
-    }
-
-    /**
-     * transaction commit
-     *
-     * @return array
-     */
-    public function commit()
-    {
-        return $this->db()->commit();
-    }
-
-    /**
-     * transaction rollback
-     *
-     * @return array
-     */
-    public function rollback()
-    {
-        return $this->db()->rollback();
-    }
-
-    /**
-     * __call
-     *
-     * @return mixd
-     */
-    public function __call($method, $param)
-    {
-        if (isset($param[0][0]) && is_array($param[0][0])) {
-            $result = array();
-            foreach ($param[0] as $k => $v) {
-                $result[] = $this->$method($v);
-            }
-            
-            return $result;
-        }
-
-        $call = false;
-        if (isset($param[1])) {
-            if (is_object($param[1])) {
-                $call = $param[1];
-            } elseif ($method == 'insert') {
-                $param[0]['insert_value_num'] = $param[1];
-            }
-        }
-
-        $param = $param ? $this->initParam($param[0], $method) : array();
-
-        $key = $this->table . $method . md5(serialize($param));
-        if (isset($param['clear']) && $param['clear'] && isset($this->data[$key])) {
-            unset($this->data[$key]);
-        }
-
-        $this->compatible($key, $method, $param);
-
-        if (!isset($this->data[$key])) {
-            $this->request($method, $param);
-            if (isset($this->config['request'][$method]['type']) && in_array($this->config['request'][$method]['type'], array('update', 'insert'))) {
-                return $this->callData($method, $param, $call);
-            }
-            $this->data[$key] = $this->callData($method, $param, $call);
-        }
-
-        return $this->data[$key];
-
-    }
-
-    /**
-     * getData
-     *
-     * @return mixd
-     */
-    private function callData($method, $param, $call = false)
-    {
-        $param = $this->search($method, $param);
-        $handle = new Model\Handle($method, $this->config, $param, $call);
-        return $handle->get();
-    }
-
-    /**
-     * compatible
-     *
-     * @return mixd
-     */
-    protected function compatible($key, $method, $param)
-    {
-        if (Config::get('database')->compatible && isset($this->config['project'])) {
-            $file = $this->config['project']['path'] . 'database/' . ucfirst(Config::get('database')->compatible) . '/' . ucfirst($this->config['name']) . '.php';
-            if (is_file($file)) {
-                $class = ucfirst($this->config['project']['name']) . '\\Database\\' . ucfirst(Config::get('database')->compatible) . '\\' . ucfirst($this->config['name']);
-                if (class_exists($class) && method_exists($class, $method)) {
-                    $this->data[$key] = $class::$method($param);
-                }
-            }
-        }
-    }
-
-    /**
-     * request
-     *
-     * @return mixd
-     */
-    protected function request($method, $param)
-    {
-        if (!isset($this->config['struct'])) {
-            $this->config['struct'] = array();
-        }
-        if (empty($this->config['request'][$method]) && isset($this->config['struct'])) {
-            $search = '';
-            if (isset($param['search_type'])) {
-                $search = $param['search_type'];
-            }
-
-            $this->config['request'][$method] = Model\Request::get($this->table, $method, $this->config['struct'], $search);
-
-            if ($method == 'list' && isset($this->config['manage']['list_type']) && $this->config['manage']['list_type']) {
-                $this->config['request']['list']['page'][0] = 50000;
-            }
-
-
-            if (isset($this->config['request'][$method]['type']) && isset($this->config['request'][$method]['option']) && $this->config['request'][$method]['type'] == 'all' && isset($this->config['request'][$method . '_option'])) {
-
-                $this->config['request'][$method]['option'] = array_merge($this->config['request'][$method]['option'], $this->config['request'][$method . '_option']);
-            }
-        }
-
-        if (isset($param['config']) && isset($this->config['request'][$method]['config']) && $this->config['request'][$method]['config']) {
-            $this->config['request'][$method] = array_merge($this->config['request'][$method], $param['config']);
-            unset($param['config']);
-            unset($this->config['request'][$method]['config']);
-        }
-
-        if (in_array($method, array('all', 'state', 'total', 'list', 'find')) && isset($param['option'])) {
-            foreach ($param['option'] as $k => $v) {
-                $this->config['request'][$method]['option'][$k] = $v;
-            }
-        }
-        if ($method == 'list') {
-            $search = Dever::search_button();
-            if ($search) {
-                $this->config['request']['list']['group'] = $search[0];
-                $this->config['request']['list']['col'] = $search[1];
-            }
-        }
-
-        if (isset($param['join'])) {
-            $this->config['request'][$method]['join'] = $param['join'];
-            if (isset($this->config['request'][$method]['option'])) {
-                foreach ($this->config['request'][$method]['option'] as $k => $v) {
-                    if (is_string($v) && !strstr($v, 't_1') && !strstr($k, '-')) {
-                        $this->config['request'][$method]['option'][$k] = 'yes-t_1.' . $k;
-                    }
-                    if (is_array($v) && !strstr($v[0], 't_1')) {
-                        if (strstr($v[0], '-')) {
-                            $temp = explode('-', $v[0]);
-                            $this->config['request'][$method]['option'][$k][0] = 'yes-t_1.' . $temp[1];
-                        } else {
-                            $this->config['request'][$method]['option'][$k][0] = 'yes-t_1.' . $k;
-                        }
-                    }
-                }
-            }
-        }
-
-        if (DEVER_APP_NAME != 'manage') {
-            $lang = Dever::langConfig();
-            if (Dever::config('base')->lang && $lang && $lang != Dever::config('base')->lang && isset($this->config['manage']['lang']) && $this->config['manage']['lang']) {
-                $col = array();
-                foreach ($this->config['manage']['lang'] as $k => $v) {
-                    $col[] = $lang . '_' . $v . ' as `' . $v . '`';
-                }
-                if (!isset($this->config['request'][$method]['col'])) {
-                    $this->config['request'][$method]['col'] = '*';
-                }
-                $this->config['request'][$method]['col'] .= ',' . implode(',', $col);
-            }
-        }
-    }
-
-    /**
-     * search
-     *
-     * @return mixd
-     */
-    protected function search($method, $param)
-    {
-        if (isset($param['search_type']) && $param['search_type'] == 2) {
-            $join = array();
-            $i = 2;
-            foreach ($param as $k => $v) {
-                if (strpos($k, '-') !== false) {
-                    $k = str_replace(array('option_', 'where_'), '', $k);
-                    if (isset($this->config['struct'][$k]) && isset($this->config['struct'][$k]['sync'])) {
-                        $temp = explode('-', $k);
-                        $join[] = array
-                        (
-                            'table' => $temp[0] . '/' . $temp[1],
-                            'type' => 'left join',
-                            'on' => $this->config['struct'][$k]['sync'],
-                        );
-
-                        $t = 't_' . $i . '.' . $temp[2];
-                        $this->config['request'][$method]['option'][$t] = $this->config['request'][$method]['option'][$k];
-                        $param['option_' . $t] = $param['option_' . $k];
-                        unset($this->config['request'][$method]['option'][$k]);
-                        unset($param['option_' . $k]);
-                        $i++;
-                    }
-                }
-            }
-            if ($join) {
-                $this->config['request'][$method]['join'] = $join;
-            }
-        }
-
-        return $param;
-    }
-
-    protected function searchFulltext($k, $param)
-    {
-
-    }
-
-    /**
-     * initParam
-     *
-     * @return mixd
-     */
-    private function initParam($param, $method)
-    {
-        if ($param && !is_array($param)) {
-            if ($this->config['link']) {
-                $param = array('id' => $param);
-            } else {
-                $param = array('where_id' => $param, 'option_id' => $param);
-            }
-        }
-        return $param;
-    }
-}

+ 0 - 577
src/Dever/Data/Model/Condition.php

@@ -1,577 +0,0 @@
-<?php namespace Dever\Data\Model;
-
-use Dever;
-use Dever\Loader\Project;
-use Dever\Loader\Config;
-use Dever\Routing\Input;
-use Dever\Output\Export;
-use Dever\Support\Env;
-use Dever\Loader\Import;
-
-class Condition
-{
-    /**
-     * method
-     *
-     * @var array
-     */
-    const METHOD = 'where,option,set,add,order,limit,group,page';
-
-    /**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * load
-     *
-     * @return mixed
-     */
-    public static function get()
-    {
-        if (empty(self::$instance)) {
-            self::$instance = new self();
-        }
-
-        return self::$instance;
-    }
-
-    /**
-     * method
-     *
-     * @return mixd
-     */
-    public function init($request, $struct, $param, $project, $name, $db)
-    {
-        $this->request = $request;
-        $this->param = $param;
-        $this->struct = $struct;
-        $this->project = $project;
-        $this->name = $name;
-        $this->db = $db;
-        $this->update = false;
-
-        $this->join();
-        $method = explode(',', self::METHOD);
-       
-        foreach ($method as $one) {
-            if (isset($this->request[$one])) {
-                if (method_exists($this, $one)) {
-                    $this->$one($this->request[$one]);
-                } else {
-                    if ($one == 'set' || $one == 'add') {
-                        $this->update = true;
-                    }
-                    $this->handle($this->request[$one], $one);
-                }
-            }
-        }
-    }
-
-    /**
-     * order
-     *
-     * @return mixd
-     */
-    protected function method($config, $method)
-    {
-        if (isset($this->request['input'])) {
-            $config = Input::get($method, $config);
-        } elseif (isset($this->param[$method])) {
-            $config = $this->param[$method];
-        }
-
-        if (is_string($config)) {
-            $config = array($config, '');
-        }
-
-        if(empty($config[0])) $config[0] = $config;
-        if(empty($config[1])) $config[1] = '';
-
-        $this->opt($method, $config);
-
-        Database::get($this->db)->$method($config[0], $config[1]);
-    }
-
-    /**
-     * order
-     *
-     * @return mixd
-     */
-    protected function order($config)
-    {
-        $this->method($config, 'order');
-    }
-
-    /**
-     * limit
-     *
-     * @return mixd
-     */
-    protected function limit($config)
-    {
-        $this->method($config, 'limit');
-    }
-
-    /**
-     * group
-     *
-     * @return mixd
-     */
-    protected function group($config)
-    {
-        $this->method($config, 'group');
-    }
-
-    /**
-     * page
-     *
-     * @return mixd
-     */
-    protected function page($config)
-    {
-        if (!$config) {
-            return;
-        }
-        if (is_string($config[1])) {
-            $temp[] = $config[1];
-            unset($config[1]);
-            $config[1] = $temp;
-        }
-
-        if (isset($this->param['page']) && $this->param['page'] && $this->param['page'] != $config) {
-            $config[0] = $this->param['page'][0];
-            unset($this->param['page'][0]);
-            if (isset($this->param['page'][1])) {
-                $config[1] = array_merge(array(), $this->param['page']);
-            }
-        }
-
-        if(isset($config[2])) $config[1][2] = $config[2];
-
-        $this->opt('page', $config);
-
-        Database::get($this->db)->page($config[0], $config[1]);
-    }
-
-    /**
-     * handle
-     *
-     * @return mixd
-     */
-    protected function handle($config, $method)
-    {
-        $send = array();
-        if (!$config && isset($this->param)) {
-            # 以后可以优化这里
-            foreach ($this->param as $k => $v) {
-                /*
-                $k = str_replace(array('option_', 'where_', 'add_', 'set_'), '', $k);
-                if ($method == 'set' && $k == 'id') {
-                    continue;
-                }
-                $config[$k] = $v;
-                */
-
-                $s = $method . '_';
-                if (strstr($k, $s)) {
-                    $k = str_replace($s, '', $k);
-                    if ($method == 'set' && $k == 'id') {
-                        continue;
-                    }
-                    $config[$k] = $v;
-                }
-            }
-        }
-
-        if (isset($config['option'])) {
-            unset($config['option']);
-        }
-        foreach ($config as $key => $value) {
-            $temp = array();
-            if (is_array($value)) {
-                $temp = $value;
-                $value = $temp[0];
-                if ($this->update && empty($this->param[$key]) && ($temp[1] != '+=' && $temp[1] != '-=')) {
-                    $this->param[$key] = $temp[1];
-                }
-            }
-
-            $index = $key;
-
-            $input = $this->input($method . '_' . $index, $value, '', $key, $method);
-            //if ($this->update && !$input) {
-            if (!$input && !Env::zero($input)) {
-                $input = $this->input($index, $value, '', $key, $method);
-                if ($method == 'add' && !$input && isset($this->struct[$key]['default']) && $this->struct[$key]['default']) {
-                    $input = $this->struct[$key]['default'];
-                }
-            }
-
-            if ($input || Env::zero($input)) {
-                if (is_array($input)) {
-                    if (isset($this->struct[$key]) && isset($this->struct[$key]['bit'])) {
-                        $vt = 0;
-                        foreach ($input as $ki => $vi) {
-                            if (isset($this->struct[$key]['bit'][$vi])) {
-                                $vt += $this->struct[$key]['bit'][$vi];
-                            }
-                        }
-                        $input = $vt;
-                    } elseif (isset($input[0]) && is_array($input[0])) {
-                        $input = base64_encode(json_encode($input, JSON_UNESCAPED_UNICODE));
-                    } else {
-                        $input = str_replace(',0', '', implode(',', $input));
-                    }
-                }
-
-
-                if ($input === 'null') {
-                    $input = '';
-                }
-
-
-
-                if ($method == 'set') {
-                    if ($input && ($input == '+=' || $input == '-=')) {
-                        $input = '';
-                    }
-                }
-
-                /*
-                if (isset($this->struct[$key]) && isset($this->struct[$key]['type']) && $key != 'id') {
-                    if (strpos($this->struct[$key]['type'], 'int') !== false && !is_object($input) && $input > 0) {
-                        $input = (int) $input;
-                    } else {
-                        $input = (string) $input;
-                    }
-                }
-                */
-
-                $result = array($key, $input);
-                if (isset($temp[1]) && $temp[1] != $input) {
-                    $result[2] = $temp[1];
-                }
-                if (isset($temp[2])) {
-                    $result[3] = $temp[2];
-                }
-                $send[] = $result;
-            }
-        }
-
-        if ($send) {
-            if ($method == 'option') {
-                $method = 'where';
-            }
-
-            $this->opt($method, $send);
-            Database::get($this->db)->$method($send);
-        }
-    }
-
-    /**
-     * opt
-     *
-     * @return mixd
-     */
-    private function opt($method, $param)
-    {
-        if (Project::load('manage') && Config::get('database')->opt && $this->project . $this->name != 'manageopt') {
-            if ($method == 'where') {
-                $col = array();
-                foreach ($param as $k => $v) {
-                    $col[] = $v[0];
-                }
-            } elseif ($method == 'order') {
-                $col = $param[0];
-                if (is_string($col)) {
-                    if (strpos($col, '`') !== false) {
-                        $col = str_replace(array('`', 'desc', 'asc', ' '), '', $col);
-                    }
-
-                    $col = explode(',', $col);
-                } elseif (is_array($col)) {
-                    foreach ($col as $k => $v) {
-                        $col[] = $k;
-                    }
-                }
-            }
-            
-            if (isset($col) && $col) {
-                Opt::push($this->project, $this->name, $col);
-            }
-        }
-    }
-
-    /**
-     * join
-     *
-     * @return mixd
-     */
-    protected function join()
-    {
-        if (isset($this->request['join']) && $this->request['join']) {
-            Database::get($this->db)->join($this->request['join']);
-        }
-    }
-
-    /**
-     * input
-     *
-     * @return mixd
-     */
-    private function input($key, $value, $split = '', &$index, $method = '')
-    {
-        if (isset($this->param[$key])) {
-            $request = $this->param[$key];
-        } elseif (isset($this->param[$index])) {
-            $request = $this->param[$index];
-        }
-
-        if (isset($request) && Env::zero($request)) {
-            return $request;
-        }
-
-        list($index, $value, $callback, $state) = $this->config($index, $value, $method);
-
-        if (empty($request)) {
-            if (isset($this->request['input'])) {
-                $request = Input::get($key, $value);
-            } else {
-                $request = $value;
-            }
-        }
-
-        if (is_array($request)) {
-            if (count($request) == count($request, 1)) {
-                $request = implode(',', $request);
-            } else {
-                $request = Dever::json_encode($request);
-            }
-        }
-
-
-
-        /*
-        if (is_array($request) && isset($request[0]) && !is_array($request[0])) {
-            $request = implode(',', $request);
-        }
-        */
-
-        if (is_string($value) && strpos($value, '/') === 0) {
-            $state = preg_match($value, $request);
-        } elseif (!empty($request)) {
-            if ($callback) {
-                $state = $callback($request);
-            } elseif (is_string($request) && $split && strpos($request, $split) !== false) {
-                $request = explode($split, $request);
-            }
-
-            $state = true;
-        }
-
-        if ($state) {
-            return $this->request($index, $request, $method);
-        }
-
-        if ($method != 'option' && !$this->update) {
-            if (isset($this->struct[$index]['desc']) && $this->struct[$index]['desc']) {
-                Export::alert($this->struct[$index]['desc']);
-            } else {
-                $alert = $this->struct[$index]['name'];
-                if ($alert) {
-                    Export::alert($alert . '不能为空或填写错误');
-                } else {
-                    Export::alert('core_database_request', array($key, ($value ? $value : $callback)));
-                }
-            }
-        }
-
-        return false;
-    }
-
-    /**
-     * config
-     *
-     * @return mixd
-     */
-    private function config($index, $value, $method)
-    {
-        $default = false;
-        if ($index && strpos($value, 'yes-') !== false) {
-            $temp = explode('-', $value);
-            $value = $temp[0];
-            $index = $temp[1];
-            if (isset($temp[2])) {
-                $default = $temp[2];
-            }
-        } elseif ($index && strpos($value, 'yes|') !== false) {
-            $temp = explode('|', $value);
-            $value = $temp[0];
-            $index = $temp[1];
-            if (isset($temp[2])) {
-                $default = $temp[2];
-            }
-        }
-
-        /*
-        if (isset($temp) && strstr($index, 't_') && strstr($index, '.')) {
-            $t = explode('.', $index);
-            $index = $t[1];
-        }
-        */
-
-        if ($index && $value == 'yes') {
-            $value = 'option';
-            /*
-            if (strpos($index, '.') !== false) {
-                $temp = explode('.', $index);
-                $index = $temp[1];
-            }*/
-            if (isset($this->struct[$index]) && is_array($this->struct[$index]) && isset($this->struct[$index]['match']) && $this->struct[$index]['match']) {
-                if (is_string($this->struct[$index]['match']) && strstr($this->struct[$index]['match'], 'option||')) {
-                    $this->struct[$index]['match'] = str_replace('option||', '', $this->struct[$index]['match']);
-                }
-                $value = $this->struct[$index]['match'];
-            }
-        }
-        if (is_array($value) && isset($value[1])) {
-            if ($this->update) {
-                $value = $value[1];
-            } else {
-                $value = $value[0];
-            }
-        }
-
-        if ($default) {
-            $value = $default;
-        }
-
-        $state = false;
-
-        if ($value == 'option') {
-            $value = '';
-            $state = true;
-        }
-
-        $callback = is_string($value) && function_exists($value);
-        if ($callback) {
-            $callback = $value;
-            $value = '';
-        }
-
-        return array($index, $value, $callback, $state);
-    }
-
-    /**
-     * replace
-     *
-     * @return mixd
-     */
-    private function replace($content)
-    {
-        $tags = array(
-
-            "'<iframe[^>]*?>.*?</iframe>'is",
-
-            "'<frame[^>]*?>.*?</frame>'is",
-
-            "'<script[^>]*?>.*?</script>'is",
-
-            "'<head[^>]*?>.*?</head>'is",
-
-            "'<title[^>]*?>.*?</title>'is",
-
-            "'<meta[^>]*?>'is",
-
-            "'<link[^>]*?>'is",
-        );
-
-        return preg_replace($tags, "", $content);
-    }
-
-    /**
-     * request
-     *
-     * @return mixd
-     */
-    private function request($index, $request, $method)
-    {
-        if ($index && isset($this->struct[$index]) && is_array($this->struct[$index]) && $request && $request != 'null') {
-
-            if (isset($this->struct[$index]['callback']) && $this->struct[$index]['callback']) {
-                $callback = $this->struct[$index]['callback'];
-                if ($callback == 'maketime') {
-                    if (is_string($request)) {
-                        $request = \Dever::maketime($request);
-                    }
-                } else {
-                    if (strpos($callback, '.')) {
-                        $temp = explode('.', $callback);
-                        $callback = $temp[0];
-                        if ($request != 'null') {
-                            $request = $callback($temp[1], $request);
-                        } else {
-                            $request = '';
-                        }
-                    } else {
-                        $request = $callback($request);
-                    }
-                }
-            } elseif (isset($this->struct[$index]['update']) && ($this->struct[$index]['update'] == 'day' || $this->struct[$index]['update'] == 'month')) {
-                $request = str_replace('-', '', $request);
-            } elseif (isset($this->struct[$index]['update']) && ($this->struct[$index]['update'] == 'date')) {
-                $request = \Dever::maketime($request);
-            }
-        }
-
-        $request = $this->update($index, $request, $method);
-
-        return $request;
-    }
-
-    /**
-     * update
-     *
-     * @return mixd
-     */
-    private function update($index, $request, $method)
-    {
-        if ($this->update && isset($this->struct[$index]['update'])) {
-            if (is_string($request) && empty($this->struct[$index]['strip'])) {
-                $request = $this->replace($request);
-            }
-
-            if ($request && is_string($request) && !strstr($request, '_') && isset($this->struct[$index]['key']) && $this->struct[$index]['key']) {
-                if (Config::get('host')->uploadRes && strpos($request, Config::get('host')->uploadRes) !== false) {
-                    $request = str_replace(Config::get('host')->uploadRes, '{uploadRes}', $request);
-                }
-                if (Dever::project('upload')) {
-                    $key = $this->struct[$index]['key'];
-                    $host = Import::load('upload/view.getYun?key=' . $key);
-                    if ($host && strpos($request, $host) !== false) {
-                        $request = str_replace($host, '{uploadYun}', $request);
-                    }
-                }
-            }
-
-            if (isset($this->struct[$index]['type'])) {
-                $type = $this->struct[$index]['type'];
-                if (strpos($type, '-')) {
-                    $temp = explode('-', $type);
-                    if (isset($temp[1]) && $temp[1] && is_string($request) && $request) {
-                        $len = strlen($request);
-                        if (!strstr($temp[0], 'text') && $len > $temp[1]) {
-                            $name = explode('-', $this->struct[$index]['name']);
-                            //Export::alert('core_database_maxlen', array($name[0], $temp[1]));
-                        }
-                    }
-                }
-            }
-        }
-
-        return $request;
-    }
-}

+ 0 - 980
src/Dever/Data/Model/Handle.php

@@ -1,980 +0,0 @@
-<?php namespace Dever\Data\Model;
-
-use Dever;
-use Dever\Loader\Config;
-use Dever\Loader\Project;
-use Dever\Loader\Import;
-use Dever\Output\Export;
-use Dever\Routing\Input;
-use Dever\String\Helper;
-use Dever\Data\Model;
-use Dever\Session\Oper;
-
-class Handle
-{
-    
-    /**
-     * param
-     *
-     * @var array
-     */
-    protected $param;
-
-    /**
-     * request
-     *
-     * @var array
-     */
-    protected $request;
-
-    /**
-     * config
-     *
-     * @var array
-     */
-    protected $config;
-
-
-    /**
-     * update state
-     *
-     * @var int
-     */
-    protected $update;
-
-    /**
-     * method
-     *
-     * @var string
-     */
-    protected $method;
-
-    /**
-     * call
-     *
-     * @var object
-     */
-    protected $call;
-
-    /**
-     * hook
-     *
-     * @var array
-     */
-    protected $hook;
-
-    /**
-     * get
-     *
-     * @return mixed
-     */
-    public function __construct($method, $config, $param, $call = false)
-    {
-        $this->method = $method;
-        $this->config = $config;
-        $this->param = $param;
-        $this->call = $call;
-        $this->request = isset($config['request'][$method]) ? $config['request'][$method] : array();
-    }
-
-    /**
-     * get
-     *
-     * @return mixed
-     */
-    public function get()
-    {
-        $data = array();
-        if ($this->request) {
-            $type = $this->request['type'];
-            $result = $this->setUpdate($type);
-            if ($result) {
-                return $result;
-            }
-            $this->manage();
-            $this->hook('start');
-            $this->top();
-
-            if ($this->check()) {
-                return;
-            }
-
-            $this->condition();
-
-            if ($this->update == 1 && isset($this->param['insert_value_num'])) {
-                $data = $this->db()->$type($this->param['insert_value_num']);
-            } else {
-                if ($type == 'all' && $this->call) {
-                    $data = $this->db()->$type($this->request['col'], $this->call);
-                } else {
-                    $data = $this->db()->$type($this->request['col']);
-                }
-            }
-            if ($this->update == 1 && $data) {
-                $this->save('add', $data, 20);
-            }
-
-            if ($this->update == 2 && isset($this->param['where_id'])) {
-                $data = $this->param['where_id'];
-            }
-
-            $this->hook('end', $data);
-
-            $this->after($type, $data);
-        }
-
-        return $data;
-    }
-
-    /**
-     * manage
-     *
-     * @return mixd
-     */
-    private function manage()
-    {
-        if (Project::load('manage') && DEVER_APP_NAME == 'manage') {
-            if ($this->config['project']['name'] != 'manage') {
-                $admin = Import::load('manage/auth.info');
-                if ($admin && $admin['id'] > 0) {
-                    if ($this->update == 1) {
-                        $this->updateManage($admin, 'insert', 'add');
-                    } elseif($this->update == 2) {
-                        $this->updateManage($admin, 'update', 'set');
-                    } elseif($admin['self'] == 1) {
-                        $this->updateManage($admin, 'select', 'where');
-                    }
-                }
-            }
-
-            if (isset($this->config['manage']['company'])) {
-                $company = Import::load('manage/company.get');
-                if ($company) {
-                    if (isset($this->param['clear_top']) && $this->param['clear_top']) {
-                        return;
-                    }
-                    if (is_array($this->config['manage']['company'])) {
-                        $col = $this->config['manage']['company']['col'];
-                    } else {
-                        $col = $this->config['manage']['company'];
-                    }
-                    
-                    if ($this->update == 1) {
-                        //$this->setParam('add_' . $col, $company);
-                        $this->param['add_' . $col] = $company;
-                    } elseif (!$this->update) {
-                        if ($this->method == 'list' && isset($this->config['manage']['company']['join'])) {
-                            $this->request['join'][] = $this->config['manage']['company']['join'];
-                            $this->request['option']['state'] = 'yes-t_1.state';
-                            $this->request['option'][$col] = 'yes-t_2.' . $col;
-                        }
-                        //$this->setParam('where_' . $col, $company);
-                        //$this->setParam('option_' . $col, $company);
-                        $this->param['option_' . $col] = $company;
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * updateManage
-     *
-     * @return mixd
-     */
-    private function updateManage($admin, $type, $prefix = 'add')
-    {
-        if (isset($admin['col_' . $type]) && $admin['col_' . $type] && is_array($this->param) && $admin['id'] > 1) {
-            $col = explode(',', $admin['col_' . $type]);
-            foreach ($col as $k => $v) {
-                if (isset($this->config['struct'][$v]) && empty($this->config['struct'][$v]['value'])) {
-                    $this->param[$prefix . '_' . $v] = $admin['id'];
-                    if ($prefix == 'where') {
-                        $this->param['option_' . $v] = $admin['id'];
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * db
-     *
-     * @return mixd
-     */
-    private function db()
-    {
-        return Database::get($this->config['db']);
-    }
-
-    /**
-     * updateState
-     *
-     * @return mixd
-     */
-    protected function setUpdate($type)
-    {
-        if ($type == 'insert') {
-            $this->update = 1;
-            # 验证是否可以插入
-            $state = $this->save();
-            if ($state) {
-                Dever::alert('提交失败');
-                return $state;
-            }
-        } elseif ($type == 'update') {
-            $this->update = 2;
-        } else {
-            $this->update = 0;
-        }
-        return false;
-    }
-
-    /**
-     * save
-     *
-     * @return mixd
-     */
-    protected function save($name = 'get', $data = false, $time = 20)
-    {
-        return false;
-        if (DEVER_APP_NAME == 'manage') {
-            return false;
-        }
-        if (!isset($this->save)) {
-            $this->save = new Oper(false, 'session');
-        }
-        if (!isset($this->save_name)) {
-            $param = $this->param;
-            if (isset($param['order_num'])) {
-                unset($param['order_num']);
-            }
-            $this->save_name = $this->config['db'] . '_' . $this->config['name'] . '_' . md5(Dever::json_encode($param));
-        }
-        
-        if ($name == 'add') {
-            return $this->save->add($this->save_name, $data, $time);
-        } else {
-            return $this->save->get($this->save_name);
-        }
-    }
-
-    /**
-     * hook
-     * @param string $key
-     * @param string $method
-     *
-     * @return mixd
-     */
-    private function hook($method = 'start', $data = array())
-    {
-        if (!$data && $method == 'start') {
-            $data = $this->param;
-        }
-        if (Dever::config('base')->hook) {
-            return;
-        }
-        if (isset($this->config[$method][$this->method])) {
-            $key = $this->config['name'] . $method . $this->method . md5(Dever::json_encode($data));
-            if (isset($this->hook[$key])) {
-                return;
-            }
-            $this->hook[$key] = true;
-            if (isset($this->config['top']) && is_array($this->config['top'])) {
-               $this->param['top'] = $this->config['top'];
-            }
-            if (isset($this->config['auth']) && is_array($this->config['auth'])) {
-                $this->param['auth'] = $this->config['auth'];
-            }
-
-            $name = $this->config['db'] . '/' . $this->config['name'];
-
-            if (is_array($this->config[$method][$this->method])) {
-                foreach ($this->config[$method][$this->method] as $k => $v) {
-                    $result = Import::load($v, $data, $name, $this->param);
-                    if ($result && is_array($result)) {
-                        $this->param[$v] = $result;
-                    }
-                }
-            } else {
-                $data = Import::load($this->config[$method][$this->method], $data, $name, $this->param);
-
-                if ($data && is_array($data)) {
-                    //$this->param[$this->config[$method][$this->method]] = $data;
-                    $this->param = $data;
-                    //print_r($this->param);die;
-                }
-            }
-        }
-    }
-
-    /**
-     * top
-     *
-     * @return mixd
-     */
-    private function top()
-    {
-        if (isset($this->config['top']) && is_array($this->config['top'])) {
-            $top = 'manage/top.sync';
-            if (isset($this->config['end']['insert']) && $this->config['end']['insert']) {
-                if (!in_array($top, $this->config['end']['insert'])) {
-                    array_push($this->config['end']['insert'], $top);
-                }
-            } else {
-                $this->config['end']['insert'][] = $top;
-            }
-            if (isset($this->config['end']['update']) && $this->config['end']['update']) {
-                if (!in_array($top, $this->config['end']['update'])) {
-                    array_push($this->config['end']['update'], $top);
-                }
-            } else {
-                $this->config['end']['update'][] = $top;
-            }
-        } elseif (isset($this->config['top']) && is_string($this->config['top'])) {
-            if (Dever::config('base')->clear_top) {
-                return;
-            }
-            if (isset($this->param['clear_top']) && $this->param['clear_top']) {
-                return;
-            }
-            $value = isset($this->param[$this->config['top']]) ? $this->param[$this->config['top']] : Input::get($this->config['top']);
-            $top = array();
-            if ($value) {
-                $top['value'] = $value;
-            } elseif (DEVER_APP_NAME == 'manage') {
-                $top = Import::load('manage/auth.getTop', $this->config['top']);
-            }
-            if ($top) {
-                $temp = explode('/', $this->config['top']);
-                $this->config['top'] = $temp[1];
-                if (strpos($this->config['top'], '-')) {
-                    $temp = explode('-', $this->config['top']);
-                    $this->config['top'] = $temp[0];
-                }
-                if (isset($this->param[$this->config['top']]) && $this->param[$this->config['top']]) {
-                    return;
-                }
-                
-                if ($this->update) {
-
-                    if ($this->update == 1 && isset($this->param['add_' . $this->config['top']]) && $this->param['add_' . $this->config['top']]) {
-                        return;
-                    }
-                    if ($this->update == 2) {
-                        return;
-                    }
-                    $this->setParam($this->config['top'], $top['value']);
-                } else {
-                    $this->setParam('where_' . $this->config['top'], $top['value']);
-                    $this->setParam('option_' . $this->config['top'], $top['value']);
-                }
-            }
-        }
-    }
-
-
-    /**
-     * check
-     *
-     * @return mixd
-     */
-    private function check()
-    {
-        $check = false;
-        if (isset($this->config['check']) && $this->update) {
-            if (is_array($this->config['check'])) {
-                foreach ($this->config['check'] as $k => $v) {
-                    if ($this->checkCol($v)) {
-                        $check = true;
-                    }
-                }
-            } else {
-                $check = $this->checkCol($this->config['check']);
-            }
-        }
-
-        return $check;
-    }
-
-    /**
-     * checkCol
-     *
-     * @return mixd
-     */
-    private function checkCol($col)
-    {
-        $check = true;
-        if (strpos($col, '.option')) {
-            $col = str_replace('.option', '', $col);
-            $check = false;
-        }
-
-        $data = explode(',', $col);
-        $id = -1;
-        if (isset($this->param['where_id'])) {
-            $id = $this->param['where_id'];
-            if ($this->update == 2 && $id < 0) {
-                //return true;
-            }
-        }
-
-
-        foreach ($data as $k => $v) {
-            if (isset($this->config['struct'][$v])) {
-                if (isset($this->param['set_' . $v])) {
-                    $param['option_' . $v] = $this->param['set_' . $v];
-                } elseif (isset($this->param['add_' . $v])) {
-                    $param['option_' . $v] = $this->param['add_' . $v];
-                } elseif (isset($this->param[$v])) {
-                    $param['option_' . $v] = $this->param[$v];
-                }
-
-                if (isset($param['option_' . $v]) && is_array($param['option_' . $v])) {
-                    $param['option_' . $v] = implode(',', $param['option_' . $v]);
-                }
-                $temp = explode('-', $this->config['struct'][$v]['name']);
-                $name[] = $temp[0];
-            }
-        }
-
-        if (isset($param) && $param && !isset($this->param['set_state'])) {
-            $info = Model::load($this->config['project']['name'] . '/' . $this->config['name'])->one($param);
-
-            if ($id > 0 && $info && $info['id'] != $id) {
-                if ($check == true) {
-                    Export::alert(implode(',', $name).'已经存在');
-                } else {
-                    return true;
-                }
-            } elseif ($id < 0 && $info) {
-                if ($check == true) {
-                    Export::alert(implode(',', $name).'已经存在');
-                } else {
-                    return true;
-                }
-            }
-        }
-
-        return false;
-    }
-
-    /**
-     * condition
-     *
-     * @return mixd
-     */
-    private function condition()
-    {
-        $this->table();
-        $this->col();
-        Condition::get()->init($this->request, $this->config['struct'], $this->param, $this->config['project']['name'], $this->config['name'], $this->config['db']);
-    }
-
-    /**
-     * table
-     *
-     * @return mixd
-     */
-    private function table()
-    {
-        $this->index = '';
-        if (isset($this->config['struct'])) {
-            if (!isset($this->config['table'])) {
-                $this->config['table'] = '';
-            }
-            if (!isset($this->config['db_prefix'])) {
-                $this->config['db_prefix'] = '';
-            }
-            if (!isset($this->config['link'])) {
-                $this->config['link'] = false;
-            }
-
-            if (Config::get('base')->alias && isset(Config::get('base')->alias[$this->config['project']['name']])) {
-                $this->config['project']['name'] = Config::get('base')->alias[$this->config['project']['name']];
-            }
-            $this->db()->table($this->config['project']['name'] . '_' . $this->config['name'], $this->index, true, $this->config['table'], $this->config['db_prefix'], $this->config['link']);
-
-            $this->create();
-        } else {
-            $this->db()->table($this->config['name'], $this->index, false);
-        }
-    }
-
-    /**
-     * create
-     *
-     * @return mixd
-     */
-    private function create()
-    {
-        if (isset($this->config['struct'])) {
-            $this->config['type'] = isset($this->config['type']) ? $this->config['type'] : 'innodb';
-            $this->config['partition'] = isset($this->config['partition']) ? $this->config['partition'] : '';
-            $this->config['auto'] = isset($this->config['auto']) ? $this->config['auto'] : 1;
-            $this->config['create'] = isset($this->config['create']) ? $this->config['create'] : -2;
-            $create = $this->db()->create($this->config['struct'], $this->index, $this->config['type'], $this->config['partition'], $this->config['create'], $this->config['auto']);
-            if ($create === false) {
-                return;
-            }
-            if ($create === true && isset($this->config['default'])) {
-                # 写入默认值
-                $this->db()->insertDefault($this->config['default'], $this->index);
-            } elseif (isset($create['struct']) && $create['struct']&& count($create['struct']) < count($this->config['struct'])) {
-                $alter = array_diff_key($this->config['struct'], $create['struct']);
-                if ($alter) {
-                    $this->db()->alter($alter, $this->config['struct'], $this->index);
-                }
-            }
-
-            if (isset($this->config['alter'])) {
-                $this->db()->alter($this->config['alter'], $this->index);
-            }
-
-            if (isset($this->config['index'])) {
-                $this->db()->index($this->config['index']);
-            }
-        }
-    }
-
-    /**
-     * col
-     *
-     * @return mixd
-     */
-    private function col()
-    {
-        if (empty($this->request['col'])) {
-            $this->request['col'] = '*';
-        }
-
-        if (Config::get('template')->sql && strpos(Config::get('template')->sql, '*') !== false) {
-            $temp = array();
-            foreach ($this->config['struct'] as $k => $v) {
-                if (isset($v['type'])) {
-                    $temp[$k] = '`' . $k . '`';
-                }
-            }
-
-            $this->request['col'] = str_replace('*', implode(',', $temp), $this->request['col']);
-        }
-    }
-
-    /**
-     * after
-     *
-     * @return mixd
-     */
-    protected function after($type, &$data)
-    {
-        if ($this->update) {
-
-            if (!isset(Config::get('base')->after) || (isset(Config::get('base')->after) && Config::get('base')->after == false)) {
-                if (Project::load('manage') && isset($this->config['manage']) && isset($this->config['manage']['filter'])) {
-                    $this->filter($this->config['manage']['filter'], $data);
-                }
-
-                if (isset($this->config['sync'])) {
-                    $this->sync($this->config['sync'], $data);
-                }
-
-                if (isset($this->config['syncone'])) {
-                    $this->syncone($this->config['syncone'], $data);
-                }
-            }
-
-        } elseif ($data && isset($this->request['relate'])) {
-            $this->relate($this->request['relate'], $data, $type);
-        } elseif ($data && isset($this->request['call'])) {
-            $this->call($this->request['call'], $data, $type);
-        } elseif ($data && isset($this->config['fill'])) {
-            $this->fill($this->config['fill'], $data, $type);
-        }
-    }
-
-    /**
-     * handle
-     *
-     * @return mixd
-     */
-    private function fill($config, &$data, $type)
-    {
-        if (isset($this->param['nofill'])) {
-            return;
-        }
-        if ($type == 'all') {
-            foreach ($data as $k => $v) {
-                $this->fill($config, $data[$k], 'aone');
-            }
-        } else {
-            if (DEVER_APP_NAME == 'manage' && $type == 'one') {
-                return;
-            }
-            foreach ($config as $k => $v) {
-                $w = array();
-                foreach ($v['where'] as $i => $j) {
-                    if (isset($data[$j]) && $data[$j]) {
-                        $w[$i] = $data[$j];
-                    } elseif($j) {
-                        $w[$i] = $j;
-                    }
-                }
-                $w['nofill'] = 1;
-                $r = Model::load($k)->one($w);
-                if ($r) {
-                    if (isset($v['update'])) {
-                        foreach ($v['update'] as $i => $j) {
-                            if (is_numeric($i)) {
-                                $i = $j;
-                            }
-                            if (isset($r[$i]) && $r[$i]) {
-                                $data[$j] = $r[$i];
-                            }
-                        }
-                    } else {
-                        if (!isset($v['no'])) {
-                            $v['no'] = array('id', 'state', 'cdate');
-                        }
-                        foreach ($r as $i => $j) {
-                            if ((isset($data[$i]) || array_key_exists($i, $data)) && (!$data[$i] || (is_numeric($data[$i]) && $data[$i] <= 0)) && $j && !in_array($i, $v['no'])) {
-                                $data[$i] = $j;
-                            }
-                        }
-                    }
-                }
-                
-            }
-        }
-    }
-
-    /**
-     * handle
-     *
-     * @return mixd
-     */
-    private function relate($config, &$data, $type)
-    {
-        if ($type == 'all') {
-            foreach ($data as $k => $v) {
-                $this->relate($config, $data[$k], 'one');
-            }
-        } else {
-            foreach ($config as $k => $v) {
-                foreach ($v as $i => $j) {
-                    $v[$i] = $data[$j];
-                }
-                $data[$k] = Model::load($k, $v);
-            }
-        }
-    }
-
-    /**
-     * handle
-     *
-     * @return mixd
-     */
-    private function call($config, &$data, $type)
-    {
-        if ($type == 'all') {
-            foreach ($data as $k => $v) {
-                $this->call($config, $data[$k], 'one');
-            }
-        } else {
-            $data = Import::load($config, $data);
-        }
-    }
-
-    private function syncone($config, $id)
-    {
-        if (Config::get('base')->syncone) {
-            return;
-        }
-        Config::get('base')->syncone = true;
-        foreach ($config as $k => $v) {
-            $id = $id > 0 ? $id : $this->param['where_id'];
-
-            $info = Model::load($this->config['project']['name'] . '/' . $this->config['name'])->one(array('option_id' => $id, 'option_time' => time()));
-
-            $where = array();
-
-            if (isset($v['where'][0])) {
-                $where['option_' . $v['where'][0]] = $info[$v['where'][1]];
-                $where[$v['where'][0]] = $info[$v['where'][1]];
-            } else {
-                foreach ($v['where'] as $k1 => $v1) {
-                    if (isset($info[$v1])) {
-                        $where['option_' . $k1] = $info[$v1];
-                        $where[$k1] = $info[$v1];
-                    } else {
-                        $where['option_' . $k1] = $v1;
-                        $where[$k1] = $v1;
-                    }
-                }
-            }
-
-            $one = Model::load($k)->one($where);
-
-            $method = 'insert';
-            $type = 'add';
-            if ($one) {
-                $method = 'update';
-                $type = 'set';
-                $where['where_id'] = $one['id'];
-            }
-
-            $param = array();
-            foreach ($v['update'] as $i => $j) {
-                if (isset($info[$j])) {
-                    $j = $info[$j];
-                }
-                $param[$type . '_' . $i] = $j;
-            }
-
-            $param = $where + $param;
-
-            Model::load($k)->$method($param);
-        }
-    }
-
-    /**
-     * handle
-     *
-     * @return mixd
-     *
-    private function sync($config, $id)
-    {
-        foreach ($config as $k => $v) {
-            $id = $id > 0 ? $id : $this->param['where_id'];
-
-            $info = Model::load($this->config['project']['name'] . '/' . $this->config['name'])->one(array('option_id' => $id, 'option_time' => time()));
-
-            $where = array();
-
-            if (isset($v['where'][0])) {
-                $where['option_' . $v['where'][0]] = $info[$v['where'][1]];
-            } else {
-                foreach ($v['where'] as $k1 => $v1) {
-                    if (isset($info[$v1])) {
-                        $where['option_' . $k1] = $info[$v1];
-                    } else {
-                        $where['option_' . $k1] = $v1;
-                    }
-                }
-            }
-
-            if (!$where) {
-                break;
-            }
-
-            if ($v['type'] == 'only') {
-                $param = $where;
-                foreach ($v['update'] as $i => $j) {
-                    if (isset($info[$j])) {
-                        $param[$i] = $info[$j];
-                    }
-                }
-                Model::load($k)->updates($param);
-            } else {
-                if ($v['type'] == 'delete') {
-                    Model::load($k)->delete($where);
-                }
-                foreach ($v['update'] as $i => $j) {
-                    if (strpos($i, '-')) {
-                        $t = explode('-', $i);
-                        $i = $t[0];
-                    }
-                    $value = $info[$j];
-
-                    if ($value) {
-                        $value = explode(',', $value);
-                        foreach ($value as $a => $b) {
-                            if ($b < 0) {
-                                continue;
-                            }
-                            $method = 'insert';
-                            $type = 'add';
-                            $param = array();
-                            $where['option_' . $i] = $b;
-                            if ($v['type'] != 'delete') {
-                                $check = Model::load($k)->one($where);
-
-                                if ($check) {
-                                    $method = 'update';
-                                    $type = 'set';
-                                    $param = array
-                                    (
-                                        'where_id' => $check['id'],
-                                    );
-                                }
-                            }
-
-                            if ($method) {
-                                $param += $where;
-
-                                if (isset($v['sync'])) {
-                                    foreach ($v['sync'] as $c => $d) {
-                                        if (isset($info[$d]) && $info[$d]) {
-                                            $param[$type . '_' . $c] = $info[$d];
-                                        }
-                                    }
-                                }
-                                Model::load($k)->$method($param);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-    */
-
-    private function sync($config, $id)
-    {
-        if (Config::get('base')->sync) {
-            return;
-        }
-        Config::get('base')->sync = true;
-        foreach ($config as $k => $v) {
-            $id = $id > 0 ? $id : $this->param['where_id'];
-
-            $info = Model::load($this->config['project']['name'] . '/' . $this->config['name'])->one(array('option_id' => $id, 'option_time' => time()));
-
-            $where = array();
-
-            if (isset($v['where'][0])) {
-                $where['option_' . $v['where'][0]] = $info[$v['where'][1]];
-                $where[$v['where'][0]] = $info[$v['where'][1]];
-            } else {
-                foreach ($v['where'] as $k1 => $v1) {
-                    if (isset($info[$v1])) {
-                        $where['option_' . $k1] = $info[$v1];
-                        $where[$k1] = $info[$v1];
-                    } else {
-                        $where['option_' . $k1] = $v1;
-                        $where[$k1] = $v1;
-                    }
-                }
-            }
-
-            if (!$where) {
-                break;
-            }
-
-            if ($v['type'] == 'only') {
-                $param = $where;
-                foreach ($v['update'] as $i => $j) {
-                    if (isset($info[$j])) {
-                        $param[$i] = $info[$j];
-                    }
-                }
-                Model::load($k)->updates($param);
-            } else {
-                if ($v['type'] == 'delete') {
-                    Model::load($k)->delete($where);
-                } else {
-                    $update = $where;
-                    $update['set_state'] = 2;
-                    Model::load($k)->updates($update);
-                }
-                foreach ($v['update'] as $i => $j) {
-                    if (strpos($i, '-')) {
-                        $t = explode('-', $i);
-                        $i = $t[0];
-                    }
-                    $value = $info[$j];
-
-                    if ($value) {
-                        $value = explode(',', $value);
-                        foreach ($value as $a => $b) {
-                            if ($b < 0) {
-                                continue;
-                            }
-                            $method = 'insert';
-                            $type = 'add';
-                            $param = array();
-                            if ($v['type'] != 'delete') {
-                                $w = $where;
-                                $w['option_' . $i] = $b;
-                                $check = Model::load($k)->one($w);
-
-                                if ($check) {
-                                    $method = 'update';
-                                    $type = 'set';
-                                    $param = array
-                                    (
-                                        'where_id' => $check['id'],
-                                        'set_state' => 1,
-                                    );
-                                }
-                            }
-
-                            if ($method) {
-                                $p = $where;
-                                $p[$type . '_' . $i] = $b;
-                                $param = array_merge($param, $p);
-
-                                if (isset($v['sync'])) {
-                                    foreach ($v['sync'] as $c => $d) {
-                                        if (isset($info[$d]) && $info[$d]) {
-                                            $param[$type . '_' . $c] = $info[$d];
-                                        }
-                                    }
-                                }
-                                Model::load($k)->$method($param);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * handle
-     *
-     * @return mixd
-     */
-    private function filter($filter, $data)
-    {
-        if ($this->method == 'update' && isset($this->param['where_id'])) {
-            $this->filterText($filter, 'set', $this->param['where_id']);
-        } elseif ($this->method == 'insert' && $data > 0) {
-            $this->filterText($filter, 'add', $data);
-        }
-    }
-
-    /**
-     * handle
-     *
-     * @return mixd
-     */
-    private function filterText($filter, $prefix = 'set', $id)
-    {
-        $text = '';
-
-        foreach ($filter as $k => $v) {
-            if (isset($this->param[$prefix . '_' . $v])) {
-                $text .= '&dever_' . $v . '=' . $this->param[$prefix . '_' . $v];
-            }
-        }
-
-        if ($text) {
-            $config['project'] = $this->config['project']['name'];
-            $config['table'] = $this->config['name'];
-            Import::load('manage/filter.handle', $id, $text, $config);
-        }
-    }
-
-    /**
-     * setParam
-     * @param string $key
-     *
-     * @return mixd
-     */
-    private function setParam($key, $value)
-    {
-        if (!isset($this->param[$key])) {
-            $this->param[$key] = $value;
-        }
-    }
-}

+ 0 - 239
src/Dever/Data/Model/Link.php

@@ -1,239 +0,0 @@
-<?php namespace Dever\Data\Model;
-
-use Dever\Data\Sql;
-
-class Link
-{
-    /**
-     * table
-     *
-     * @var string
-     */
-    protected $table;
-
-    /**
-     * col
-     *
-     * @var string
-     */
-    protected $col;
-
-    /**
-     * bind
-     *
-     * @var array
-     */
-    protected $bind;
-
-    /**
-     * where
-     *
-     * @var array
-     */
-    protected $where;
-
-    /**
-     * order
-     *
-     * @var array
-     */
-    protected $order;
-
-    /**
-     * group
-     *
-     * @var array
-     */
-    protected $group;
-
-    /**
-     * limit
-     *
-     * @var array
-     */
-    protected $limit;
-
-    /**
-     * page
-     *
-     * @var array
-     */
-    protected $page;
-
-    /**
-     * cache
-     *
-     * @var string
-     */
-    protected $cache;
-
-    /**
-     * db
-     *
-     * @var Dever\Data\Model
-     */
-    protected $db;
-
-    /**
-     * sql
-     *
-     * @var Dever\Data\Sql
-     */
-    protected $sql;
-
-    /**
-     * __construct
-     *
-     * @return mixed
-     */
-    public function __construct($db)
-    {
-        $this->db = $db;
-        $this->sql = Sql::getInstance();
-    }
-
-    /**
-     * fetch
-     *
-     * @return mixd
-     */
-    public function fetch($method = 'fetch')
-    {
-        $sql = $this->sql->select($this->table, $this->col);
-        echo $sql;die;
-        return $this->db->$method($sql, $this->bind, $this->page, $this->cache);
-    }
-
-    /**
-     * fetchAll
-     *
-     * @return mixd
-     */
-    public function fetchAll()
-    {
-        return $this->fetch('fetchAll');
-    }
-
-    /**
-     * table
-     *
-     * @return mixd
-     */
-    public function table($name)
-    {
-        $this->table = $name;
-        return $this;
-    }
-
-    /**
-     * col
-     *
-     * @return mixd
-     */
-    public function col($col)
-    {
-        $this->col = $col;
-        return $this;
-    }
-
-    /**
-     * order
-     *
-     * @return mixd
-     */
-    public function order()
-    {
-        return $this;
-    }
-
-    /**
-     * group
-     *
-     * @return mixd
-     */
-    public function group($group)
-    {
-        $this->sql->group($group);
-        return $this;
-    }
-
-    /**
-     * limit
-     *
-     * @return mixd
-     */
-    public function limit($limit)
-    {
-        $this->sql->limit(array($limit));
-        return $this;
-    }
-
-    /**
-     * page
-     *
-     * @return mixd
-     */
-    public function page($page)
-    {
-        $this->page = $page;
-        return $this;
-    }
-
-    /**
-     * cache
-     *
-     * @return mixd
-     */
-    public function cache($cache)
-    {
-        $this->cache = $cache;
-        return $this;
-    }
-
-    /**
-     * where
-     *
-     * @return mixd
-     */
-    public function where($param)
-    {
-        $this->param($param);
-        if ($this->where) {
-            foreach ($this->where as $k => $v) {
-                $this->sql->where($v);
-            }
-        }
-        
-        return $this;
-    }
-
-    /**
-     * param
-     *
-     * @return mixd
-     */
-    public function param($param)
-    {
-        $this->where = array();
-        foreach ($param as $k => $v) {
-            if (strpos($k, 'where_') !== false || strpos($k, 'option_') !== false) {
-                $k = str_replace(array('where_', 'option_'), '', $k);
-                $key = ':' . count($this->where);
-                if (is_array($v) && isset($v[0])) {
-                    $this->bind[$key] = $v[0];
-                    $v[0] = $key;
-                    array_unshift($v, $k);
-                    $this->where[$k] = $v;
-                } else {
-                    $this->bind[$key] = $v;
-                    $this->where[$k] = array($k, $key);
-                }
-            } elseif ($k == 'limit' || $k == 'order' || $k == 'group') {
-                $this->$k = $v;
-            } else {
-                $k = str_replace(array('add_', 'set_'), '', $k);
-                $this->update[$k] = $v;
-            }
-        }
-    }
-}

+ 0 - 41
src/Dever/Data/Model/Opt.php

@@ -1,41 +0,0 @@
-<?php namespace Dever\Data\Model;
-
-use Dever\Support\Command;
-use Dever\Output\Debug;
-
-class Opt
-{
-    protected static $data;
-
-    protected static $instance;
-
-    /**
-     * push
-     *
-     * @return mixd
-     */
-    public static function push($project, $table, $col)
-    {
-        if ($col) {
-            $key = $project . '.' . $table;
-            foreach ($col as $k => $v) {
-                self::$data[$key][$v] = $v;
-            }
-
-            $time = Debug::time();
-            self::$data[$key]['time'] = $time;
-        }
-    }
-
-    /**
-     * record
-     *
-     * @return mixd
-     */
-    public static function record()
-    {
-        if (self::$data) {
-            Command::log('src/auth.opt', self::$data);
-        }
-    }
-}

+ 0 - 550
src/Dever/Data/Model/Request.php

@@ -1,550 +0,0 @@
-<?php namespace Dever\Data\Model;
-
-use Dever\Loader\Config;
-
-class Request
-{
-    /**
-     * config
-     *
-     * @var array
-     */
-    protected $config;
-
-    /**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * load
-     *
-     * @return mixed
-     */
-    public static function get($key, $method, $struct, $search)
-    {
-        if (empty(self::$instance[$key])) {
-            self::$instance[$key] = new self();
-        }
-
-        return self::$instance[$key]->call($method, $struct, $search);
-    }
-
-    /**
-     * call
-     *
-     * @return mixd
-     */
-    public function call($method, $struct, $search)
-    {
-        if (empty($this->config[$method])) {
-            $call = '_' . $method;
-            if(strpos($call, 'update_')) {
-                $this->config[$method] = $this->auto($method);
-            } else {
-                $this->config[$method] = $this->$call();
-            }
-            $this->setting($method, $struct, $search);
-        }
-        return $this->config[$method];
-    }
-
-    /**
-     * setting
-     * @param string $method
-     * @param array $struct
-     *
-     * @return mixd
-     */
-    protected function setting($method, $struct, $search)
-    {
-        $state = $this->state($method);
-        if ($state && $struct) {
-            foreach ($struct as $key => $value) {
-                if (isset($value['match'])) {
-                    $this->settingValue($state, $method, $key, $value, $search);
-                }
-            }
-        }
-    }
-
-    /**
-     * settingValue
-     *
-     * @return mixd
-     */
-    protected function settingValue($state, $method, $key, $value, $search)
-    {
-        if (is_array($value['match'])) {
-            $value['match'] = $value['match'][0];
-            if (isset($value['insert']) && $state == 'add') {
-                $value['match'] = 'yes';
-            } elseif(empty($value['insert']) && ($state == 'add' || $state == 'set')) {
-                $value['match'] = 'yes';
-            }
-        }
-        if ($state == 'option') {
-            $this->settingOption($method, $key, $value);
-            if (isset($value['search']) && is_string($value['search']) && $search && strpos($value['search'], 'exp') !== false) {
-                $this->config[$method][$state][$key] = array($value['match'], $this->searchType($search));
-            }
-        }
-
-        if (empty($this->config[$method][$state][$key]) && isset($value['match'])) {
-            if (is_string($value['match']) && strstr($value['match'], 'option||')) {
-                $value['match'] = str_replace('option||', '', $value['match']);
-            }
-            $this->config[$method][$state][$key] = $value['match'];
-        }
-    }
-
-    /**
-     * settingValue
-     *
-     * @return mixd
-     */
-    protected function settingOption($method, $key, $value)
-    {
-        if (isset($value['bit'])) {
-            $this->config[$method]['option'][$key] = array('option', '&');
-        }
-
-        if (isset($value['order']) && isset($this->config[$method]['order'])) {
-            $this->settingOrder($method, $key, $value);
-        }
-
-        if (isset($value['search'])) {
-            $this->settingSearch($method, $key, $value);
-        }
-
-        if (isset($value['in'])) {
-            $this->config[$method]['option'][$key] = array('option', 'in');
-        }
-    }
-
-    /**
-     * settingValue
-     *
-     * @return mixd
-     */
-    protected function settingOrder($method, $key, $value)
-    {
-        if (isset($this->config[$method]['order']['id']) && $this->config[$method]['order']['id'] != $key) {
-            $temp = $this->config[$method]['order']['id'];
-            unset($this->config[$method]['order']['id']);
-            $this->config[$method]['order'][$key] = is_string($value['order']) ? $value['order'] : 'desc';
-            if ($key != 'id') {
-                $this->config[$method]['order']['id'] = $temp;
-            }
-            unset($temp);
-        }
-    }
-
-    /**
-     * settingSearch
-     *
-     * @return mixd
-     */
-    protected function settingSearch($method, $key, $value)
-    {
-        if (is_string($value['search'])) {
-            if (strpos($value['search'], 'time') !== false || strpos($value['search'], 'date') !== false || strpos($value['search'], 'day') !== false || strpos($value['search'], 'month') !== false || strpos($value['search'], 'year') !== false || strstr($key, 'date')) {
-                $this->config[$method]['option']['start_' . $key] = array('yes-' . $key, '>=');
-                $this->config[$method]['option']['end_' . $key] = array('yes-' . $key, '<=');
-            } elseif ($method == 'list' && (strpos($value['search'], 'selects_in') !== false)) {
-                $this->config[$method]['option'][$key] = array('option', 'in');
-            } elseif ($method == 'list' && (strpos($value['search'], 'fulltext') !== false || strpos($value['search'], 'linkage') !== false || strpos($value['search'], 'selects') !== false)) {
-                $this->config[$method]['option'][$key] = array('option', 'like');
-            }
-        }
-    }
-
-    /**
-     * searchType
-     *
-     * @return mixd
-     */
-    private function searchType($method)
-    {
-        switch($method)
-        {
-            case 1:
-                $method = '=';
-                break;
-            case 2:
-                $method = 'like';
-                break;
-            case 3:
-                $method = '>';
-                break;
-            case 4:
-                $method = '>=';
-                break;
-            case 5:
-                $method = '<';
-                break;
-            case 6:
-                $method = '<=';
-                break;
-        }
-        
-        return $method;
-    }
-
-    /**
-     * state
-     *
-     * @return mixd
-     */
-    protected function state($method)
-    {
-        $config = array('option', 'set', 'add');
-        foreach ($config as $value) {
-            if (isset($this->config[$method][$value])) {
-                return $value;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * auto
-     *
-     * @return mixd
-     */
-    protected function auto($method)
-    {
-        $config = $this->_update();
-        $method = str_replace('update_', '', $method);
-        $config['set'][$method] = 'yes';
-        return $config;
-    }
-
-    /**
-     * _find
-     *
-     * @return mixd
-     */
-    protected function _find()
-    {
-        return array
-        (
-            'type' => 'one',
-            'where' => array('state' => 1),
-            'order' => array('id' => 'desc'),
-            'option' => array(),
-        );
-    }
-
-    /**
-     * _select
-     *
-     * @return mixd
-     */
-    protected function _select()
-    {
-        return array
-        (
-            'type' => 'all',
-            'order' => array('id' => 'desc'),
-            'col' => '*',
-            'where' => array('state' => 1),
-            'option' => array(),
-        );
-    }
-
-    /**
-     * _select
-     *
-     * @return mixd
-     */
-    protected function _select_page()
-    {
-        return array
-        (
-            'type' => 'all',
-            'order' => array('id' => 'desc'),
-            'col' => '*',
-            'page' => array(10, 'list'),
-            'where' => array('state' => 1),
-            'option' => array(),
-        );
-    }
-
-    /**
-     * _one
-     *
-     * @return mixd
-     */
-    protected function _one()
-    {
-        return array
-        (
-            'type' => 'one',
-            'option' => array(),
-        );
-    }
-
-    /**
-     * _list
-     *
-     * @return mixd
-     */
-    protected function _list()
-    {
-        $page = $this->_all();
-        $num = 20;
-        if (Config::get('base')->excel) {
-            return $page;
-        }
-        return array_merge($page, array('page' => array($num, 'list')));
-    }
-
-    /**
-     * _state 即将废弃
-     *
-     * @return mixd
-     */
-    protected function _state()
-    {
-        return array_merge($this->_all(), array('where' => array('state' => 1)));
-    }
-
-    /**
-     * _state 即将废弃
-     *
-     * @return mixd
-     */
-    protected function _stateTotal()
-    {
-        return array_merge($this->_total(), array('where' => array('state' => 1)));
-    }
-
-    /**
-     * _state 即将废弃
-     *
-     * @return mixd
-     */
-    protected function _stateOne()
-    {
-        return array_merge($this->_one(), array('where' => array('state' => 1)));
-    }
-
-    /**
-     * _all
-     *
-     * @return mixd
-     */
-    protected function _limit()
-    {
-        return array
-        (
-            'type' => 'all',
-            'order' => array('id' => 'desc'),
-            //'group' => 'id',
-            'limit' => '0,100',
-            'col' => '*|id',
-            'option' => array(),
-        );
-    }
-
-    /**
-     * _all 即将废弃
-     *
-     * @return mixd
-     */
-    protected function _all()
-    {
-        return array
-        (
-            'type' => 'all',
-            'order' => array('id' => 'desc'),
-            //'group' => 'id',
-            //'limit' => '0,10',
-            'col' => '*|id',
-            'option' => array(),
-        );
-    }
-
-    /**
-     * _getmul
-     *
-     * @return mixd
-     */
-    protected function _getmul()
-    {
-        $config = $this->_all();
-
-        if (Config::get('base')->mul_type) {
-            if (Config::get('base')->mul_type == 2) {
-                unset($config['where']);
-                $config['option'] = array();
-            } else {
-                $config['where']['id'] = array('yes', 'in');
-            }
-        }
-
-        return $config;
-    }
-
-    /**
-     * _search
-     *
-     * @return mixd
-     */
-    protected function _search()
-    {
-        return array
-        (
-            'config' => true,
-            'option' => array
-            (
-                'ids' => array('yes-id', 'in'),
-                'name' => array('yes', 'like'),
-                'id' => 'yes',
-                'state' => 1,
-            ),
-            'type' => 'all',
-            'order' => array('reorder' => 'desc', 'id' => 'desc'),
-            'page' => array(10, 'list'),
-            'col' => 'name as name, id, id as value, "" as selected, "" as disabled|id',
-        );
-    }
-
-    /**
-     * _search
-     *
-     * @return mixd
-     */
-    protected function _search_find()
-    {
-        return array
-        (
-            'option' => array
-            (
-                'ids' => array('yes-id', 'in'),
-                'name' => array('yes', 'like'),
-                'id' => 'yes',
-                'state' => 1,
-            ),
-            'type' => 'all',
-            'order' => array('reorder' => 'desc', 'id' => 'desc'),
-            'col' => 'name as name, id, id as value, "" as selected, "" as disabled|id',
-        );
-    }
-
-    /**
-     * _total
-     *
-     * @return mixd
-     */
-    protected function _total()
-    {
-        return array
-        (
-            'type' => 'count',
-            'col' => 'count(1) as total',
-            'option' => array
-            (
-                'start' => array('yes-cdate', '>='),
-                'end' => array('yes-cdate', '<='),
-            ),
-        );
-    }
-
-    /**
-     * _update
-     *
-     * @return mixd
-     */
-    protected function _update()
-    {
-        return array
-        (
-            'type' => 'update',
-            'set' => array(),
-            'where' => array('id' => 'yes'),
-        );
-    }
-
-    /**
-     * _updates 慎用!
-     *
-     * @return mixd
-     */
-    protected function _updates()
-    {
-        return array
-        (
-            'type' => 'update',
-            'set' => array(),
-            'option' => array(),
-        );
-    }
-
-    /**
-     * _updatemul
-     *
-     * @return mixd
-     */
-    protected function _updatemul()
-    {
-        $config = $this->_updates();
-
-        if (Config::get('base')->mul_type) {
-            if (Config::get('base')->mul_type == 2) {
-                unset($config['where']);
-                $config['option'] = array();
-            } else {
-                $config['where']['id'] = array('yes', 'in');
-            }
-        }
-
-        return $config;
-    }
-
-    /**
-     * _delete
-     *
-     * @return mixd
-     */
-    protected function _delete()
-    {
-        return array
-        (
-            'type' => 'delete',
-            'option' => array(),
-            //'where' => array('id' => 'yes'),
-        );
-    }
-
-    /**
-     * _insert
-     *
-     * @return mixd
-     */
-    protected function _insert()
-    {
-        return array
-        (
-            'type' => 'insert',
-            'add' => array(),
-        );
-    }
-
-    /**
-     * _inserts
-     *
-     * @return mixd
-     */
-    protected function _inserts()
-    {
-        return array
-        (
-            'type' => 'inserts',
-            'add' => array(),
-        );
-    }
-}

+ 0 - 104
src/Dever/Data/Mongo/Connect.php

@@ -1,104 +0,0 @@
-<?php namespace Dever\Data\Mongo;
-
-use Dever\Output\Debug;
-use MongoDB\Driver\Manager as Mongo;
-
-class Connect
-{
-    /**
-     * handle
-     *
-     * @var object
-     */
-    private $handle;
-
-    /**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * getInstance
-     *
-     * @return Dever\Data\Mongo\Connect;
-     */
-    public static function getInstance($config)
-    {
-        $key = $config['host'] . $config['database'];
-        if (empty(self::$instance[$key])) {
-            self::$instance[$key] = new self();
-            self::$instance[$key]->init($config);
-        }
-
-        return self::$instance[$key];
-    }
-
-    /**
-     * init
-     *
-     * @return mixd
-     */
-    private function init($config)
-    {
-        if (strpos($config['host'], ':') !== false) {
-            list($config['host'], $config['port']) = explode(':', $config['host']);
-        }
-
-        try
-        {
-            if (!isset($config['timeout'])) {
-                $config['timeout'] = 1000;
-            }
-            $this->handle = new Mongo('mongodb://' . $config['host'] . ':' . $config['port'], array("connectTimeoutMS" => $config['timeout']));
-
-            $this->db = $config['database'];
-
-            Debug::log('mongodb ' . $config['host'] . ' connected', $config['type']);
-        } catch (\PDOException $e) {
-            echo $e->getMessage();die;
-        }
-    }
-
-    /**
-     * __destruct
-     *
-     * @return mixd
-     */
-    public function __destruct()
-    {
-        $this->close();
-    }
-
-    /**
-     * table
-     *
-     * @return mixd
-     */
-    public function table($table)
-    {
-        return $this->handle;
-        //return $this->handle->selectCollection($table);
-    }
-
-    /**
-     * handle
-     *
-     * @return object
-     */
-    public function handle()
-    {
-        return $this->handle;
-    }
-
-    /**
-     * close
-     *
-     * @return mixd
-     */
-    public function close()
-    {
-        $this->handle = null;
-    }
-}

+ 0 - 494
src/Dever/Data/Mongo/Store.php

@@ -1,494 +0,0 @@
-<?php namespace Dever\Data\Mongo;
-
-use Dever\Data\Store as Base;
-use MongoDB\Driver\Command;
-use MongoDB\Driver\BulkWrite;
-use MongoDB\Driver\Query;
-use MongoDB\BSON\Regex;
-use MongoDB\BSON\ObjectId;
-
-class Store extends Base
-{
-    /**
-     * init
-     *
-     * @return mixd
-     */
-    public function init()
-    {
-        return;
-    }
-
-    /**
-     * connect
-     *
-     * @return mixd
-     */
-    public function connect($config)
-    {
-        return Connect::getInstance($config);
-    }
-
-    /**
-     * setTable
-     *
-     * @return mixd
-     */
-    public function setTable($table)
-    {
-        $this->register();
-        $this->table = $this->read->db . '.' . $table;
-        $this->connect = $this->read->table($table);
-    }
-
-    /**
-     * getIndex
-     *
-     * @return mixed
-     */
-    public function getIndex($version, $index)
-    {
-        $return = $this->connect->ensureIndex($index[$version], array('name' => ''));
-
-        $this->log($index[$version], 'index');
-
-        $data['index'] = $version;
-
-        return $data;
-    }
-
-    /**
-     * alter table
-     *
-     * @return mixed
-     */
-    public function alter($alter, $struct = array(), $name = '')
-    {
-        return true;
-    }
-
-    /**
-     * query table
-     *
-     * @return mixed
-     */
-    public function query($sql, $state = true)
-    {
-        return true;
-    }
-
-    /**
-     * exe table
-     *
-     * @return mixed
-     */
-    public function exe($sql, $value = array(), $method = 'fetchAll')
-    {
-        return true;
-    }
-
-    /**
-     * insert the default value
-     *
-     * @return mixed
-     */
-    public function getInserts($value)
-    {
-        $col = explode(',', $value['col']);
-        $value = explode(',', $value['value']);
-
-        foreach ($col as $k => $v) {
-            $this->value['add'][$v] = $value[$k];
-            $this->insert();
-        }
-
-        $this->log($value, 'inserts');
-
-        $data = include $file;
-
-        $data['insert'] = $value;
-
-        return $data;
-    }
-
-    /**
-     * all
-     *
-     * @return array
-     */
-    public function all($col)
-    {
-        $key = false;
-        if (strpos($col, '|') !== false) {
-            $array = explode('|', $col);
-            $key = $array[1];
-            $col = $array[0];
-        }
-        $data = $this->select($col, 'find');
-
-        $result = array();
-
-        if ($data) {
-            foreach ($data as $k => $v) {
-                $v = (array)$v;
-                $v['id'] = (array) $v['_id'];
-                $v['id'] = $v['id']['oid'];
-                unset($v['_id']);
-                if (isset($v[$key])) {
-                    if (isset($array[3]) && isset($v[$array[2]])) {
-                        $result[$v[$key]][$v[$array[2]]] = $v;
-                    } elseif (isset($array[2]) && isset($v[$array[2]])) {
-                        $result[$v[$key]] = $v[$array[2]];
-                    } elseif (isset($array[2])) {
-                        $result[$v[$key]][] = $v;
-                    } else {
-                        $result[$v[$key]] = $v;
-                    }
-                } else {
-                    $result[] = $v;
-                }
-            }
-        }
-
-        return $result;
-    }
-
-    /**
-     * one
-     *
-     * @return array
-     */
-    public function one($col = '')
-    {
-        $data = $this->select($col, 'findOne');
-        $result = array();
-
-        if ($data) {
-            foreach ($data as $k => $v) {
-                $v = (array)$v;
-                $v['id'] = (array) $v['_id'];
-                $v['id'] = $v['id']['oid'];
-                unset($v['_id']);
-                $result = $v;
-            }
-        }
-
-        return $result;
-    }
-
-    /**
-     * count
-     *
-     * @return array
-     */
-    public function count($col = 'clear')
-    {
-        return $this->select($col, 'count');
-    }
-
-    /**
-     * insert
-     *
-     * @return int
-     */
-    public function insert($num = 1)
-    {
-        $insert = array();
-        foreach ($this->value['add'] as $k => $v) {
-            if (is_numeric($v)) {
-                $v = (float) $v;
-            }
-            $insert[$k] = $v;
-        }
-        $bulk = new BulkWrite;
-        if ($num > 1) {
-            $data = $insert;
-            $insert = array();
-            foreach ($i = 0; $i < $num; $i++) {
-                $insert[] = $data;
-            }
-        }
-        $id = $bulk->insert($insert);
-        $result = $this->connect->executeBulkWrite($this->table, $bulk);
-        $this->log($this->value, 'insert');
-        $this->value = array();
-        if ($result->getInsertedCount() >= 1) {
-            return (string) $id;
-        }
-        return false;
-    }
-
-    /**
-     * update
-     *
-     * @return int
-     */
-    public function update()
-    {
-        $update = array();
-        foreach ($this->value['set'] as $k => $v) {
-            if (is_numeric($v)) {
-                $v = (float) $v;
-            }
-            $update[$k] = $v;
-        }
-        $update = array('$set' => $update);
-        $param = array('multi' => true, 'upsert' => false);
-        $bulk = new BulkWrite;
-        $bulk->update($this->value['where'], $update, $param);
-        $result = $this->connect->executeBulkWrite($this->table, $bulk);
-        $this->log($this->value, 'update');
-        $this->value = array();
-        return $result->getModifiedCount();
-    }
-
-    /**
-     * delete
-     *
-     * @return int
-     */
-    public function delete()
-    {
-        $bulk = new BulkWrite;
-        $bulk->delete($this->value['where']);
-        $result = $this->connect->executeBulkWrite($this->table, $bulk);
-        $this->log($this->value, 'delete');
-        $this->value = array();
-        return $result->getDeletedCount();
-    }
-
-    /**
-     * command
-     *
-     * @return mixd
-     */
-    public function command(array $param) {
-        return $this->connect->executeCommand($this->table, new Command($param));
-    }
-
-    /**
-     * select
-     *
-     * @return array
-     */
-    private function select($col = '', $method = 'find')
-    {
-        $filter = array();
-        $options = array();
-        if (isset($this->value['where'])) {
-            $filter = $this->value['where'];
-        }
-        if (isset($filter['state'])) {
-            $filter['state'] = (string) $filter['state'];
-        }
-        
-        if ($method == 'count') {
-            $query = new Query($filter, $options);
-            $cursor = $this->connect->executeQuery($this->table, $query);
-            $result = count($cursor->toArray());
-        } else {
-            if (isset($this->value['order'])) {
-                $options['sort'] = $this->value['order'];
-            }
-            if (isset($this->value['limit'])) {
-                foreach ($this->value['limit'] as $k => $v) {
-                    $options['skip'] = $k;
-                    $options['limit'] = $v;
-                }
-            }
-            if ($col && $col != '*' && $col != 'clear') {
-                if (is_string($col)) {
-                    $temp = explode(',', $col);
-                    $col = array();
-                    foreach ($temp as $k => $v) {
-                        $options['projection'][$v] = true;
-                    }
-                }
-            }
-
-            $query = new Query($filter, $options);
-            $result = $this->connect->executeQuery($this->table, $query);
-        }
-
-        $this->log($this->value, 'select');
-
-        if ($col != 'clear') {
-            $this->value = array();
-        }
-
-        return $result;
-    }
-
-    /**
-     * join
-     *
-     * @return object
-     */
-    public function join($param)
-    {
-        return $this;
-    }
-
-    /**
-     * __call
-     *
-     * @return object
-     */
-    public function __call($method, $param)
-    {
-        if (is_array($param[0])) {
-            foreach ($param[0] as $k => $v) {
-                if ($method == 'order') {
-                    $this->call($method, array($k, $v));
-                } else {
-                    $this->call($method, $v);
-                }
-            }
-        } else {
-            $this->call($method, $param);
-        }
-
-        return $this;
-    }
-
-    /**
-     * call
-     *
-     * @return mixd
-     */
-    private function call($method, $param)
-    {
-        if (is_array($param) && isset($param[0])) {
-            if ($param[0] == 'id') {
-                $param[0] = '_id';
-            }
-
-            $func = 'convert_' . $method;
-            if (method_exists($this, $func)) {
-                $this->$func($param);
-            }
-            if (is_array($param) && isset($param[1])) {
-                $this->value[$method][$param[0]] = $param[1];
-            } else {
-                $this->value[$method] = $param;
-            }
-        } else {
-            $this->value[$method] = $param;
-        }
-    }
-
-    /**
-     * convert_order
-     *
-     * @return mixed
-     */
-    private function convert_order(&$param)
-    {
-        switch ($param[1]) {
-            case 'desc':
-                $param[1] = -1;
-                break;
-            case 'asc':
-                $param[1] = 1;
-                break;
-        }
-    }
-
-    /**
-     * convert_limit
-     *
-     * @return mixed
-     */
-    private function convert_limit(&$param)
-    {
-        $param = explode(',', $param[0]);
-    }
-
-    /**
-     * convert_group
-     *
-     * @return mixed
-     */
-    private function convert_group(&$param)
-    {
-        print_r($param);die;
-    }
-
-    /**
-     * convert_where
-     *
-     * @return mixed
-     */
-    private function convert_where(&$param)
-    {
-        if (is_numeric($param[1])) {
-            $param[1] = (int) $param[1];
-            return;
-        }
-        if (isset($param[2])) {
-            $state = true;
-            switch ($param[2]) {
-                case 'like':
-                    # 模糊查询
-                    $param[1] = (string) $param[1];
-                    if (strpos($param[1], '%') !== false) {
-                        $param[1] = str_replace('%', '(.*?)', $param[1]);
-                        $param[1] = new Regex($param[1], 'i');
-                    } else {
-                        $param[1] = new Regex($param[1] . '(.*?)', 'i');
-                    }
-                    $state = false;
-                    break;
-
-                case 'in':
-                case 'nin':
-                    # in查询
-                    $param[1] = explode(',', $param[1]);
-                    if ($param[0] == '_id') {
-                        foreach ($param[1] as $k => $v) {
-                            $param[1][$k] = new ObjectId($v);
-                        }
-                    }
-                    $param[2] = '$' . $param[2];
-                    break;
-
-                case '>':
-                    $param[2] = '$gt';
-                    break;
-                case '>=':
-                    $param[2] = '$gte';
-                    break;
-                case '<':
-                    $param[2] = '$lt';
-                    break;
-                case '<=':
-                    $param[2] = '$lte';
-                    break;
-                case '!=':
-                    $param[2] = '$ne';
-                    break;
-                case '%':
-                    $param[2] = '$mod';
-                    break;
-                case 'bt':
-                    $state = false;
-                    $param[1] = array('gt' => $param[1][0], 'lt' => $param[1][1]);
-                    break;
-                case 'bte':
-                    $state = false;
-                    $param[1] = array('gte' => $param[1][0], 'lte' => $param[1][1]);
-                    break;
-                default:
-                    $param[2] = '$' . $param[2];
-                    break;
-            }
-            if ($state == true) {
-                $param[1] = array($param[2] => $param[1]);
-            }
-        }
-
-        if ($param[0] == '_id' && is_string($param[1])) {
-            $param[1] = new ObjectId($param[1]);
-        }
-    }
-}

+ 0 - 225
src/Dever/Data/Mysql/Connect.php

@@ -1,225 +0,0 @@
-<?php namespace Dever\Data\Mysql;
-
-use Dever\Output\Debug;
-
-class Connect
-{
-    /**
-     * handle
-     *
-     * @var object
-     */
-    private $handle;
-
-    /**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * getInstance
-     *
-     * @return Dever\Data\Mysql\Connect;
-     */
-    public static function getInstance($config)
-    {
-        $key = $config['host'] . $config['database'];
-        if (empty(self::$instance[$key])) {
-            self::$instance[$key] = new self();
-            self::$instance[$key]->init($config);
-        }
-
-        return self::$instance[$key];
-    }
-
-    /**
-     * init
-     *
-     * @return mixd
-     */
-    private function init($config)
-    {
-        $this->handle = @mysql_connect($config['host'], $config['username'], $config['password'], true);
-
-        if (!$this->handle) {
-            die('Could not connect: ' . mysql_error());
-        }
-
-        Debug::log('db ' . $config['host'] . ' connected', $config['type']);
-
-        if (!mysql_select_db($config['database'], $this->handle)) {
-            $this->query("CREATE DATABASE `" . $config['database'] . "` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
-
-            if (!mysql_select_db($config['database'], $this->handle)) {
-                die("Can\'t use " . $config['database'] . " : " . mysql_error());
-            }
-        }
-
-        $this->query("set names '" . $config['charset'] . "'");
-        //$this->_log('connected mysql:' . $config['host']);
-    }
-
-    /**
-     * __construct
-     *
-     * @return mixd
-     */
-    public function __destruct()
-    {
-        $this->close();
-    }
-
-    /**
-     * handle
-     *
-     * @return object
-     */
-    public function handle()
-    {
-        return $this->handle;
-    }
-
-    /**
-     * close
-     *
-     * @return mixd
-     */
-    public function close()
-    {
-        @mysql_close($this->handle);
-        $this->handle = null;
-    }
-
-    /**
-     * fetchAll
-     *
-     * @return object
-     */
-    public function fetchAll($sql, $method = MYSQL_ASSOC)
-    {
-        $handle = $this->exec($sql);
-
-        $result = array();
-
-        while ($row = mysql_fetch_array($handle, $method)) {
-            $result[] = $row;
-        }
-
-        return $result;
-    }
-
-    /**
-     * fetch
-     *
-     * @return object
-     */
-    public function fetch($sql, $method = MYSQL_ASSOC)
-    {
-        $handle = $this->exec($sql);
-
-        $result = mysql_fetch_array($handle, $method);
-
-        return $result;
-    }
-
-    /**
-     * exec
-     *
-     * @return object
-     */
-    public function exec($sql)
-    {
-        # 同步执行
-        if (strpos($sql, ';')) {
-            $temp = explode(';', $sql);
-            foreach ($temp as $k => $v) {
-                $this->exec($v);
-            }
-
-            return true;
-        } else {
-            return mysql_query($sql, $this->handle);
-        }
-    }
-
-    /**
-     * query
-     *
-     * @return object
-     */
-    public function query($sql)
-    {
-        $this->exec($sql);
-
-        return $this;
-    }
-
-    /**
-     * rowCount
-     *
-     * @return object
-     */
-    public function rowCount()
-    {
-        return mysql_affected_rows();
-    }
-
-    /**
-     * fetchColumn
-     *
-     * @return object
-     */
-    public function fetchColumn($sql)
-    {
-        $handle = $this->exec($sql);
-
-        $result = mysql_fetch_row($handle);
-
-        return $result[0];
-    }
-
-    /**
-     * lastid
-     *
-     * @return int
-     */
-    public function id()
-    {
-        return mysql_insert_id($this->handle);
-    }
-
-    /**
-     *
-     * @desc 释放结果内存
-     * @param  $query SQL语句
-     * @return  Boolean
-     * @author alfa  2011-2-17
-     */
-    public function freeResult($query)
-    {
-        return @mysql_free_result($query);
-    }
-
-    /**
-     * @desc 得到错误编号
-     * @return (int)错误编号
-     * @author alfa  2011-2-17
-     */
-    public function getErrno()
-    {
-        return mysql_errno();
-    }
-
-    /**
-     *
-     * @desc 得到错误消息
-     * @return (string)错误消息
-     * @author alfa  2011-2-17
-     */
-    public function getError()
-    {
-        return mysql_error();
-    }
-}

+ 0 - 402
src/Dever/Data/Mysql/Store.php

@@ -1,402 +0,0 @@
-<?php namespace Dever\Data\Mysql;
-
-use Dever\Data\Sql;
-use Dever\Data\Store as Base;
-
-class Store extends Base
-{
-    /**
-     * init
-     *
-     * @return mixd
-     */
-    public function init()
-    {
-        $this->sql = Sql::getInstance();
-    }
-
-    /**
-     * connect
-     *
-     * @return mixd
-     */
-    public function connect($config)
-    {
-        return Connect::getInstance($config);
-    }
-
-    /**
-     * setTable
-     *
-     * @return mixd
-     */
-    public function setTable($table)
-    {
-        $this->table = $table;
-    }
-
-    /**
-     * getIndex
-     *
-     * @return mixed
-     */
-    public function getIndex($version, $index)
-    {
-        $this->register();
-        $sql = $this->sql->showIndex($this->table);
-
-        $info = $this->update->fetchAll($sql);
-
-        if ($info) {
-            foreach ($info as $k => $v) {
-                if ($v['Key_name'] != 'PRIMARY') {
-                    $sql = $this->sql->dropIndex($this->table, $v['Key_name']);
-                    $this->update->query($sql);
-                }
-            }
-        }
-
-        $sql = $this->sql->index($this->table, $index[$version]);
-
-        $this->query($sql);
-
-        $this->log($sql, 'index');
-
-        $data['index'] = $version;
-
-        $data['order'] = array_flip(explode(',', array_shift($index[$version])));
-
-        return $data;
-    }
-
-    public function exe($sql, $value = array(), $method = 'fetchAll')
-    {
-        $this->register();
-        if (stristr($sql, 'select')) {
-            $db = $this->read;
-        } else {
-            $db = $this->update;
-        }
-
-        $sql = $this->replace($sql, $value);
-
-        $handle = $db->query($sql);
-
-        if ($method) {
-            $data = $handle->$method();
-            $this->log($sql, false, $data);
-            return $data;
-        } else {
-            return $handle;
-        }
-    }
-
-    public function query($sql, $state = true)
-    {
-        if (empty($this->config['shell'])) {
-            if (strpos($this->config['host'], ':') !== false) {
-                $temp = explode(':', $this->config['host']);
-                $this->config['host'] = $temp[0];
-                $this->config['port'] = $temp[1];
-            }
-
-            $this->config['shell'] = 'mysql -u' . $this->config['username'] . ' -p' . $this->config['password'] . ' ' . $this->config['database'] . ' -h' . $this->config['host'] . ' -P' . $this->config['port'] . ' -e ';
-        }
-
-        if ($state == true) {
-            # 异步执行
-            \Dever::run($this->config['shell'] . '"' . $sql . '"');
-        } else {
-            $this->register();
-            # 同步执行
-            if (strpos($sql, ';')) {
-                $temp = explode(';', $sql);
-                foreach ($temp as $k => $v) {
-                    $this->update->query($v);
-                }
-            } else {
-                $this->update->query($sql);
-            }
-        }
-    }
-
-    /**
-     * insert the default value
-     *
-     * @return mixed
-     */
-    public function getInserts($value, $data = array())
-    {
-        $this->register();
-        $sql = $this->sql->inserts($this->table, $value['col'], $value['value']);
-
-        $this->update->query($sql);
-
-        $this->log($sql, 'inserts');
-
-        $data['insert'] = $sql;
-
-        return $data;
-    }
-
-    /**
-     * all
-     *
-     * @return array
-     */
-    public function all($col)
-    {
-        $key = false;
-        if (strpos($col, '|') !== false) {
-            $array = explode('|', $col);
-            $key = $array[1];
-            $col = $array[0];
-        }
-        $data = $this->select($col, 'fetchAll');
-
-        if ($data && $key) {
-            $result = array();
-
-            foreach ($data as $k => $v) {
-                if (isset($v[$key])) {
-                    if (isset($array[3]) && isset($v[$array[2]])) {
-                        $result[$v[$key]][$v[$array[2]]] = $v;
-                    } elseif (isset($array[2]) && isset($v[$array[2]])) {
-                        $result[$v[$key]] = $v[$array[2]];
-                    } elseif (isset($array[2])) {
-                        $result[$v[$key]][] = $v;
-                    } else {
-                        $result[$v[$key]] = $v;
-                    }
-                }
-            }
-
-            return $result;
-        }
-
-        return $data;
-    }
-
-    /**
-     * one
-     *
-     * @return array
-     */
-    public function one($col)
-    {
-        return $this->select($col);
-    }
-
-    /**
-     * count
-     *
-     * @return array
-     */
-    public function count($col = '')
-    {
-        return $this->select($col, 'fetchColumn', 'count');
-    }
-
-    /**
-     * insert
-     *
-     * @return int
-     */
-    public function insert()
-    {
-        $this->register();
-        $sql = $this->sql->insert($this->table);
-
-        $id = $this->update->query($sql)->id();
-
-        $this->log($sql, $this->value);
-
-        $this->cache();
-
-        $this->value = array();
-
-        return $id;
-    }
-
-    /**
-     * update
-     *
-     * @return int
-     */
-    public function update()
-    {
-        $this->register();
-        $sql = $this->sql->update($this->table);
-
-        $result = false;
-
-        if ($sql) {
-            $result = $this->update->query($sql)->rowCount();
-            //$result = $this->update->query($sql)->id();
-
-            $this->log($sql, $this->value);
-
-            $this->cache();
-        }
-
-        $this->value = array();
-
-        return $result;
-    }
-
-    /**
-     * delete
-     *
-     * @return int
-     */
-    public function delete()
-    {
-        $this->register();
-        $sql = $this->sql->delete($this->table);
-
-        $result = false;
-
-        if ($sql) {
-            $result = $this->update->query($sql)->rowCount();
-
-            $this->log($sql, $this->value);
-
-            $this->cache();
-        }
-
-        $this->value = array();
-
-        return $result;
-    }
-
-    /**
-     * select
-     *
-     * @return array
-     */
-    private function select($col = '', $method = 'fetch', $type = 'select')
-    {
-        $sql = $this->sql->{$type}($this->table, $col);
-
-        $key = $this->table . '_' . $method . '_' . md5($sql);
-
-        $data = $this->cache($key);
-
-        if ($data) {
-            if ($col != 'clear') {
-                $this->value = array();
-            }
-
-            return $data;
-        }
-
-        if ($type == 'count' && strpos($sql, 'group by `')) {
-            $method = 'fetchAll';
-        }
-        $this->register();
-
-        $data = $this->read->$method($sql);
-
-        $this->cache($key, 'put', $data);
-
-        $this->log($sql, $this->value, $data);
-
-        if ($col != 'clear') {
-            $this->value = array();
-        }
-
-        return $data;
-    }
-
-    /**
-     * join
-     *
-     * @return object
-     */
-    public function join($param)
-    {
-        $this->sql->join($param);
-
-        return $this;
-    }
-
-    /**
-     * begin
-     *
-     * @return object
-     */
-    public function begin()
-    {
-        $this->register();
-        $this->update->query('start transaction');
-
-        return $this;
-    }
-
-    /**
-     * commit
-     *
-     * @return object
-     */
-    public function commit()
-    {
-        $this->register();
-        $this->update->query('commit');
-
-        return $this;
-    }
-
-    /**
-     * rollback
-     *
-     * @return object
-     */
-    public function rollback()
-    {
-        $this->register();
-        $this->update->query('rollback');
-
-        return $this;
-    }
-
-    /**
-     * __call
-     *
-     * @return object
-     */
-    public function __call($method, $param)
-    {
-        if (is_array($param[0]) && $method != 'order') {
-            foreach ($param[0] as $k => $v) {
-                $this->call($method, $v);
-            }
-        } else {
-            $this->call($method, $param);
-        }
-
-        return $this;
-    }
-
-    /**
-     * call
-     *
-     * @return mixd
-     */
-    private function call($method, $param)
-    {
-        if ($method == 'where' || $method == 'set' || $method == 'add') {
-            # 特殊处理in
-            if (isset($param[2]) && $param[2] == 'in') {
-                if (is_array($param[1])) {
-                    $param[1] = '(' . implode(',', $param[1]) . ')';
-                } else {
-                    $param[1] = '(' . $param[1] . ')';
-                }
-            } else {
-                $param[1] = is_numeric($param[1]) ? intval($param[1]) : '"' . $param[1] . '"';
-            }
-        }
-
-        $this->sql->$method($param);
-    }
-}

+ 0 - 202
src/Dever/Data/Pdo/Connect.php

@@ -1,202 +0,0 @@
-<?php namespace Dever\Data\Pdo;
-
-use Dever\Output\Debug;
-use Dever\Output\Export;
-
-class Connect
-{
-    /**
-     * handle
-     *
-     * @var object
-     */
-    private $handle;
-
-    /**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * getInstance
-     *
-     * @return Dever\Data\Pdo\Connect;
-     */
-    public static function getInstance($config)
-    {
-        $key = $config['host'] . $config['database'];
-        if (empty(self::$instance[$key])) {
-            self::$instance[$key] = new self();
-            self::$instance[$key]->init($config);
-        }
-
-        return self::$instance[$key];
-    }
-
-    /**
-     * init
-     *
-     * @return mixd
-     */
-    private function init($config)
-    {
-        if ($this->handle) {
-            return;
-        }
-        if (strpos($config['host'], ':') !== false) {
-            list($config['host'], $config['port']) = explode(':', $config['host']);
-        }
-
-        $dsn['type'] = $config['type'];
-        $dsn['host'] = $config['host'];
-        $dsn['port'] = $config['port'];
-        $dsn['dbname'] = $config['database'];
-        $dsn['charset'] = $config['charset'];
-
-        if (!isset($config['collation'])) {
-            $config['collation'] = 'utf8mb4_general_ci';
-        }
-        $dsn['collation'] = $config['collation'];
-
-        foreach ($dsn as $key => $val) {
-            $dsn[$key] = "$key=$val";
-        }
-
-        $type = isset($config['pdo_type']) ? $config['pdo_type'] : 'mysql';
-        $dsnList = $type . ':' . implode(';', $dsn);
-
-        try {
-            $persistent = false;
-            if (isset($config['persistent'])) {
-                $persistent = $config['persistent'];
-            }
-            $this->handle = new \PDO($dsnList, $config['username'], $config['password'], array(\PDO::ATTR_PERSISTENT => $persistent));
-            $this->handle->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
-            //$this->handle->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
-            $this->handle->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_NATURAL);
-            $this->handle->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
-            //$this->handle->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
-
-            Debug::log('db ' . $config['host'] . ' connected', $config['type']);
-        } catch (\PDOException $e) {
-            if (strstr($e->getMessage(), 'Unknown database')) {
-                $method = 'mysql';
-                if (function_exists('mysqli_connect')) {
-                    $method = 'mysqli';
-                }
-                $connect = $method . '_connect';
-                $query = $method . '_query';
-                $close = $method . '_close';
-                $link = $connect($config['host'] . ':' . $config['port'], $config['username'], $config['password']);
-                if ($link) {
-                    if ($method == 'mysql') {
-                        $query("CREATE DATABASE `" . $config['database'] . "` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;", $link);
-                    } else {
-                        $query($link, "CREATE DATABASE `" . $config['database'] . "` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;");
-                    }
-                    
-                    $close($link);
-                }
-                
-                $this->init($config);
-            } else {
-                Export::alert($e->getMessage());
-            }
-        }
-
-        //$this->query("set names '".$config['charset']."'");
-        //$this->_log('connected mysql:' . $config['host']);
-    }
-
-    public function set()
-    {
-        //$this->handle->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
-        $this->handle->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
-    }
-
-    /**
-     * __construct
-     *
-     * @return mixd
-     */
-    public function __destruct()
-    {
-        $this->close();
-    }
-
-    /**
-     * handle
-     *
-     * @return object
-     */
-    public function handle()
-    {
-        return $this->handle;
-    }
-
-    /**
-     * close
-     *
-     * @return mixd
-     */
-    public function close()
-    {
-        $this->handle = null;
-    }
-
-    /**
-     * prepare
-     *
-     * @return object
-     */
-    public function prepare($sql)
-    {
-        return $this->handle->prepare($sql);
-    }
-
-    /**
-     * exec
-     *
-     * @return object
-     */
-    public function exec($sql)
-    {
-        return $this->handle->exec($sql);
-    }
-
-    /**
-     * query
-     *
-     * @return object
-     */
-    public function query($sql)
-    {
-        if ($sql) {
-            return $this->handle->query($sql);
-        }
-
-        return false;
-    }
-
-    /**
-     * lastid
-     *
-     * @return int
-     */
-    public function id()
-    {
-        return $this->handle->lastInsertId();
-    }
-
-    /**
-     * method
-     *
-     * @return mixed
-     */
-    public function method($method)
-    {
-        return $this->handle->$method();
-    }
-}

+ 0 - 503
src/Dever/Data/Pdo/Store.php

@@ -1,503 +0,0 @@
-<?php namespace Dever\Data\Pdo;
-
-use Dever\Data\Sql;
-use Dever\Data\Store as Base;
-
-class Store extends Base
-{
-    /**
-     * init
-     *
-     * @return mixd
-     */
-    public function init()
-    {
-        $this->sql = Sql::getInstance();
-    }
-
-    /**
-     * connect
-     *
-     * @return mixd
-     */
-    public function connect($config)
-    {
-        return Connect::getInstance($config);
-    }
-
-    /**
-     * setTable
-     *
-     * @return mixd
-     */
-    public function setTable($table)
-    {
-        $this->table = $table;
-    }
-
-    /**
-     * getIndex
-     *
-     * @return mixed
-     */
-    public function getIndex($version, $index)
-    {
-        $this->register();
-        $sql = $this->sql->showIndex($this->table);
-
-        $handle = $this->update->query($sql);
-
-        $info = $handle->fetchAll();
-
-        $this->dropIndex($info);
-
-        $sql = $this->sql->index($this->table, $index[$version]);
-
-        $this->query($sql);
-
-        $this->log($sql, 'index');
-
-        $data['index'] = $version;
-
-        $data['order'] = array_flip(explode(',', array_shift($index[$version])));
-
-        return $data;
-    }
-
-    private function dropIndex($info)
-    {
-        if ($info) {
-            $this->register();
-            $index = array();
-            foreach ($info as $k => $v) {
-                if ($v['Key_name'] != 'PRIMARY' && !isset($index[$v['Key_name']])) {
-                    $sql = $this->sql->dropIndex($this->table, $v['Key_name']);
-                    $this->update->query($sql);
-                    $index[$v['Key_name']] = true;
-                }
-            }
-        }
-    }
-
-    public function exe($sql, $value = array(), $method = '')
-    {
-        $create = false;
-        if (stristr($sql, 'create')) {
-            $create = true;
-        }
-        $this->register($create);
-        
-        if ($create && isset($this->create)) {
-            $db = $this->create;
-        } elseif (stristr($sql, 'select')) {
-            $db = $this->read;
-        } else {
-            $db = $this->update;
-        }
-
-        if (!is_array($value)) {
-            $value = array(':0' => $value);
-        }
-
-        try {
-            if ($value) {
-                $handle = $db->prepare($sql);
-                $handle->execute($value);
-            } else {
-                $handle = $db->query($sql);
-            }
-        } catch (\PDOException $exception) {
-            $this->error($exception->getMessage(), $sql);
-        }
-
-        if ($method) {
-            $data = $handle->$method();
-            $this->log($sql, $value, $data);
-            return $data;
-        } else {
-            return $handle;
-        }
-    }
-
-    public function query($sql, $state = false)
-    {
-        if (empty($this->config['shell'])) {
-            if (is_string($this->config['host']) && strpos($this->config['host'], ':') !== false) {
-                $temp = explode(':', $this->config['host']);
-                $this->config['host'] = $temp[0];
-                $this->config['port'] = $temp[1];
-            } elseif (isset($this->config['host']['read']) && strpos($this->config['host']['read'], ':') !== false) {
-                $temp = explode(':', $this->config['host']['read']);
-                $this->config['host'] = $temp[0];
-                $this->config['port'] = $temp[1];
-            }
-
-            $this->config['shell'] = 'mysql -u' . $this->config['username'] . ' -p' . $this->config['password'] . ' ' . $this->config['database'] . ' -h' . $this->config['host'] . ' -P' . $this->config['port'] . ' -e ';
-        }
-
-        if ($state == true) {
-            # 异步执行
-            \Dever::run($this->config['shell'] . '"' . $sql . '"');
-        } else {
-            try {
-                $this->register();
-                # 同步执行
-                if (strpos($sql, ';')) {
-                    $temp = explode(';', $sql);
-                    foreach ($temp as $k => $v) {
-                        $this->update->query($v);
-                    }
-                } else {
-                    $this->update->query($sql);
-                }
-            } catch (\PDOException $exception) {
-                $this->error($exception->getMessage(), $sql);
-            }
-        }
-    }
-
-    /**
-     * insert the default value
-     *
-     * @return mixed
-     */
-    public function insertValues($value, $data = array())
-    {
-        $this->register();
-        $sql = $this->sql->insertValues($this->table, $value['col'], $value['value']);
-
-        try {
-            $this->update->query($sql);
-        } catch (\PDOException $exception) {
-            $this->error($exception->getMessage(), $sql);
-        }
-
-        $this->log($sql, 'insertValues');
-
-        $data['insert'] = $sql;
-
-        return $data;
-    }
-
-    /**
-     * all
-     *
-     * @return array
-     */
-    public function all($col, $call = false)
-    {
-        $config = false;
-        if (strpos($col, '|') !== false) {
-            $config = explode('|', $col);
-            $col = $config[0];
-        }
-        return $this->select($col, 'fetchAll', 'select', $config, $call);
-    }
-
-    /**
-     * one
-     *
-     * @return array
-     */
-    public function one($col)
-    {
-        return $this->select($col);
-    }
-
-    /**
-     * count
-     *
-     * @return array
-     */
-    public function count($col = '')
-    {
-        return $this->select($col, 'fetchColumn', 'count');
-    }
-
-    /**
-     * insert
-     *
-     * @return int
-     */
-    public function insert($num = 1)
-    {
-        $sql = $this->sql->insert($this->table, $num);
-
-        if ($sql) {
-            try {
-                $this->register();
-
-                $handle = $this->update->prepare($sql);
-
-                $handle->execute($this->value);
-            } catch (\PDOException $exception) {
-                $this->error($exception->getMessage(), $sql);
-            }
-
-            $id = $this->update->id();
-
-            $this->log($sql, $this->value);
-
-            $this->cache();
-        }
-
-        $this->value = array();
-
-        return $id;
-    }
-
-    /**
-     * update
-     *
-     * @return int
-     */
-    public function update()
-    {
-        $sql = $this->sql->update($this->table);
-
-        $result = false;
-
-        if ($sql) {
-            try {
-                $this->register();
-
-                $handle = $this->update->prepare($sql);
-
-                $handle->execute($this->value);
-            } catch (\PDOException $exception) {
-                $this->error($exception->getMessage(), $sql);
-            }
-
-            $result = $handle->rowCount();
-            //$result = $this->update->id();
-
-            $this->log($sql, $this->value);
-
-            $this->cache();
-        }
-
-        $this->value = array();
-
-        return $result;
-    }
-
-    /**
-     * delete
-     *
-     * @return int
-     */
-    public function delete()
-    {
-        $sql = $this->sql->delete($this->table);
-
-        $result = false;
-
-        if ($sql) {
-            try {
-                $this->register();
-
-                $handle = $this->update->prepare($sql);
-
-                $handle->execute($this->value);
-            } catch (\PDOException $exception) {
-                $this->error($exception->getMessage(), $sql);
-            }
-
-            $result = $handle->rowCount();
-
-            $this->log($sql, $this->value);
-
-            $this->cache();
-        }
-
-        $this->value = array();
-
-        return $result;
-    }
-
-    /**
-     * select
-     *
-     * @return array
-     */
-    private function select($col = '', $method = 'fetch', $type = 'select', $config = false, $call = false)
-    {
-        $sql = $this->sql->{$type}($this->table, $col);
-
-        $key = $this->table . '_' . $method . '_' . md5(serialize($this->value) . $sql);
-
-        $data = $this->cache($key);
-
-        if ($data !== false) {
-            if ($col != 'clear') {
-                $this->value = array();
-            }
-
-            return $data;
-        }
-
-        if ($type == 'count' && strpos($sql, 'group by `')) {
-            $method = 'fetchAll';
-        }
-
-        try {
-            $this->register();
-
-            if ($this->value) {
-                $handle = $this->read->prepare($sql);
-                /*
-                if ($method == 'fetchAll') {
-                    # 查询大量数据时,不缓存数据到内存,防止内存溢出
-                    $this->read->set();
-                }*/
-                $handle->execute($this->value);
-            } else {
-                $handle = $this->read->query($sql);
-            }
-        } catch (\PDOException $exception) {
-            $this->error($exception->getMessage(), $sql);
-        }
-
-        if ($method == 'fetchAll') {
-            if ($call) {
-                $this->value = array();
-            }
-            $data = $this->fetchAll($handle, $config, $call);
-            
-        } else {
-            $data = $handle->$method();
-        }
-
-        //print_r($data);die;
-        $state = $this->cache($key, 'put', $data);
-        $this->log($sql, $this->value, $data);
-        if ($col != 'clear') {
-            $this->value = array();
-        }
-        return $data;
-    }
-
-    /**
-     * join
-     *
-     * @return object
-     */
-    public function join($param)
-    {
-        $this->sql->join($param);
-
-        return $this;
-    }
-
-    /**
-     * begin
-     *
-     * @return object
-     */
-    public function begin()
-    {
-        $this->register();
-        $this->update->method('beginTransaction');
-
-        return $this;
-    }
-
-    /**
-     * commit
-     *
-     * @return object
-     */
-    public function commit()
-    {
-        $this->register();
-        $this->update->method('commit');
-
-        return $this;
-    }
-
-    /**
-     * rollback
-     *
-     * @return object
-     */
-    public function rollback()
-    {
-        $this->register();
-        $this->update->method('rollBack');
-
-        return $this;
-    }
-
-    /**
-     * __call
-     *
-     * @return object
-     */
-    public function __call($method, $param)
-    {
-        if (isset($param[0]) && is_array($param[0]) && $method != 'order') {
-            foreach ($param[0] as $k => $v) {
-                $this->call($method, $v);
-            }
-        } else {
-            $this->call($method, $param);
-        }
-
-        return $this;
-    }
-
-    /**
-     * call
-     *
-     * @return mixd
-     */
-    private function call($method, $param)
-    {
-        if ($method == 'where' || $method == 'set' || $method == 'add') {
-            # 特殊处理in
-            if (!strstr($param[1], '/') && strstr($param[1], 'select') && $param[1] != 'selected') {
-
-            } elseif (isset($param[2]) && ($param[2] == 'in' || $param[2] == 'not in')) {
-                if (!is_array($param[1])) {
-                    $param[1] = explode(',', $param[1]);
-                }
-
-                $prefix = 'in_';
-                $temp = $param[0];
-                foreach ($param[1] as $k => $v) {
-                    if (strpos($temp, '.')) {
-                        $temp = str_replace('.', '_', $temp);
-                    }
-                    $k = ':' . $temp . '_' . $prefix . $k;
-                    $key[] = $k;
-                    $this->value[$k] = $v;
-                }
-
-                $param[1] = '(' . implode(',', $key) . ')';
-            } else {
-                $prefix = $param[0];
-                if (strstr($prefix, ',')) {
-                    $prefix = str_replace(',', '_', $prefix);
-                }
-                if (strstr($prefix, '.')) {
-                    $prefix = str_replace('.', '_', $prefix);
-                }
-                if (strstr($prefix, '-')) {
-                    $prefix = str_replace('-', '_', $prefix);
-                }
-                $key = ':' . $prefix . count($this->value);
-
-                $this->value[$key] = $param[1];
-
-                $param[1] = $key;
-
-                if (isset($param[2]) && $param[2] == 'like') {
-                    $param[2] = 'like^' . $this->value[$key];
-                    //$this->value[$key] = trim($this->value[$key], ',');
-                }
-            }
-        }
-
-        $this->sql->$method($param);
-    }
-}

+ 0 - 857
src/Dever/Data/Sql.php

@@ -1,857 +0,0 @@
-<?php namespace Dever\Data;
-
-class Sql
-{
-    /**
-     * prefix
-     *
-     * @var string
-     */
-    private $prefix = '';
-    
-    /**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * getInstance
-     *
-     * @return Dever\Data\Sql;
-     */
-    public static function getInstance()
-    {
-        if (empty(self::$instance)) {
-            self::$instance = new self();
-        }
-
-        return self::$instance->init();
-    }
-
-    public function setColOrder($order)
-    {
-        $this->colOrder = $order;
-    }
-
-    /**
-     * create
-     *
-     * @return string
-     */
-    public function create($table, &$struct, $type = '', $partition = '', $state = false, $auto = 1)
-    {
-        $create = $primary = array();
-
-        foreach ($struct as $k => $v) {
-            if (isset($v['table']) && $v['table'] != $table) {
-                unset($struct[$k]);
-                $struct[$k . '_no_col'] = $v;
-                continue;
-            }
-            
-            $primary[$k] = '';
-            if (is_array($v)) {
-                if (!isset($v['type'])) {
-                    unset($struct[$k]);
-                    $struct[$k . '_no_col'] = $v;
-                    continue;
-                }
-                $com = $v;
-                $v = $com['type'];
-                if (strpos($com['type'], 'text') !== false) {
-                    $primary[$k] .= '';
-                } elseif (strpos($com['type'], 'int') === false && strpos($com['type'], 'float') === false && strpos($com['type'], 'decimal') === false) {
-                    $primary[$k] .= 'null';
-                } elseif (!empty($com['default'])) {
-                    $default = $com['default'];
-                    $com['default'] = '{default}';
-                    $primary[$k] .= 'not null default \'' . $com['default'] . '\'';
-                } elseif ($k != 'id' && (strpos($com['type'], 'int') !== false || strpos($com['type'], 'float') !== false || strpos($com['type'], 'decimal') !== false)) {
-                    $primary[$k] .= 'not null default 0';
-                } elseif ($k == 'id') {
-                    $primary[$k] .= 'not null';
-                } else {
-                    $primary[$k] .= 'null';
-                }
-
-                if (!empty($com['name'])) {
-                    $primary[$k] .= ' comment \'' . $com['name'] . '\'';
-                }
-            } elseif (is_string($v) && strpos($v, ' ') !== false) {
-                $com = explode(' ', $v);
-                $v = $com[0];
-                if (!empty($com[1])) {
-                    $default = $com[1];
-                    $com[1] = '{default}';
-                    $primary[$k] .= 'not null default \'' . $com[1] . '\'';
-                } else {
-                    $primary[$k] .= 'null';
-                }
-
-                if (!empty($com[2])) {
-                    $primary[$k] .= ' comment \'' . $com[2] . '\'';
-                }
-            }
-            if ($k == 'id') {
-                $primary[$k] = 'unsigned auto_increment primary key ' . $primary[$k];
-            }
-            if (strpos($v, '-')) {
-                $v = '`' . $k . '` ' . strtoupper(str_replace('-', '(', $v) . ') ' . $primary[$k] . '');
-            } else {
-                $v = '`' . $k . '` ' . strtoupper(str_replace('-', '(', $v) . ' ' . $primary[$k] . '');
-            }
-            
-            if (strpos($v, '{DEFAULT}') && isset($default)) {
-                $v = str_replace('{DEFAULT}', $default, $v);
-            }
-            $create[] = $v;
-        }
-
-        if ($state === -1) {
-            $sql = 'DROP TABLE IF EXISTS `' . $table . '`;CREATE TABLE `' . $table . '`(' . implode(',', $create) . ')';
-        } else {
-            $sql    = 'CREATE TABLE `' . $table . '`(' . implode(',', $create) . ')';
-        }
-        //$sql = 'DROP TABLE IF EXISTS `' . $table . '`;CREATE TABLE `' . $table . '`(' . implode(',', $create) . ')';
-
-        if ($auto) {
-            $sql .= ' AUTO_INCREMENT = ' . $auto;
-            if ($type) {
-                $sql .= ',';
-            } else {
-                $sql .= ';';
-            }
-        }
-
-        if ($type) {
-            $sql .= ' ENGINE = ' . $type . ';';
-        }
-
-
-        if ($partition) {
-            foreach ($partition['value'] as $k => $v) {
-                $partition['value'][$k] = 'PARTITION ' . $table .'_' . $k . ' VALUES ' . strtoupper($partition['exp']) . ' (' . $v . ')';
-            }
-            if (stristr($partition['exp'],'THEN')) {
-                $k = $k + 1;
-                $v = 'MAXVALUE';
-                $partition['value'][$k] = 'PARTITION ' . $table .'_' . $k . ' VALUES ' . strtoupper($partition['exp']) . ' ' . $v . '';
-            }
-            
-            $sql .= 'PARTITION BY ' . strtoupper($partition['type']).'('.$partition['col'].') ) (
-                '.implode(',', $partition['value']).'
-            );';
-        }
-
-        //echo $sql;die;
-
-        return $sql;
-    }
-
-    /**
-     * alter
-     *
-     * @return string
-     */
-    public function alter($table, $config)
-    {
-        $create = $primary = array();
-
-        $alter = 'ALTER TABLE `' . $table;
-
-        $sql = array();
-        foreach ($config as $k => $v) {
-            if (!isset($v['default'])) {
-                $v['default'] = '';
-            }
-            if (isset($v['type'])) {
-                $v = array
-                    (
-                    'add', $k, $k, $v['type'] . ' ' . $v['default'] . ' ' . $v['name'],
-                );
-            }
-
-            if (empty($v[3])) {
-                continue;
-            }
-            $sql[$k] = '';
-            if (isset($v[3]) && strpos($v[3], ' ') !== false) {
-                $com = explode(' ', $v[3]);
-                if (strstr($com[0], '-')) {
-                    $sql[$k] = str_replace('-', '(', $com[0]) . ') ';
-                } else {
-                    $sql[$k] = $com[0] . ' ';
-                }
-                
-                if (isset($com[1]) && $com[1] != '') {
-                    $sql[$k] .= 'not null default \'' . $com[1] . '\'';
-                } else {
-                    $sql[$k] .= 'not null';
-                }
-
-                if (!empty($com[2])) {
-                    $sql[$k] .= ' comment \'' . $com[2] . '\'';
-                }
-                $sql[$k] = strtoupper($sql[$k]);
-            }
-
-            if ($v[0] == 'add') {
-                # 新增字段
-                $sql[$k] = $alter . '` ADD `' . $v[1] . '` ' . $sql[$k];
-            } elseif ($v[0] == 'delete') {
-                # 删除字段
-                $sql[$k] = $alter . '` DROP `' . $v[1] . '`';
-            } else {
-                # 修改字段
-                $sql[$k] = $alter . '` CHANGE `' . $v[1] . '` `' . $v[2] . '` ' . $sql[$k];
-            }
-        }
-
-        $sql = implode(';', $sql);
-
-        return $sql;
-    }
-
-    /**
-     * col
-     *
-     * @return string
-     */
-    private function col($col)
-    {
-        $result = '';
-
-        if (is_array($col)) {
-            $array = array();
-            foreach ($col as $k => $v) {
-                if (!is_numeric($k)) {
-                    $array[] = $this->prefix . $k . ' AS ' . $v;
-                } else {
-                    $array[] = $this->prefix . $v;
-                }
-            }
-            $result = implode(' ', $array);
-        } else {
-            if ($col == '*' && isset($this->colOrder) && $this->colOrder) {
-                $col = array();
-                foreach ($this->colOrder as $k => $v) {
-                    if (!preg_match('/_no_col$/i', $k) && !preg_match('/^hr/i', $k))  {
-                        $col[] = '`'.$k.'`';
-                    }
-                }
-                $col = implode(',', $col);
-                $this->colOrder = array();
-                //$col = '`' . implode('`,`', array_keys($this->colOrder)) . '`';
-            }
-            $result = $col ? $this->prefix . $col : $this->prefix . '*';
-        }
-
-        if (isset($this->col) && $this->col) {
-            $result .= ',' . $this->col;
-        }
-
-        if (isset($this->score) && $this->score) {
-            $result .= ',(' . implode('+', $this->score) . ') as col_score';
-        }
-
-        if (isset($this->as) && $this->as) {
-            $result .= ','.implode(',', $this->as);
-        }
-        return $result;
-    }
-
-    /**
-     * select
-     *
-     * @return string
-     */
-    public function select($table, $col = '')
-    {
-        $this->table = $table;
-        $where = $this->createWhere();
-
-        $join = isset($this->join) ? implode(' ', $this->join) : '';
-
-        if (isset($this->orderBy) && $this->orderBy) {
-            $order = $this->orderBy;
-        } else {
-            $order = $this->order;
-        }
-        $sql = 'SELECT ' . $this->col($col) . ' FROM `' . $table . '` ' . $join . $where . ' ' . $this->group . ' ' . $order . ' ' . $this->limit;
-
-        $this->init();
-
-        return $sql;
-    }
-
-    /**
-     * createWhere
-     *
-     * @return string
-     */
-    private function createWhere()
-    {
-        $where = '';
-        if ($this->where) {
-            if (isset($this->colOrder)) {
-                ksort($this->where);
-            }
-
-            if (isset($this->between)) {
-                $where = 'WHERE ' . $this->between . ' ' . implode(' ', $this->where);
-                $this->limit = '';
-            } else {
-                $where = 'WHERE ' . ltrim(implode(' ', $this->where), ' and');
-            }
-        }
-
-        return $where;
-    }
-
-    /**
-     * count
-     *
-     * @return string
-     */
-    public function count($table, $col = '')
-    {
-        $where = $this->createWhere();
-
-        $state = 1;
-        if ($col == 'clear') {
-            $col = '';
-            $state = 2;
-        }
-
-        if (!$col || $col == '*') {
-            $col = 'count(*) as total';
-        }
-
-        $join = isset($this->join) ? implode(' ', $this->join) : '';
-
-        if (strstr($this->group, 'group')) {
-            $sql = '`' . $table . '` ' . $join . $where . ' ' . $this->group . ' ';
-
-            $sql = 'SELECT ' . $col . ' FROM (SELECT '.$col.' FROM '.$sql.' ) a ';
-
-        } else {
-            $sql = 'SELECT ' . $col . ' FROM `' . $table . '` ' . $join . $where . ' ' . $this->group . ' ';
-        }
-
-        
-
-        if ($state == 1) {
-            $this->init();
-        }
-
-        return $sql;
-    }
-
-    /**
-     * showIndex
-     *
-     * @return string
-     */
-    public function showIndex($table)
-    {
-        $sql = 'SHOW INDEX FROM ' . $table . ' ';
-
-        return $sql;
-    }
-
-    /**
-     * dropIndex
-     *
-     * @return string
-     */
-    public function dropIndex($table, $name)
-    {
-        $sql = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $name;
-
-        return $sql;
-    }
-
-    /**
-     * index
-     *
-     * @return string
-     */
-    public function index($table, $value)
-    {
-        $sql = 'ALTER TABLE ' . $table . ' ';
-
-        $max = count($value) - 1;
-
-        $i = 0;
-
-        foreach ($value as $k => $v) {
-            $type = 'INDEX';
-            if (strpos($v, '.')) {
-                $t = explode('.', $v);
-                $v = $t[0];
-                $type = ucwords($t[1]);
-            }
-            $sql .= 'ADD ' . $type . ' ' . $k . ' (' . $v . ')';
-
-            if ($i >= $max) {
-                $sql .= '';
-            } else {
-                $sql .= ',';
-            }
-
-            $i++;
-        }
-
-        return $sql;
-    }
-
-    /**
-     * insert
-     *
-     * @return string
-     */
-    public function insert($table, $num = 1)
-    {
-        $sql = 'INSERT INTO `' . $table . '` (' . implode(',', $this->col) . ') VALUES (' . implode(',', $this->value) . ')';
-
-        if ($num > 1) {
-            $insert = array();
-            for ($i = 1; $i < $num; $i++) {
-                $insert[] = '(' . implode(',', $this->value) . ')';
-            }
-            $sql .= ',' . implode(',', $insert);
-        }
-
-        $this->init();
-
-        return $sql;
-    }
-
-    /**
-     * replace
-     *
-     * @return string
-     */
-    public function replace($table)
-    {
-        $sql = 'REPLACE INTO `' . $table . '` (' . implode(',', $this->col) . ') VALUES (' . implode(',', $this->value) . ')';
-
-        $this->init();
-
-        return $sql;
-    }
-
-    /**
-     * insertValues
-     *
-     * @return string
-     */
-    public function insertValues($table, $col, $value)
-    {
-        $sql = 'INSERT INTO `' . $table . '` (' . $col . ') VALUES ';
-
-        $max = count($value) - 1;
-
-        foreach ($value as $k => $v) {
-            $sql .= '(' . $v . ')';
-
-            if ($k >= $max) {
-                $sql .= '';
-            } else {
-                $sql .= ',';
-            }
-        }
-
-        return $sql;
-    }
-
-    /**
-     * explain
-     *
-     * @return string
-     */
-    public function explain($sql)
-    {
-        $sql = 'EXPLAIN ' . $sql . ' ';
-
-        return $sql;
-    }
-
-    /**
-     * update
-     *
-     * @return string
-     */
-    public function update($table)
-    {
-        if (!$this->where) {
-            return false;
-        }
-
-        $where = $this->createWhere();
-
-        $sql = 'UPDATE `' . $table . '` SET ' . implode(',', $this->value) . ' ' . $where;
-
-        //echo $sql;die;
-
-        $this->init();
-
-        return $sql;
-    }
-
-    /**
-     * delete
-     *
-     * @return string
-     */
-    public function delete($table)
-    {
-        if (!$this->where) {
-            return false;
-        }
-
-        $where = $this->createWhere();
-
-        if (!$where) {
-            return false;
-        }
-
-        $sql = 'DELETE FROM `' . $table . '` ' . $where;
-
-        $this->init();
-
-        return $sql;
-    }
-
-    /**
-     * truncate
-     *
-     * @return string
-     */
-    public function truncate($table)
-    {
-        $sql = 'TRUNCATE TABLE `' . $table . '`';
-
-        return $sql;
-    }
-
-    /**
-     * opt
-     *
-     * @return string
-     */
-    public function opt($table)
-    {
-        $sql = 'OPTIMIZE TABLE `' . $table . '`';
-
-        return $sql;
-    }
-
-    /**
-     * sql
-     *
-     * @return string
-     */
-    public function sql($sql)
-    {
-        return $sql;
-    }
-
-    /**
-     * init
-     *
-     * @return object
-     */
-    public function init()
-    {
-        $this->where = $this->value = $this->col = $this->join = $this->score = $this->as = array();
-        $this->order = '';
-        $this->orderBy = '';
-        $this->group = '';
-        $this->limit = '';
-        $this->prefix = '';
-
-        return $this;
-    }
-
-    /**
-     * where
-     *
-     * @return string
-     */
-    public function where($param)
-    {
-        $where = '';
-        if (empty($param[2])) {
-            $param[2] = '=';
-        }
-
-        $value = 1;
-        if (strpos($param[2], '|') !== false) {
-            $temp = explode('|', $param[2]);
-            $param[2] = $temp[0];
-            $value = $temp[1];
-        }
-
-        if (empty($param[3])) {
-            $param[3] = 'and';
-        }
-
-        if (strpos($param[3], '))') !== false) {
-            $temp = explode('))', $param[3]);
-            $param[3] = $temp[0];
-            $where = ' ))';
-        } elseif (strpos($param[3], ')') !== false) {
-            $temp = explode(')', $param[3]);
-            $param[3] = $temp[0];
-            $where = ' )';
-        }
-
-        $col = '`s_' . $param[0] . '`';
-
-        /*
-        if (!strpos($param[0], '.')) {
-            $param[0] = $this->prefix . '`' . $param[0] . '`';
-        }*/
-
-        if (!$this->prefix && !strstr($param[0], ',')) {
-            $param[0] = '`' . $param[0] . '`';
-        }
-        if (strstr($param[0], ',')) {
-            $temp = explode(',', $param[0]);
-            $w = array();
-            if (strstr($param[2], 'like')) {
-                $content = explode('^', $param[2]);
-                $param[2] = $content[0];
-
-                foreach ($temp as $v) {
-                    if (isset($content[1]) && strstr($content[1], ',')) {
-                        $concat = 'concat(",", ' . $v . ',",")';
-                    } else {
-                        $concat = $v;
-                    }
-                    $instr = 'instr('.$concat.', ' . $param[1] . ')';
-                    $w[] = ' ' . $instr . ' > 0 ';
-                }
-            } else {
-                foreach ($temp as $v) {
-                    $w[] = '`' . $v . '` '. $param[2] . ' ' . $param[1];
-                }
-            }
-            
-            $where = ' and (' . implode(' or ', $w) . ') ' . $where;
-        } elseif (strstr($param[2], 'like')) {
-            $content = explode('^', $param[2]);
-            $param[2] = $content[0];
-
-            if (isset($content[1]) && strstr($content[1], ',')) {
-                //$content[1] = trim($content[1], ',');
-                $len = strlen($content[1]);
-                if (isset($content[1]) && strstr($content[1], ',')) {
-                    $concat = 'concat(' . $param[0] . ',",")';
-                } else {
-                    $concat = $param[0];
-                }
-                $instr = 'left('.$concat.', '.$len.')=' . $param[1];
-                $where = $param[3] . ' ' . $instr . $where;
-            } else {
-                if ((isset($content[1]) && strstr($content[1], ',')) || $param[2] == 'like_num') {
-                    $concat = 'concat(",", ' . $param[0] . ',",")';
-                } else {
-                    $concat = $param[0];
-                }
-                $instr = 'instr('.$concat.', ' . $param[1] . ')';
-                $where = $param[3] . ' ' . $instr . ' > 0' . $where;
-                if ($param[2] == 'like_score') {
-                    $this->orderBy = 'order by col_score desc';
-                    $this->score[] = 'IF('.$instr.', IF(' . $param[0] . '=' . $param[1] . ', 1000*'.$value.', (100-'.$instr.')*'.$value.'), 0)';
-                }
-            }
-            
-            //$this->as[] = ' CONCAT("<em class=\"dever_highlight\">",' . $param[0] . ',"</em>") as ' . $col;
-        } else {
-            $where = $param[3] . ' ' . $param[0] . ' ' . $param[2] . ' ' . $param[1] . $where;
-        }
-
-        if ($param[2] == 'in' && isset($param[4]) && $param[4] == 'order') {
-            $param[1] = str_replace(array('(',')'), '', $param[1]);
-            $this->orderBy = 'order by field(' . $param[0] . ', ' . $param[1] . ')';
-        }
-
-        if (isset($this->colOrder)) {
-            $param[0] = trim($param[0], '`');
-            if (isset($this->colOrder[$param[0]])) {
-                $this->where[$this->colOrder[$param[0]]] = $where;
-            } else {
-                $num = count($this->where) + 100;
-                $this->where[$num] = $where;
-            }
-        } else {
-            $this->where[] = $where;
-        }
-    }
-
-    /**
-     * order
-     *
-     * @return string
-     */
-    public function order($param)
-    {
-        if (is_array($param[0])) {
-            $this->order = 'order by ';
-            foreach ($param[0] as $k => $v) {
-                $k1 = '';
-                if (strpos($k, '.')) {
-                    $t = explode('.', $k);
-                    $k = $t[1];
-                    $k1 = $t[0] . '.';
-                }
-                $order[] = $k1 . '`' . $k . '` ' . $v;
-            }
-
-            $this->order .= implode(',', $order);
-
-            //echo $this->order;die;
-        } else {
-            if (empty($param[1])) {
-                $param[1] = 'desc';
-            }
-
-            if (!strstr($param[0], '()') && !strstr($param[0], 't_')) {
-                $param[0] = '`'.$param[0].'`';
-            }
-
-            $this->order = 'order by ' . $param[0] . ' ' . $param[1];
-        }
-    }
-
-    /**
-     * group
-     *
-     * @return string
-     */
-    public function group($param)
-    {
-        if (is_array($param) && isset($param[0])) {
-            //$param = trim(implode(',', $param), ',');
-            $param = $param[0];
-
-            $this->group = ' group by ' . $param;
-        }
-
-        # 去掉id的分组,没用
-        if (is_string($param) && $param != 'id') {
-            if ($param == 'day') {
-                $this->col = 'FROM_UNIXTIME(day, "%Y-%m-%d") as day';
-            } elseif ($param == 'month') {
-                $this->col = 'FROM_UNIXTIME(day, "%Y-%m") as month';
-            } elseif ($param == 'year') {
-                $this->col = 'FROM_UNIXTIME(day, "%Y") as year';
-            } elseif (strpos($param, ',') === false) {
-                $this->col = $param;
-            }
-
-            $this->group = ' group by ' . $param;
-        }
-    }
-
-    /**
-     * join 为临时解决方案,不建议用join
-     *
-     * @return string
-     */
-    public function join($param)
-    {
-        $this->prefix = 't_1.';
-        $this->join[] = 'as t_1';
-        $num = 2;
-        foreach ($param as $k => $v) {
-            if ($v) {
-                $table = 't_' . $num;
-                if (strpos($v['on'][0], '.') === false) {
-                    $v['on'][0] = 't_1.`' . $v['on'][0] . '`';
-                } else {
-                    $v['on'][0] = 't_' . $v['on'][0];
-                }
-
-                $v['on'][1] = $table . '.`' . $v['on'][1] . '`';
-
-                $v['table'] = str_replace('/', '_', $v['table']);
-                if (DEVER_PROJECT != 'default') {
-                    $v['table'] = DEVER_PROJECT . '_' . $v['table'];
-                }
-
-                $this->join[] = ucwords($v['type']) . ' `' . $v['table'] . '` AS ' . $table . ' ON ' . $v['on'][0] . '=' . $v['on'][1] . ' ';
-
-                if (isset($v['col'])) {
-                    $this->col = $v['col'];
-                }
-
-                $num++;
-            }
-        }
-    }
-
-    /**
-     * limit
-     *
-     * @return string
-     */
-    public function limit($param)
-    {
-        //if(empty($param[1])) $param[1] = 0;
-
-        //$this->limit = 'limit ' . $param[1] . ',' . $param[0];
-        $this->limit = 'limit ' . $param[0];
-
-        //$this->between = ' `id` BETWEEN ' . $param[1] . ' AND ' . ($param[1] + $param[0]);
-    }
-
-    /**
-     * reset limit
-     *
-     * @return string
-     */
-    public function reset($param)
-    {
-        $this->{$param[0]} = '';
-    }
-
-    /**
-     * add
-     *
-     * @return string
-     */
-    public function add($param)
-    {
-        $this->col[] = '`' . $param[0] . '`';
-        $this->value[] = $param[1];
-    }
-
-    /**
-     * set
-     *
-     * @return string
-     */
-    public function set($param)
-    {
-        if (empty($param[2])) {
-            $param[2] = '=';
-        }
-
-        $param[0] = '`' . $param[0] . '`';
-
-        if (strpos($param[2], '+=') !== false) {
-            $param[2] = '=' . $param[0] . '+';
-        }
-
-        if (strpos($param[2], '-=') !== false) {
-            $param[2] = '=' . $param[0] . '-';
-        }
-
-        $this->value[] = $param[0] . $param[2] . $param[1];
-    }
-}

+ 0 - 755
src/Dever/Data/Store - 副本.php

@@ -1,755 +0,0 @@
-<?php namespace Dever\Data;
-
-use Dever;
-use Dever\Cache\Handle;
-use Dever\Loader\Config;
-use Dever\Output\Debug;
-use Dever\Pagination\Paginator as Page;
-use Dever\Routing\Input;
-use Dever\Support\Path;
-use Dever\Routing\Uri;
-
-class Store
-{
-    /**
-     * sql
-     *
-     * @var Dever\Data\Sql
-     */
-    protected $sql;
-
-    /**
-     * create
-     *
-     * @var Dever\Data\Connect
-     */
-    protected $create;
-
-    /**
-     * read
-     *
-     * @var Dever\Data\Connect
-     */
-    protected $read;
-
-    /**
-     * update
-     *
-     * @var Dever\Data\Connect
-     */
-    protected $update;
-
-    /**
-     * config
-     *
-     * @var array
-     */
-    protected $config;
-
-    /**
-     * table
-     *
-     * @var string
-     */
-    protected $table;
-
-    /**
-     * alias
-     *
-     * @var string
-     */
-    protected $alias;
-
-    /**
-     * value
-     *
-     * @var array
-     */
-    protected $value = array();
-
-    /**
-     * instance
-     *
-     * @var string
-     */
-    protected static $instance;
-
-    /**
-     * getInstance
-     *
-     * @return Dever\Data\Store;
-     */
-    public static function getInstance($key, $config)
-    {
-        if (empty(static::$instance[$key])) {
-            static::$instance[$key] = new static($config);
-        }
-
-        return static::$instance[$key];
-    }
-
-    
-
-    /**
-     * __construct
-     *
-     * @return mixd
-     */
-    public function __construct($config)
-    {
-        $this->init();
-
-        $this->config = $config;
-
-        //$this->register($config);
-    }
-
-    /**
-     * register
-     *
-     * @return mixd
-     */
-    protected function register($create = false)
-    {
-        if ($create) {
-            if ($this->create) {
-                return;
-            }
-        } elseif ($this->read && $this->update) {
-            return;
-        }
-        
-        if (is_array($this->config['host'])) {
-            $config = $this->config;
-            $host = $this->config['host'];
-            if ($host['read'] != $host['update']) {
-                $config['host'] = $host['read'];
-                $this->read = $this->connect($config);
-                $config['host'] = $host['update'];
-                $this->update = $this->connect($config);
-            } else {
-                $config['host'] = $host['read'];
-                $this->read = $this->update = $this->connect($config);
-            }
-            if ($create && isset($host['create'])) {
-                $config['host'] = $host['create'];
-                $this->create = $this->connect($config);
-            }
-        } else {
-            $this->read = $this->update = $this->connect($this->config);
-        }
-        # 查询大量数据时,不缓存数据到内存,防止内存溢出
-        if (Dever::config('base')->pdo_no_cache) {
-            $this->read->set();
-        }
-        $this->config['link'] = false;
-    }
-
-    /**
-     * table
-     *
-     * @return object
-     */
-    public function table($table, $name = '', $state = true, $alias = '', $prefix = false, $link = false)
-    {
-        $this->config['link'] = $link;
-        # 后续增加表名别名功能
-        $this->alias = $alias ? $alias : $table;
-        if ($prefix) {
-            $table = $prefix . '_' . $table;
-        } elseif (defined('DEVER_DB_PREFIX')) {
-            $table = DEVER_DB_PREFIX . '_' . $table;
-        } elseif ($state == true && defined('DEVER_PROJECT') && DEVER_PROJECT != 'default') {
-            $table = DEVER_PROJECT . '_' . $table;
-        }
-
-        $this->setTable($table);
-
-        if (!$link && $state == true && isset($this->sql) && Config::get('database')->sqlOp) {
-            $file = $this->file($name);
-
-            if (is_file($file)) {
-                $config = include $file;
-                if (isset($config['struct'])) $this->sql->setColOrder($config['struct']);
-            }
-        }
-
-        return $this;
-    }
-
-    /**
-     * table
-     *
-     * @return object
-     */
-    public function index($index, $name = '')
-    {
-        if ($this->config['link']) {
-            return false;
-        }
-
-        if (empty($index)) {
-            return false;
-        }
-        $file = $this->file($name);
-        if (!is_file($file)) {
-            return false;
-        }
-
-        $data = include $file;
-
-        if (isset($index['version'])) {
-            $version = $index['version'];
-
-            unset($index['version']);
-        } else {
-            $version = 1;
-        }
-
-        if (empty($data['index']) || (isset($data['index']) && $data['index'] < $version)) {
-            $data = array_merge($data, $this->getIndex($version, $index));
-            file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-        }
-
-        return $this;
-    }
-
-    /**
-     * alter table
-     *
-     * @return mixed
-     */
-    public function alter($alter, $struct = array(), $name = '')
-    {
-        if ($this->config['link']) {
-            return false;
-        }
-
-        if (empty($this->sql)) {
-            return false;
-        }
-        if (empty($alter)) {
-            return false;
-        }
-        $file = $this->file($name);
-
-        if (!is_file($file)) {
-            return false;
-        }
-
-        $data = include $file;
-        if (is_array($struct)) {
-            $sql = $this->sql->alter($this->table, $alter);
-
-            $this->exe($sql);
-
-            $this->log($sql, 'alter');
-
-            $data['struct'] = array_flip(array_keys($struct));
-
-            file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-        } else {
-            if (isset($alter['version'])) {
-                $version = $alter['version'];
-            } else {
-                $version = 1;
-            }
-
-            if (isset($alter[$version]) && (empty($data['alter']) || (isset($data['alter']) && $data['alter'] != $version))) {
-                $sql = $this->sql->alter($this->table, $alter[$version]);
-
-                $this->exe($sql);
-
-                $this->log($sql, 'alter');
-
-                $data['alter'] = $version;
-
-                file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-            }
-        }
-
-        return true;
-    }
-
-    /**
-     * insert the default value
-     *
-     * @return mixed
-     */
-    public function insertDefault($value, $name = '')
-    {
-        $file = $this->file($name);
-        if (!is_file($file)) {
-            return false;
-        }
-
-        $data = include $file;
-        if (isset($value['col']) && isset($value['value'])) {
-            $this->truncate();
-
-            $data = $this->insertValues($value, $data);
-
-            file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-        }
-
-        return true;
-    }
-
-    /**
-     * file
-     *
-     * @return mixed
-     */
-    public function file($name = '')
-    {
-        $path = Config::data();
-
-        if ($name) {
-            $name = $this->table . '_' . $name . '.php';
-        } else {
-            $name = $this->table . '.php';
-        }
-
-        $temp = explode('_', $this->table);
-
-        $file = Path::get($path . 'database/', $temp[0] . '/' . $name);
-        return $file;
-    }
-
-    /**
-     * create
-     *
-     * @return mixed
-     */
-    public function create($struct, $name = '', $type = 'innodb', $partition = '', $create = -2, $auto = 1)
-    {
-        if ($this->config['link']) {
-            return false;
-        }
-
-        if (isset($this->sql) && $create > 0) {
-            return false;
-        }
-        if (isset($this->sql) && $create === -2 && Config::get('database')->create > 0) {
-            return false;
-        }
-
-        $create = $create <= 0 && $create >= -1 ? $create : Config::get('database')->create;
-        $file = $this->file($name);
-        if (is_file($file)) {
-            return include $file;
-        }
-
-        if (isset($this->sql)) {
-            $sql = $this->sql->create($this->table, $struct, $type, $partition, $create, $auto);
-
-            $this->exe($sql);
-
-            $this->log($sql, 'create');
-        } elseif (method_exists($this, 'createTable')) {
-            $this->createTable($struct);
-        }
-
-        $data['time'] = DEVER_TIME;
-
-        $data['table'] = $this->table;
-
-        if (isset($this->sql)) {
-            $data['create'] = $sql;
-
-            $data['struct'] = array_flip(array_keys($struct));
-        } else {
-            $data['create'] = true;
-
-            $this->log($data, 'create');
-        }
-
-        file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-
-        return true;
-    }
-
-    private function truncate()
-    {
-        if (isset($this->sql)) {
-            $sql = $this->sql->truncate($this->table);
-
-            $this->exe($sql);
-
-            $this->log($sql, 'truncate');
-        }
-    }
-
-    /**
-     * getPageBySql
-     *
-     * @return array
-     */
-    public function getPageBySql($config = array(), $sql = false, $data = array(), Model $model)
-    {
-        empty($config['template']) && $config['template'] = 'list';
-
-        empty($config['key']) && $config['key'] = 'current';
-
-        empty($config['link']) && $config['link'] = '';
-
-        empty($config['num']) && $config['num'] = 10;
-
-        $page = Page::getInstance($config['key']);
-
-        $page->template($config['template']);
-
-        $page->link($config['link']);
-
-        $total = Input::get('pt', -1);
-
-        if (isset($config['explode']) && isset($config['content'])) {
-            $content = explode($config['explode'], $config['content']);
-            $page->offset(1);
-            $data = $page->data($content, $total);
-        } else {
-            empty($config['first_num']) && $config['first_num'] = 0;
-            $offset = $page->offset($config['num'], $config['first_num']);
-            $data = $page->sqlCount($sql, (isset($config['offset']) ? $config['offset'] : $offset), $total, $model, $data);
-        }
-
-        Dever::$global['page'][$config['key']] = $page->toArray();
-        
-        return $data;
-    }
-
-    /**
-     * page
-     *
-     * @return object
-     */
-    public function page($num, $config = array())
-    {
-        $this->reset('limit');
-
-        empty($config[0]) && $config[0] = 'list';
-
-        empty($config[1]) && $config[1] = 'current';
-
-        empty($config[2]) && $config[2] = '';
-
-        $page = Page::getInstance($config[1]);
-
-        $page->template($config[0]);
-
-        $page->link($config[2]);
-
-        $this->limit($page->offset($num). ',' . $num);
-
-        $total = Input::get('pt', -1);
-
-        if ($total < 0) {
-            $total = $this->count('clear');
-        }
-
-        $page->total($total);
-
-        Dever::$global['page'][$config[1]] = $page->toArray();
-        return $this;
-    }
-
-    public function deleteCache($value, $key, $handle)
-    {
-        return $handle->delete($key);
-    }
-
-    /*
-    public function cache($key = false, $method = 'get', $data = false)
-    {
-        $cache = isset($this->config['cache']) ? $this->config['cache'] : Config::get('cache')->cAll;
-
-        if (isset($cache['route']) && $cache['route'] > 0 && $this->table && !isset(Config::get('base')->clearCache['route'])) {
-            $handle = Handle::getInstance('route', $cache['route']);
-            if ($method == 'put' && $data !== false) {
-                $route = Uri::key();
-                $value = $handle->hGet($this->table, $route, true);
-                if (!$value) {
-                    $handle->hSet($this->table, $route, 1);
-                }
-            } elseif (!$key && $this->table) {
-                $value = $handle->hGet($this->table, false, true);
-                $handle->delete($this->table);
-                if ($value) {
-                    array_walk($value, array($this, 'deleteCache'), $handle);
-                }
-            }
-        }
-
-        if (empty($cache['mysql'])) {
-            return false;
-        }
-
-        $handle = Handle::getInstance('mysql', $cache['mysql']);
-        if (!$key && $this->table) {
-            $value = $handle->hGet($this->table, false, true);
-            if ($value) {
-                array_walk($value, array($this, 'deleteCache'), $handle);
-            }
-        }
-
-        if ($method == 'get') {
-            if (DEVER_APP_NAME == 'manage') {
-                return false;
-            }
-            return $handle->get($key);
-        }
-
-        if ($method == 'put' && $data !== false) {
-
-            if ($this->table) {
-                $value = $handle->hGet($this->table, $key, true);
-                if (!$value) {
-                    $handle->hSet($this->table, $key, 1);
-                }
-            }
-
-            return $handle->set($key, $data);
-        }
-
-        return false;
-    }
-    */
-
-    public function cache($key = false, $method = 'get', $data = false)
-    {
-        $cache = isset($this->config['cache']) ? $this->config['cache'] : Config::get('cache')->cAll;
-
-        //if (isset($cache['route']) && $cache['route'] > 0 && $this->table && !isset(Config::get('base')->clearCache['route'])) {
-        if (isset($cache['route']) && $cache['route'] > 0 && $this->table) {
-            $handle = Handle::getInstance('route', $cache['route']);
-            if ($method == 'put') {
-                $keys = $handle->get($this->table, false);
-                $route = Uri::key();
-                if (!isset($keys[$route])) {
-                    $keys[$route] = 1;
-                    $handle->set($this->table, $keys, 0, false);
-                }
-            } elseif (!$key && $this->table) {
-                if (Config::get('base')->after == 1) {
-                    return;
-                }
-                $keys = $handle->get($this->table, false);
-                if ($keys) {
-                    array_walk($keys, array($this, 'deleteCache'), $handle);
-                }
-            }
-        }
-
-        if (empty($cache['mysql'])) {
-            return false;
-        }
-
-        $handle = Handle::getInstance('mysql', $cache['mysql']);
-        if (!$key && $this->table) {
-            if (Config::get('base')->after == 1) {
-                return;
-            }
-            $keys = $handle->get($this->table, false);
-            if ($keys) {
-                array_walk($keys, array($this, 'deleteCache'), $handle);
-            }
-        } else {
-            if ($method == 'get') {
-                if (DEVER_APP_NAME == 'manage') {
-                    return false;
-                }
-                return $handle->get($key);
-            }
-
-            if ($method == 'put' && $data !== false) {
-
-                if ($this->table) {
-                    $keys = $handle->get($this->table, false);
-                    if (!isset($keys[$key])) {
-                        $keys[$key] = 1;
-                        $handle->set($this->table, $keys, 0, false);
-                    }
-                }
-
-                return $handle->set($key, $data);
-            }
-        }
-
-        return false;
-    }
-
-    /**
-     * error
-     *
-     * @return error
-     */
-    public function error($msg, $sql = '')
-    {
-        if (isset($this->sql)) {
-            if ($sql) {
-                $msg = array('sql' => $sql, 'error' => $msg);
-            } elseif (is_object($msg)) {
-                $msg = (array) $msg;
-            } elseif (is_string($msg)) {
-                $msg = array('sql' => $msg);
-            }
-            Debug::wait($msg, 'Dever SQL DB Error!');
-        } else {
-            if (is_string($msg)) {
-                $msg = array('value' => $msg);
-            }
-            Debug::wait($msg, 'Dever NOSQL DB Error!');
-        }
-    }
-
-    /**
-     * log
-     *
-     * @return log
-     */
-    public function log($value, $param = array(), $data = array())
-    {
-        if (isset($this->sql)) {
-            $value = $this->replace($value, $param, $this->sql);
-            $this->sql($value);
-            if (!Input::shell('all') && is_array($data)) {
-                $data = count($data) . ' records';
-            }
-            Debug::log(array('sql' => $value, 'data' => $data), $this->config['type']);
-        } else {
-            Debug::log(array('value' => $value, 'method' => $param), $this->config['type']);
-        }
-    }
-
-    /**
-     * sql
-     *
-     * @return sql
-     */
-    public function replace($value, $param)
-    {
-        if ($value && is_array($param)) {
-            foreach ($param as $k => $v) {
-                if (is_string($v)) {
-                    if (strstr($value, 'select') && strpos($v, ',')) {
-                        $v = 'in('.$v.')';
-                    } else {
-                        $v = '"' . $v . '"';
-                    }
-                }
-                $value = str_replace($k, $v, $value);
-            }
-        }
-
-        return $value;
-    }
-
-    /**
-     * sql
-     *
-     * @return mixed
-     */
-    public function sql($value)
-    {
-        if (!Config::get('database')->sql) {
-            Config::get('database')->sql = array();
-        }
-        $sql = Config::get('database')->sql;
-        array_push($sql, $value);
-        Config::get('database')->sql = $sql;
-    }
-
-    /**
-     * begin
-     *
-     * @return object
-     */
-    public function begin()
-    {
-        return $this;
-    }
-
-    /**
-     * commit
-     *
-     * @return object
-     */
-    public function commit()
-    {
-        return $this;
-    }
-
-    /**
-     * rollback
-     *
-     * @return object
-     */
-    public function rollback()
-    {
-        return $this;
-    }
-
-    /**
-     * fetchAll
-     *
-     * @return array
-     */
-    protected function fetchAll($handle, $config = false, $call = false)
-    {
-        $rows = function() use ($handle) {
-            while ($row = $handle->fetch()) {
-                yield $row;
-            }
-        };
-        $result = array();
-        $data = $rows();
-        if ($data) {
-            if ($config) {
-                $result = $this->fetchSet($data, $config, $call);
-            } else {
-                foreach ($data as $row) {
-                    $result[] = $this->cb($call, $row);
-                }
-            }
-        }
-        return $result;
-    }
-
-    /**
-     * call
-     *
-     * @return array
-     */
-    protected function cb($call, $data)
-    {
-        if ($call) {
-            return $call($data);
-        }
-        return $data;
-    }
-
-    /**
-     * fetchSet
-     *
-     * @return array
-     */
-    protected function fetchSet($data, $config, $call = false)
-    {
-        $result = array();
-        $key = $config[1];
-        foreach ($data as $row) {
-            if (isset($row[$key])) {
-                if (isset($config[3]) && isset($row[$config[2]])) {
-                    $result[$row[$key]][$row[$config[2]]] = $this->cb($call, $row);
-                } elseif (isset($config[2]) && isset($row[$config[2]])) {
-                    $result[$row[$key]] = $this->cb($call, $row[$config[2]]);
-                } elseif (isset($config[2])) {
-                    $result[$row[$key]][] = $this->cb($call, $row);
-                } else {
-                    $result[$row[$key]] = $this->cb($call, $row);
-                }
-            }
-        }
-        return $result;
-    }
-}

+ 0 - 734
src/Dever/Data/Store.php

@@ -1,734 +0,0 @@
-<?php namespace Dever\Data;
-use Dever;
-class Store
-{
-    /**
-     * sql
-     *
-     * @var Dever\Data\Sql
-     */
-    protected $sql;
-
-    /**
-     * create
-     *
-     * @var Dever\Data\Connect
-     */
-    protected $create;
-
-    /**
-     * read
-     *
-     * @var Dever\Data\Connect
-     */
-    protected $read;
-
-    /**
-     * update
-     *
-     * @var Dever\Data\Connect
-     */
-    protected $update;
-
-    /**
-     * config
-     *
-     * @var array
-     */
-    protected $config;
-
-    /**
-     * table
-     *
-     * @var string
-     */
-    protected $table;
-
-    /**
-     * alias
-     *
-     * @var string
-     */
-    protected $alias;
-
-    /**
-     * value
-     *
-     * @var array
-     */
-    protected $value = array();
-    protected static $instance;
-    public static function getInstance($key)
-    {
-        if (empty(static::$instance[$key])) {
-            static::$instance[$key] = new static(Dever::config('setting')['database'][$key]);
-        }
-        return static::$instance[$key];
-    }
-
-    /**
-     * __construct
-     *
-     * @return mixd
-     */
-    public function __construct($config)
-    {
-        $class = 'Dever\\Data\\Store\\' . $config['type'];
-        $class = new $class();
-        echo $class;die;
-        $class->init();
-
-        $this->config = $config;
-    }
-
-    public function create($struct, $name = '', $type = 'innodb', $partition = '', $create = -2, $auto = 1)
-    {
-        if ($this->config['link']) {
-            return false;
-        }
-
-        if (isset($this->sql) && $create > 0) {
-            return false;
-        }
-        if (isset($this->sql) && $create === -2 && Config::get('database')->create > 0) {
-            return false;
-        }
-
-        $create = $create <= 0 && $create >= -1 ? $create : Config::get('database')->create;
-        $file = $this->file($name);
-        if (is_file($file)) {
-            return include $file;
-        }
-
-        if (isset($this->sql)) {
-            $sql = $this->sql->create($this->table, $struct, $type, $partition, $create, $auto);
-
-            $this->exe($sql);
-
-            $this->log($sql, 'create');
-        } elseif (method_exists($this, 'createTable')) {
-            $this->createTable($struct);
-        }
-
-        $data['time'] = DEVER_TIME;
-
-        $data['table'] = $this->table;
-
-        if (isset($this->sql)) {
-            $data['create'] = $sql;
-
-            $data['struct'] = array_flip(array_keys($struct));
-        } else {
-            $data['create'] = true;
-
-            $this->log($data, 'create');
-        }
-
-        file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-
-        return true;
-    }
-
-    /**
-     * register
-     *
-     * @return mixd
-     */
-    protected function register($create = false)
-    {
-        if ($create) {
-            if ($this->create) {
-                return;
-            }
-        } elseif ($this->read && $this->update) {
-            return;
-        }
-        
-        if (is_array($this->config['host'])) {
-            $config = $this->config;
-            $host = $this->config['host'];
-            if ($host['read'] != $host['update']) {
-                $config['host'] = $host['read'];
-                $this->read = $this->connect($config);
-                $config['host'] = $host['update'];
-                $this->update = $this->connect($config);
-            } else {
-                $config['host'] = $host['read'];
-                $this->read = $this->update = $this->connect($config);
-            }
-            if ($create && isset($host['create'])) {
-                $config['host'] = $host['create'];
-                $this->create = $this->connect($config);
-            }
-        } else {
-            $this->read = $this->update = $this->connect($this->config);
-        }
-        # 查询大量数据时,不缓存数据到内存,防止内存溢出
-        if (Dever::config('base')->pdo_no_cache) {
-            $this->read->set();
-        }
-        $this->config['link'] = false;
-    }
-
-    /**
-     * table
-     *
-     * @return object
-     */
-    public function table($table, $name = '', $state = true, $alias = '', $prefix = false, $link = false)
-    {
-        $this->config['link'] = $link;
-        # 后续增加表名别名功能
-        $this->alias = $alias ? $alias : $table;
-        if ($prefix) {
-            $table = $prefix . '_' . $table;
-        } elseif (defined('DEVER_DB_PREFIX')) {
-            $table = DEVER_DB_PREFIX . '_' . $table;
-        } elseif ($state == true && defined('DEVER_PROJECT') && DEVER_PROJECT != 'default') {
-            $table = DEVER_PROJECT . '_' . $table;
-        }
-
-        $this->setTable($table);
-
-        if (!$link && $state == true && isset($this->sql) && Config::get('database')->sqlOp) {
-            $file = $this->file($name);
-
-            if (is_file($file)) {
-                $config = include $file;
-                if (isset($config['struct'])) $this->sql->setColOrder($config['struct']);
-            }
-        }
-
-        return $this;
-    }
-
-    /**
-     * table
-     *
-     * @return object
-     */
-    public function index($index, $name = '')
-    {
-        if ($this->config['link']) {
-            return false;
-        }
-
-        if (empty($index)) {
-            return false;
-        }
-        $file = $this->file($name);
-        if (!is_file($file)) {
-            return false;
-        }
-
-        $data = include $file;
-
-        if (isset($index['version'])) {
-            $version = $index['version'];
-
-            unset($index['version']);
-        } else {
-            $version = 1;
-        }
-
-        if (empty($data['index']) || (isset($data['index']) && $data['index'] < $version)) {
-            $data = array_merge($data, $this->getIndex($version, $index));
-            file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-        }
-
-        return $this;
-    }
-
-    /**
-     * alter table
-     *
-     * @return mixed
-     */
-    public function alter($alter, $struct = array(), $name = '')
-    {
-        if ($this->config['link']) {
-            return false;
-        }
-
-        if (empty($this->sql)) {
-            return false;
-        }
-        if (empty($alter)) {
-            return false;
-        }
-        $file = $this->file($name);
-
-        if (!is_file($file)) {
-            return false;
-        }
-
-        $data = include $file;
-        if (is_array($struct)) {
-            $sql = $this->sql->alter($this->table, $alter);
-
-            $this->exe($sql);
-
-            $this->log($sql, 'alter');
-
-            $data['struct'] = array_flip(array_keys($struct));
-
-            file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-        } else {
-            if (isset($alter['version'])) {
-                $version = $alter['version'];
-            } else {
-                $version = 1;
-            }
-
-            if (isset($alter[$version]) && (empty($data['alter']) || (isset($data['alter']) && $data['alter'] != $version))) {
-                $sql = $this->sql->alter($this->table, $alter[$version]);
-
-                $this->exe($sql);
-
-                $this->log($sql, 'alter');
-
-                $data['alter'] = $version;
-
-                file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-            }
-        }
-
-        return true;
-    }
-
-    /**
-     * insert the default value
-     *
-     * @return mixed
-     */
-    public function insertDefault($value, $name = '')
-    {
-        $file = $this->file($name);
-        if (!is_file($file)) {
-            return false;
-        }
-
-        $data = include $file;
-        if (isset($value['col']) && isset($value['value'])) {
-            $this->truncate();
-
-            $data = $this->insertValues($value, $data);
-
-            file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
-        }
-
-        return true;
-    }
-
-    /**
-     * file
-     *
-     * @return mixed
-     */
-    public function file($name = '')
-    {
-        $path = Config::data();
-
-        if ($name) {
-            $name = $this->table . '_' . $name . '.php';
-        } else {
-            $name = $this->table . '.php';
-        }
-
-        $temp = explode('_', $this->table);
-
-        $file = Path::get($path . 'database/', $temp[0] . '/' . $name);
-        return $file;
-    }
-
-    /**
-     * create
-     *
-     * @return mixed
-     */
-    
-
-    private function truncate()
-    {
-        if (isset($this->sql)) {
-            $sql = $this->sql->truncate($this->table);
-
-            $this->exe($sql);
-
-            $this->log($sql, 'truncate');
-        }
-    }
-
-    /**
-     * getPageBySql
-     *
-     * @return array
-     */
-    public function getPageBySql($config = array(), $sql = false, $data = array(), Model $model)
-    {
-        empty($config['template']) && $config['template'] = 'list';
-
-        empty($config['key']) && $config['key'] = 'current';
-
-        empty($config['link']) && $config['link'] = '';
-
-        empty($config['num']) && $config['num'] = 10;
-
-        $page = Page::getInstance($config['key']);
-
-        $page->template($config['template']);
-
-        $page->link($config['link']);
-
-        $total = Input::get('pt', -1);
-
-        if (isset($config['explode']) && isset($config['content'])) {
-            $content = explode($config['explode'], $config['content']);
-            $page->offset(1);
-            $data = $page->data($content, $total);
-        } else {
-            empty($config['first_num']) && $config['first_num'] = 0;
-            $offset = $page->offset($config['num'], $config['first_num']);
-            $data = $page->sqlCount($sql, (isset($config['offset']) ? $config['offset'] : $offset), $total, $model, $data);
-        }
-
-        Dever::$global['page'][$config['key']] = $page->toArray();
-        
-        return $data;
-    }
-
-    /**
-     * page
-     *
-     * @return object
-     */
-    public function page($num, $config = array())
-    {
-        $this->reset('limit');
-
-        empty($config[0]) && $config[0] = 'list';
-
-        empty($config[1]) && $config[1] = 'current';
-
-        empty($config[2]) && $config[2] = '';
-
-        $page = Page::getInstance($config[1]);
-
-        $page->template($config[0]);
-
-        $page->link($config[2]);
-
-        $this->limit($page->offset($num). ',' . $num);
-
-        $total = Input::get('pt', -1);
-
-        if ($total < 0) {
-            $total = $this->count('clear');
-        }
-
-        $page->total($total);
-
-        Dever::$global['page'][$config[1]] = $page->toArray();
-        return $this;
-    }
-
-    public function deleteCache($value, $key, $handle)
-    {
-        return $handle->delete($key);
-    }
-
-    /*
-    public function cache($key = false, $method = 'get', $data = false)
-    {
-        $cache = isset($this->config['cache']) ? $this->config['cache'] : Config::get('cache')->cAll;
-
-        if (isset($cache['route']) && $cache['route'] > 0 && $this->table && !isset(Config::get('base')->clearCache['route'])) {
-            $handle = Handle::getInstance('route', $cache['route']);
-            if ($method == 'put' && $data !== false) {
-                $route = Uri::key();
-                $value = $handle->hGet($this->table, $route, true);
-                if (!$value) {
-                    $handle->hSet($this->table, $route, 1);
-                }
-            } elseif (!$key && $this->table) {
-                $value = $handle->hGet($this->table, false, true);
-                $handle->delete($this->table);
-                if ($value) {
-                    array_walk($value, array($this, 'deleteCache'), $handle);
-                }
-            }
-        }
-
-        if (empty($cache['mysql'])) {
-            return false;
-        }
-
-        $handle = Handle::getInstance('mysql', $cache['mysql']);
-        if (!$key && $this->table) {
-            $value = $handle->hGet($this->table, false, true);
-            if ($value) {
-                array_walk($value, array($this, 'deleteCache'), $handle);
-            }
-        }
-
-        if ($method == 'get') {
-            if (DEVER_APP_NAME == 'manage') {
-                return false;
-            }
-            return $handle->get($key);
-        }
-
-        if ($method == 'put' && $data !== false) {
-
-            if ($this->table) {
-                $value = $handle->hGet($this->table, $key, true);
-                if (!$value) {
-                    $handle->hSet($this->table, $key, 1);
-                }
-            }
-
-            return $handle->set($key, $data);
-        }
-
-        return false;
-    }
-    */
-
-    public function cache($key = false, $method = 'get', $data = false)
-    {
-        $cache = isset($this->config['cache']) ? $this->config['cache'] : Config::get('cache')->cAll;
-
-        //if (isset($cache['route']) && $cache['route'] > 0 && $this->table && !isset(Config::get('base')->clearCache['route'])) {
-        if (isset($cache['route']) && $cache['route'] > 0 && $this->table) {
-            $handle = Handle::getInstance('route', $cache['route']);
-            if ($method == 'put') {
-                $keys = $handle->get($this->table, false);
-                $route = Uri::key();
-                if (!isset($keys[$route])) {
-                    $keys[$route] = 1;
-                    $handle->set($this->table, $keys, 0, false);
-                }
-            } elseif (!$key && $this->table) {
-                if (Config::get('base')->after == 1) {
-                    return;
-                }
-                $keys = $handle->get($this->table, false);
-                if ($keys) {
-                    array_walk($keys, array($this, 'deleteCache'), $handle);
-                }
-            }
-        }
-
-        if (empty($cache['mysql'])) {
-            return false;
-        }
-
-        $handle = Handle::getInstance('mysql', $cache['mysql']);
-        if (!$key && $this->table) {
-            if (Config::get('base')->after == 1) {
-                return;
-            }
-            $keys = $handle->get($this->table, false);
-            if ($keys) {
-                array_walk($keys, array($this, 'deleteCache'), $handle);
-            }
-        } else {
-            if ($method == 'get') {
-                if (DEVER_APP_NAME == 'manage') {
-                    return false;
-                }
-                return $handle->get($key);
-            }
-
-            if ($method == 'put' && $data !== false) {
-
-                if ($this->table) {
-                    $keys = $handle->get($this->table, false);
-                    if (!isset($keys[$key])) {
-                        $keys[$key] = 1;
-                        $handle->set($this->table, $keys, 0, false);
-                    }
-                }
-
-                return $handle->set($key, $data);
-            }
-        }
-
-        return false;
-    }
-
-    /**
-     * error
-     *
-     * @return error
-     */
-    public function error($msg, $sql = '')
-    {
-        if (isset($this->sql)) {
-            if ($sql) {
-                $msg = array('sql' => $sql, 'error' => $msg);
-            } elseif (is_object($msg)) {
-                $msg = (array) $msg;
-            } elseif (is_string($msg)) {
-                $msg = array('sql' => $msg);
-            }
-            Debug::wait($msg, 'Dever SQL DB Error!');
-        } else {
-            if (is_string($msg)) {
-                $msg = array('value' => $msg);
-            }
-            Debug::wait($msg, 'Dever NOSQL DB Error!');
-        }
-    }
-
-    /**
-     * log
-     *
-     * @return log
-     */
-    public function log($value, $param = array(), $data = array())
-    {
-        if (isset($this->sql)) {
-            $value = $this->replace($value, $param, $this->sql);
-            $this->sql($value);
-            if (!Input::shell('all') && is_array($data)) {
-                $data = count($data) . ' records';
-            }
-            Debug::log(array('sql' => $value, 'data' => $data), $this->config['type']);
-        } else {
-            Debug::log(array('value' => $value, 'method' => $param), $this->config['type']);
-        }
-    }
-
-    /**
-     * sql
-     *
-     * @return sql
-     */
-    public function replace($value, $param)
-    {
-        if ($value && is_array($param)) {
-            foreach ($param as $k => $v) {
-                if (is_string($v)) {
-                    if (strstr($value, 'select') && strpos($v, ',')) {
-                        $v = 'in('.$v.')';
-                    } else {
-                        $v = '"' . $v . '"';
-                    }
-                }
-                $value = str_replace($k, $v, $value);
-            }
-        }
-
-        return $value;
-    }
-
-    /**
-     * sql
-     *
-     * @return mixed
-     */
-    public function sql($value)
-    {
-        if (!Config::get('database')->sql) {
-            Config::get('database')->sql = array();
-        }
-        $sql = Config::get('database')->sql;
-        array_push($sql, $value);
-        Config::get('database')->sql = $sql;
-    }
-
-    /**
-     * begin
-     *
-     * @return object
-     */
-    public function begin()
-    {
-        return $this;
-    }
-
-    /**
-     * commit
-     *
-     * @return object
-     */
-    public function commit()
-    {
-        return $this;
-    }
-
-    /**
-     * rollback
-     *
-     * @return object
-     */
-    public function rollback()
-    {
-        return $this;
-    }
-
-    /**
-     * fetchAll
-     *
-     * @return array
-     */
-    protected function fetchAll($handle, $config = false, $call = false)
-    {
-        $rows = function() use ($handle) {
-            while ($row = $handle->fetch()) {
-                yield $row;
-            }
-        };
-        $result = array();
-        $data = $rows();
-        if ($data) {
-            if ($config) {
-                $result = $this->fetchSet($data, $config, $call);
-            } else {
-                foreach ($data as $row) {
-                    $result[] = $this->cb($call, $row);
-                }
-            }
-        }
-        return $result;
-    }
-
-    /**
-     * call
-     *
-     * @return array
-     */
-    protected function cb($call, $data)
-    {
-        if ($call) {
-            return $call($data);
-        }
-        return $data;
-    }
-
-    /**
-     * fetchSet
-     *
-     * @return array
-     */
-    protected function fetchSet($data, $config, $call = false)
-    {
-        $result = array();
-        $key = $config[1];
-        foreach ($data as $row) {
-            if (isset($row[$key])) {
-                if (isset($config[3]) && isset($row[$config[2]])) {
-                    $result[$row[$key]][$row[$config[2]]] = $this->cb($call, $row);
-                } elseif (isset($config[2]) && isset($row[$config[2]])) {
-                    $result[$row[$key]] = $this->cb($call, $row[$config[2]]);
-                } elseif (isset($config[2])) {
-                    $result[$row[$key]][] = $this->cb($call, $row);
-                } else {
-                    $result[$row[$key]] = $this->cb($call, $row);
-                }
-            }
-        }
-        return $result;
-    }
-}

+ 0 - 562
src/Dever/Data/Store/Pdo.php

@@ -1,562 +0,0 @@
-<?php namespace Dever\Data\Store;
-use Dever\Data\Sql;
-class Pdo
-{
-    /**
-     * init
-     *
-     * @return mixd
-     */
-    public function init()
-    {
-        $this->sql = Sql::getInstance();
-    }
-
-    /**
-     * connect
-     *
-     * @return mixd
-     */
-    public function connect($config)
-    {
-        if ($this->handle) {
-            return;
-        }
-        if (strpos($config['host'], ':') !== false) {
-            list($config['host'], $config['port']) = explode(':', $config['host']);
-        }
-
-        $dsn['type'] = $config['type'];
-        $dsn['host'] = $config['host'];
-        $dsn['port'] = $config['port'];
-        $dsn['dbname'] = $config['database'];
-        $dsn['charset'] = $config['charset'];
-
-        if (!isset($config['collation'])) {
-            $config['collation'] = 'utf8mb4_general_ci';
-        }
-        $dsn['collation'] = $config['collation'];
-
-        foreach ($dsn as $key => $val) {
-            $dsn[$key] = "$key=$val";
-        }
-
-        $type = isset($config['pdo_type']) ? $config['pdo_type'] : 'mysql';
-        $dsnList = $type . ':' . implode(';', $dsn);
-
-        try {
-            $persistent = false;
-            if (isset($config['persistent'])) {
-                $persistent = $config['persistent'];
-            }
-            $this->handle = new \PDO($dsnList, $config['username'], $config['password'], array(\PDO::ATTR_PERSISTENT => $persistent));
-            $this->handle->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
-            //$this->handle->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
-            $this->handle->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_NATURAL);
-            $this->handle->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
-            //$this->handle->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
-
-            Debug::log('db ' . $config['host'] . ' connected', $config['type']);
-        } catch (\PDOException $e) {
-            if (strstr($e->getMessage(), 'Unknown database')) {
-                $method = 'mysql';
-                if (function_exists('mysqli_connect')) {
-                    $method = 'mysqli';
-                }
-                $connect = $method . '_connect';
-                $query = $method . '_query';
-                $close = $method . '_close';
-                $link = $connect($config['host'] . ':' . $config['port'], $config['username'], $config['password']);
-                if ($link) {
-                    if ($method == 'mysql') {
-                        $query("CREATE DATABASE `" . $config['database'] . "` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;", $link);
-                    } else {
-                        $query($link, "CREATE DATABASE `" . $config['database'] . "` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;");
-                    }
-                    
-                    $close($link);
-                }
-                
-                $this->init($config);
-            } else {
-                Export::alert($e->getMessage());
-            }
-        }
-    }
-
-    /**
-     * setTable
-     *
-     * @return mixd
-     */
-    public function setTable($table)
-    {
-        $this->table = $table;
-    }
-
-    /**
-     * getIndex
-     *
-     * @return mixed
-     */
-    public function getIndex($version, $index)
-    {
-        $this->register();
-        $sql = $this->sql->showIndex($this->table);
-
-        $handle = $this->update->query($sql);
-
-        $info = $handle->fetchAll();
-
-        $this->dropIndex($info);
-
-        $sql = $this->sql->index($this->table, $index[$version]);
-
-        $this->query($sql);
-
-        $this->log($sql, 'index');
-
-        $data['index'] = $version;
-
-        $data['order'] = array_flip(explode(',', array_shift($index[$version])));
-
-        return $data;
-    }
-
-    private function dropIndex($info)
-    {
-        if ($info) {
-            $this->register();
-            $index = array();
-            foreach ($info as $k => $v) {
-                if ($v['Key_name'] != 'PRIMARY' && !isset($index[$v['Key_name']])) {
-                    $sql = $this->sql->dropIndex($this->table, $v['Key_name']);
-                    $this->update->query($sql);
-                    $index[$v['Key_name']] = true;
-                }
-            }
-        }
-    }
-
-    public function exe($sql, $value = array(), $method = '')
-    {
-        $create = false;
-        if (stristr($sql, 'create')) {
-            $create = true;
-        }
-        $this->register($create);
-        
-        if ($create && isset($this->create)) {
-            $db = $this->create;
-        } elseif (stristr($sql, 'select')) {
-            $db = $this->read;
-        } else {
-            $db = $this->update;
-        }
-
-        if (!is_array($value)) {
-            $value = array(':0' => $value);
-        }
-
-        try {
-            if ($value) {
-                $handle = $db->prepare($sql);
-                $handle->execute($value);
-            } else {
-                $handle = $db->query($sql);
-            }
-        } catch (\PDOException $exception) {
-            $this->error($exception->getMessage(), $sql);
-        }
-
-        if ($method) {
-            $data = $handle->$method();
-            $this->log($sql, $value, $data);
-            return $data;
-        } else {
-            return $handle;
-        }
-    }
-
-    public function query($sql, $state = false)
-    {
-        if (empty($this->config['shell'])) {
-            if (is_string($this->config['host']) && strpos($this->config['host'], ':') !== false) {
-                $temp = explode(':', $this->config['host']);
-                $this->config['host'] = $temp[0];
-                $this->config['port'] = $temp[1];
-            } elseif (isset($this->config['host']['read']) && strpos($this->config['host']['read'], ':') !== false) {
-                $temp = explode(':', $this->config['host']['read']);
-                $this->config['host'] = $temp[0];
-                $this->config['port'] = $temp[1];
-            }
-
-            $this->config['shell'] = 'mysql -u' . $this->config['username'] . ' -p' . $this->config['password'] . ' ' . $this->config['database'] . ' -h' . $this->config['host'] . ' -P' . $this->config['port'] . ' -e ';
-        }
-
-        if ($state == true) {
-            # 异步执行
-            \Dever::run($this->config['shell'] . '"' . $sql . '"');
-        } else {
-            try {
-                $this->register();
-                # 同步执行
-                if (strpos($sql, ';')) {
-                    $temp = explode(';', $sql);
-                    foreach ($temp as $k => $v) {
-                        $this->update->query($v);
-                    }
-                } else {
-                    $this->update->query($sql);
-                }
-            } catch (\PDOException $exception) {
-                $this->error($exception->getMessage(), $sql);
-            }
-        }
-    }
-
-    /**
-     * insert the default value
-     *
-     * @return mixed
-     */
-    public function insertValues($value, $data = array())
-    {
-        $this->register();
-        $sql = $this->sql->insertValues($this->table, $value['col'], $value['value']);
-
-        try {
-            $this->update->query($sql);
-        } catch (\PDOException $exception) {
-            $this->error($exception->getMessage(), $sql);
-        }
-
-        $this->log($sql, 'insertValues');
-
-        $data['insert'] = $sql;
-
-        return $data;
-    }
-
-    /**
-     * all
-     *
-     * @return array
-     */
-    public function all($col, $call = false)
-    {
-        $config = false;
-        if (strpos($col, '|') !== false) {
-            $config = explode('|', $col);
-            $col = $config[0];
-        }
-        return $this->select($col, 'fetchAll', 'select', $config, $call);
-    }
-
-    /**
-     * one
-     *
-     * @return array
-     */
-    public function one($col)
-    {
-        return $this->select($col);
-    }
-
-    /**
-     * count
-     *
-     * @return array
-     */
-    public function count($col = '')
-    {
-        return $this->select($col, 'fetchColumn', 'count');
-    }
-
-    /**
-     * insert
-     *
-     * @return int
-     */
-    public function insert($num = 1)
-    {
-        $sql = $this->sql->insert($this->table, $num);
-
-        if ($sql) {
-            try {
-                $this->register();
-
-                $handle = $this->update->prepare($sql);
-
-                $handle->execute($this->value);
-            } catch (\PDOException $exception) {
-                $this->error($exception->getMessage(), $sql);
-            }
-
-            $id = $this->update->id();
-
-            $this->log($sql, $this->value);
-
-            $this->cache();
-        }
-
-        $this->value = array();
-
-        return $id;
-    }
-
-    /**
-     * update
-     *
-     * @return int
-     */
-    public function update()
-    {
-        $sql = $this->sql->update($this->table);
-
-        $result = false;
-
-        if ($sql) {
-            try {
-                $this->register();
-
-                $handle = $this->update->prepare($sql);
-
-                $handle->execute($this->value);
-            } catch (\PDOException $exception) {
-                $this->error($exception->getMessage(), $sql);
-            }
-
-            $result = $handle->rowCount();
-            //$result = $this->update->id();
-
-            $this->log($sql, $this->value);
-
-            $this->cache();
-        }
-
-        $this->value = array();
-
-        return $result;
-    }
-
-    /**
-     * delete
-     *
-     * @return int
-     */
-    public function delete()
-    {
-        $sql = $this->sql->delete($this->table);
-
-        $result = false;
-
-        if ($sql) {
-            try {
-                $this->register();
-
-                $handle = $this->update->prepare($sql);
-
-                $handle->execute($this->value);
-            } catch (\PDOException $exception) {
-                $this->error($exception->getMessage(), $sql);
-            }
-
-            $result = $handle->rowCount();
-
-            $this->log($sql, $this->value);
-
-            $this->cache();
-        }
-
-        $this->value = array();
-
-        return $result;
-    }
-
-    /**
-     * select
-     *
-     * @return array
-     */
-    private function select($col = '', $method = 'fetch', $type = 'select', $config = false, $call = false)
-    {
-        $sql = $this->sql->{$type}($this->table, $col);
-
-        $key = $this->table . '_' . $method . '_' . md5(serialize($this->value) . $sql);
-
-        $data = $this->cache($key);
-
-        if ($data !== false) {
-            if ($col != 'clear') {
-                $this->value = array();
-            }
-
-            return $data;
-        }
-
-        if ($type == 'count' && strpos($sql, 'group by `')) {
-            $method = 'fetchAll';
-        }
-
-        try {
-            $this->register();
-
-            if ($this->value) {
-                $handle = $this->read->prepare($sql);
-                /*
-                if ($method == 'fetchAll') {
-                    # 查询大量数据时,不缓存数据到内存,防止内存溢出
-                    $this->read->set();
-                }*/
-                $handle->execute($this->value);
-            } else {
-                $handle = $this->read->query($sql);
-            }
-        } catch (\PDOException $exception) {
-            $this->error($exception->getMessage(), $sql);
-        }
-
-        if ($method == 'fetchAll') {
-            if ($call) {
-                $this->value = array();
-            }
-            $data = $this->fetchAll($handle, $config, $call);
-            
-        } else {
-            $data = $handle->$method();
-        }
-
-        //print_r($data);die;
-        $state = $this->cache($key, 'put', $data);
-        $this->log($sql, $this->value, $data);
-        if ($col != 'clear') {
-            $this->value = array();
-        }
-        return $data;
-    }
-
-    /**
-     * join
-     *
-     * @return object
-     */
-    public function join($param)
-    {
-        $this->sql->join($param);
-
-        return $this;
-    }
-
-    /**
-     * begin
-     *
-     * @return object
-     */
-    public function begin()
-    {
-        $this->register();
-        $this->update->method('beginTransaction');
-
-        return $this;
-    }
-
-    /**
-     * commit
-     *
-     * @return object
-     */
-    public function commit()
-    {
-        $this->register();
-        $this->update->method('commit');
-
-        return $this;
-    }
-
-    /**
-     * rollback
-     *
-     * @return object
-     */
-    public function rollback()
-    {
-        $this->register();
-        $this->update->method('rollBack');
-
-        return $this;
-    }
-
-    /**
-     * __call
-     *
-     * @return object
-     */
-    public function __call($method, $param)
-    {
-        if (isset($param[0]) && is_array($param[0]) && $method != 'order') {
-            foreach ($param[0] as $k => $v) {
-                $this->call($method, $v);
-            }
-        } else {
-            $this->call($method, $param);
-        }
-
-        return $this;
-    }
-
-    /**
-     * call
-     *
-     * @return mixd
-     */
-    private function call($method, $param)
-    {
-        if ($method == 'where' || $method == 'set' || $method == 'add') {
-            # 特殊处理in
-            if (!strstr($param[1], '/') && strstr($param[1], 'select') && $param[1] != 'selected') {
-
-            } elseif (isset($param[2]) && ($param[2] == 'in' || $param[2] == 'not in')) {
-                if (!is_array($param[1])) {
-                    $param[1] = explode(',', $param[1]);
-                }
-
-                $prefix = 'in_';
-                $temp = $param[0];
-                foreach ($param[1] as $k => $v) {
-                    if (strpos($temp, '.')) {
-                        $temp = str_replace('.', '_', $temp);
-                    }
-                    $k = ':' . $temp . '_' . $prefix . $k;
-                    $key[] = $k;
-                    $this->value[$k] = $v;
-                }
-
-                $param[1] = '(' . implode(',', $key) . ')';
-            } else {
-                $prefix = $param[0];
-                if (strstr($prefix, ',')) {
-                    $prefix = str_replace(',', '_', $prefix);
-                }
-                if (strstr($prefix, '.')) {
-                    $prefix = str_replace('.', '_', $prefix);
-                }
-                if (strstr($prefix, '-')) {
-                    $prefix = str_replace('-', '_', $prefix);
-                }
-                $key = ':' . $prefix . count($this->value);
-
-                $this->value[$key] = $param[1];
-
-                $param[1] = $key;
-
-                if (isset($param[2]) && $param[2] == 'like') {
-                    $param[2] = 'like^' . $this->value[$key];
-                    //$this->value[$key] = trim($this->value[$key], ',');
-                }
-            }
-        }
-
-        $this->sql->$method($param);
-    }
-}

+ 68 - 31
src/Dever/Debug.php

@@ -2,52 +2,73 @@
 use Dever;
 class Debug
 {
+    public static $shell;
     private static $data;
     private static $trace;
-    private static $tool;
     private static $time;
     private static $memory;
-    public static $shell;
     private static $start;
     public static function init()
     {
         self::$shell = Dever::shell(Config::get('setting')['shell']);
         if (self::$shell) {
-            ini_set('display_errors', true);
             self::$start = microtime();
-            self::$tool = new \Whoops\Run;
-            self::$tool->pushHandler(new \Whoops\Handler\PrettyPageHandler);
-            if (\Whoops\Util\Misc::isAjaxRequest()) {
-                self::$tool->pushHandler(new \Whoops\Handler\JsonResponseHandler);
+            ini_set('display_errors', true);
+            set_error_handler(array(__CLASS__, 'error_handler'));
+            set_exception_handler(array(__CLASS__, 'exception_handler'));
+        }
+    }
+    public static function error_handler($no, $str, $file, $line)
+    {
+        $data['msg'] = $str;
+        $data['file'] = $file . ':' . $line;
+        $content = file_get_contents($file);
+        $lines = explode("\n", $content);
+        $lines = array_slice($lines, $line - 10, 20, true);
+        $code = '<code>';
+        foreach ($lines as $k => $v) {
+            $k+=1;
+            if ($k == $line) {
+                $code .= '<a style="display:inline-block;color:red">' . $k . $v . '</a>';
+            } else {
+                $code .= $k . $v;
             }
-            self::$tool->register();
+            $code .= "\n";
         }
+        $code .= '</code>';
+        self::add($code, false);
+        self::out($data, false);
+    }
+    public static function exception_handler($exception)
+    {
+        self::error_handler($exception->getCode(), $exception->getMessage(), $exception->getFile(), $exception->getLine());
     }
-    public static function add($msg, $type = 'log')
+    public static function add($data, $type = 'log')
     {
         if (self::$shell) {
-            $format = is_array($msg) ? $msg : array('msg' => $msg);
-            $format = array_merge($format, self::env());
-            self::data($type, Output::format($format));
+            $msg = $data;
+            if ($type) {
+                $msg = is_array($msg) ? $msg : array('msg' => $msg);
+                $msg = array_merge($msg, self::env());
+            }
+            self::data($type, Output::format($msg));
         }
+        return $data;
     }
     public static function out($data, $type = 'out')
     {
         if (self::$shell) {
-            self::add($data, 'out');
-            self::runtime();
-            $handler = self::$tool->getHandlers();
-            foreach (self::$data as $k => $v) {
-                $handler[0]->addDataTable(ucwords($k), $v);
-            }
-            $title = 'Dever Debug!';
-            $handler[0]->setPageTitle($title);
-            throw new Exceptions($title);
+            self::add($data, $type);
+            self::total();
+            echo self::html();die;
         }
     }
-    public static function error($msg, $type = 'error')
+    public static function total()
     {
-        self::$shell = true;self::out($msg, $type);
+        self::data('include', Output::format(self::load()));
+        $msg = array('time' => self::time(), 'memory' => self::memory());
+        self::data('total', Output::format($msg));
+        return $msg;
     }
     public static function lib($class, $method)
     {
@@ -81,8 +102,8 @@ class Debug
                 }
             }
         }
-        if (!$trace) {
-            $trace = array_keys((self::$trace));
+        if (!$trace && self::$trace) {
+            $trace = array_keys(self::$trace);
             $trace = $trace[0];
         }
         return $trace;
@@ -106,14 +127,11 @@ class Debug
     }
     private static function data($method, $msg)
     {
+        if (!$method) {
+            $method = 'error';
+        }
         self::$data[$method][] = $msg;
     }
-    private static function runtime()
-    {
-        self::data('runtime', Output::format(self::load()), 'Load Files');
-        $msg = Output::format(array('time' => self::time(), 'memory' => self::memory()));
-        self::data('runtime', $msg, 'Total');
-    }
     private static function check($value)
     {
         if (isset($value['file']) && strpos($value['file'], DEVER_APP_PATH) !== false) {
@@ -171,4 +189,23 @@ class Debug
         }
         return $result;
     }
+    private static function html($show = '')
+    {
+        $html = '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/styles/atom-one-dark.min.css">
+<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script><div>';
+        if (self::$data) {
+            foreach (self::$data as $k => $v) {
+                $html .= $k;
+                $html .= '<table style="width:100%;">';
+                foreach ($v as $i => $j) {
+                    $html .= '<tr>';
+                    $html .= '<td style="background-color:#f5f5f5;padding: 8px;">' . $j . '</td>';
+                    $html .= '</tr>';
+                }
+                $html .= '</table>';
+            }
+        }
+        $html .= '</div><script>hljs.highlightAll();</script>';
+        return $html;
+    }
 }

+ 0 - 14
src/Dever/Exceptions.php

@@ -1,14 +0,0 @@
-<?php namespace Dever;
-use RuntimeException;
-class Exceptions extends RuntimeException
-{
-    public function __construct($message, $code = 0)
-    {
-        parent::__construct($message, $code);
-    }
-    public function getTraces()
-    {
-    	$data = Debug::getTrace();
-    	return $data;
-    }
-}

+ 18 - 0
src/Dever/Helper/Arr.php

@@ -0,0 +1,18 @@
+<?php namespace Dever\Helper;
+class Arr
+{
+    public static function replace($replace, $value, $key = 'col')
+    {
+        $result = array();
+        foreach ($replace as $k => $v) {
+            if (isset($value[$k])) {
+                $v = $value[$k];
+                $k = $value[$k][$key];
+            }
+            if ($v) {
+                $result[$k] = $v;
+            }
+        }
+        return $result;
+    }
+}

+ 53 - 0
src/Dever/Helper/Cmd.php

@@ -0,0 +1,53 @@
+<?php namespace Dever\Helper;
+use Dever;
+class Cmd
+{
+    public static function run($api, $app = false, $daemon = true)
+    {
+        if (strpos($api, 'http://') !== false) {
+            return self::shell('curl "' . $api . '"');
+        }
+        if (!$app) {
+            $app = DEVER_APP_NAME;
+        }
+        $app = Dever::project($app);
+        if (strpos($app['path'], 'http') !== false) {
+            return self::shell('curl "' . $app['path'] . $api . '"', $daemon);
+        } else {
+            $php = Dever::config('setting')['php'] ?? 'php';
+            $temp = explode('?', $api);
+            parse_str($temp[1], $param);
+            $param['l'] = $temp[0];
+            return self::shell($php . ' ' . $app['path'] . 'index.php ' . $param, $daemon);
+        }
+    }
+    public static function kill($command)
+    {
+        self::shell("ps -ef | grep " . $command . " | grep -v grep | awk '{print $2}' | xargs kill -9");
+    }
+    public static function shell($shell, $daemon = true)
+    {
+        if ($daemon) {
+            $shell .= ' 1>/dev/null 2>&1 &';
+        }
+        $result = exec($shell);
+        return $result;
+    }
+    public static function bash($cmd)
+    {
+        $file = Dever::path('shell/' . md5($cmd));
+        $cmd = '#!/usr/bin/env sh ' . "\n" . $cmd;
+        file_put_contents($file, $cmd);
+        exec('chmod +x ' . $file);
+        return $file;
+    }
+    public static function process($command, $count = false)
+    {
+        $shell = "ps -ef | grep " . $command . " | grep -v grep";
+        if ($count) {
+            $shell .= ' | wc -l';
+        }
+        $result = self::run($shell, false);
+        return $result;
+    }
+}

+ 269 - 0
src/Dever/Helper/Curl.php

@@ -0,0 +1,269 @@
+<?php namespace Dever\Helper;
+use Dever;
+class Curl
+{
+    private $handle;
+    private $url;
+    private $get_info = false;
+    private $log = true;
+    private $result_header = false;
+    private $param = array();
+    private $header = array();
+    public function load($url, $param = false, $type = '', $json = false, $header = false, $agent = false, $proxy = false, $refer = false)
+    {
+        if ($type == 'get_info') {
+            $this->get_info = true;
+            $type = 'get';
+        }
+        $this->init();
+        $this->param($param);
+        $this->setRequest($type);
+        if ($header) {
+            $this->setHeader($header);
+        }
+        if (!$agent) {
+            $agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36';
+        }
+        if ($agent) {
+            $this->setAgent($agent);
+        }
+        if ($proxy) {
+            $this->setProxy($proxy);
+        }
+        if ($refer) {
+            $this->setRefer($refer);
+        }
+        if ($json) {
+            $this->setJson($param);
+        } elseif ($type == 'file') {
+            $this->setFormData($param);
+        } elseif ($type == 'post' || $type == 'put') {
+            $this->setForm($param);
+        } elseif ($param) {
+            if (strpos($url, '?')) {
+                $url .= '&';
+            } else {
+                $url .= '?';
+            }
+            $url .= http_build_query($param);
+        }
+        if (strpos($url, '??')) {
+            $url = str_replace('??', '?', $url);
+        }
+        $this->setUrl($url);
+        return $this;
+    }
+    public function setLog($log)
+    {
+        $this->log = $log;
+    }
+    private function init()
+    {
+        if (!$this->handle) {
+            $this->handle = curl_init();
+        }
+    }
+    private function param(&$param)
+    {
+        if ($param && is_array($param) && isset($param[0])) {
+            $temp = $param;
+            $param = array();
+            foreach ($temp as $k => $v) {
+                if (is_array($v)) {
+                    $param = array_merge($param, $v);
+                } else {
+                    $param[$k] = $v;
+                }
+            }
+        }
+    }
+    public function setRequest($type)
+    {
+        if ($type == 'post' || $type == 'file') {
+            curl_setopt($this->handle, CURLOPT_POST, true);
+        } elseif ($type == 'put' || $type == 'delete') {
+            curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, strtoupper($type));
+        } else {
+            curl_setopt($this->handle, CURLOPT_HTTPGET, true);
+        }
+    }
+    public function setHeader($header)
+    {
+        if (is_array($header)) {
+            foreach ($header as $k => $v) {
+                if (is_string($k)) {
+                    $this->header[] = $k . ':' . $v;
+                } else {
+                    $this->header[] = $v;
+                }
+            }
+        } else {
+            $this->header = explode("\n", $header);
+        }
+    }
+    public function setAgent($agent)
+    {
+        curl_setopt($this->handle, CURLOPT_USERAGENT, $agent);
+    }
+    public function setProxy($proxy)
+    {
+        curl_setopt($this->handle, CURLOPT_PROXY, $proxy[0]); //代理服务器地址   
+        curl_setopt($this->handle, CURLOPT_PROXYPORT, $proxy[1]); //代理服务器端口
+        curl_setopt($this->handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
+    }
+    public function setRefer($refer)
+    {
+        curl_setopt($this->handle, CURLOPT_REFERER, $refer);
+    }
+    public function setJson($param)
+    {
+        if (is_array($param)) {
+            if (isset($param['item_desc'])) {
+                $param = json_encode($param, JSON_UNESCAPED_UNICODE);
+            } else {
+                $param = json_encode($param);
+            }
+        }
+        $header['Content-Type'] = 'application/json';
+        $header['Content-Length'] = strlen($param);
+        $this->setHeader($header);
+        $this->setParam($param);
+    }
+    public function setFormData($param)
+    {
+        $header['Content-Type'] = 'multipart/form-data';
+        if (!is_array($param)) {
+            $param = json_decode($param, $param);
+        }
+        $this->setHeader($header);
+        $this->setParam($param);
+    }
+    public function setForm($param)
+    {
+        $header['Content-Type'] = 'application/x-www-form-urlencoded';
+        if (!is_array($param)) {
+            $param = json_decode($param, $param);
+        }
+        if (is_array($param)) {
+            $param = http_build_query($param);
+        }
+        $this->setHeader($header);
+        $this->setParam($param);
+    }
+    public function setUrl($url)
+    {
+        $this->url = $url;
+        curl_setopt($this->handle, CURLOPT_URL, $url);
+        curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, true);
+    }
+    public function result($setting = false)
+    {
+        if ($setting) {
+            $this->setting($setting);
+        }
+        if ($this->header) {
+            curl_setopt($this->handle, CURLOPT_HTTPHEADER, $this->header);
+        }
+        curl_setopt($this->handle, CURLOPT_HEADER, false);
+        if ($this->result_header) {
+            $this->result_header = array();
+            curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, array($this, 'headerHandler'));
+        }
+        if (Dever::shell('debug')) {
+            curl_setopt($this->handle, CURLINFO_HEADER_OUT, true);
+        }
+        curl_setopt($this->handle, CURLOPT_ACCEPT_ENCODING, 'gzip,deflate');
+        $result = curl_exec($this->handle);
+        $debug = array();
+        if (Dever::shell('debug')) {
+            $debug['request'] = curl_getinfo($this->handle, CURLINFO_HEADER_OUT);
+        } elseif ($this->get_info) {
+            $result = curl_getinfo($this->handle);
+        }
+        curl_close($this->handle);
+        $data = $result;
+        if (!Dever::shell('all') && is_array($data)) {
+            $data = count($data) . ' records';
+        }
+        $debug['url'] = $this->url;
+        $debug['param'] = $this->param;
+        $debug['result'] = $data;
+        if ($this->log) {
+            Dever::log($debug, 'curl');
+        }
+        Dever::debug($debug, 'curl');
+        return $result;
+    }
+    public function setting($setting = array())
+    {
+        if ($setting) {
+            $this->init();
+            foreach ($setting as $k => $v) {
+                $method = 'set' . ucfirst($k);
+                $this->$method($v);
+            }
+        }
+    }
+    public function setVerbose($verbose)
+    {
+        curl_setopt($this->handle, CURLOPT_VERBOSE, $verbose);
+    }
+    public function setUserPWD($userpwd)
+    {
+        curl_setopt($this->handle, CURLOPT_USERPWD, $userpwd);
+    }
+    public function setTimeOut($time)
+    {
+        curl_setopt($this->handle, CURLOPT_TIMEOUT, $time);
+    }
+    public function setCookie($cookie)
+    {
+        curl_setopt($this->handle, CURLOPT_COOKIE, $cookie);
+    }
+    public function setParam($param)
+    {
+        $this->param = $param;
+        if (is_array($param)) {
+            $param = http_build_query($param);
+        }
+        curl_setopt($this->handle, CURLOPT_POSTFIELDS, $param);
+    }
+    public function setEncode($encode)
+    {
+        curl_setopt($this->handle, CURLOPT_ENCODING, $encode);
+    }
+    public function setIp($ip)
+    {
+        $config['CLIENT-IP'] = $ip;
+        $config['X-FORWARDED-FOR'] = $ip;
+        $this->setHeader($config);
+    }
+    public function setResultHeader($value)
+    {
+        $this->result_header = $value;
+    }
+    public function header()
+    {
+        return $this->result_header;
+    }
+    private function headerHandler($curl, $headerLine)
+    {
+        $len = strlen($headerLine);
+        $split = explode(':', $headerLine, 2);
+        if (count($split) > 1) {
+            $key = trim($split[0]);
+            $value = trim($split[1]);
+            $this->result_header[$key] = $value;
+        }
+        return $len;
+    }
+    public function resultCookie()
+    {
+        $result = $this->result();
+        list($header, $body) = explode("\r\n\r\n", $result, 2);
+        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
+        $info['cookie']  = substr($matches[1][0], 1);
+        $info['content'] = $body;
+        return $info;
+    }
+}

+ 148 - 0
src/Dever/Helper/Date.php

@@ -0,0 +1,148 @@
+<?php namespace Dever\Helper;
+class Date
+{
+    # 获取时间戳
+    public static function mktime($v)
+    {
+        if (!$v) {
+            return '';
+        }
+        if (is_numeric($v)) {
+            return $v;
+        }
+        if (strstr($v, ' ')) {
+            $t = explode(' ', $v);
+            $v = $t[0];
+            $s = explode(':', $t[1]);
+        } else {
+            $s = array(0, 0, 0);
+        }
+        if (!isset($s[1])) {
+            $s[1] = 0;
+        }
+        if (!isset($s[2])) {
+            $s[2] = 0;
+        }
+        if (strstr($v, '-')) {
+            $t = explode('-', $v);
+        } elseif (strstr($v, '/')) {
+            $u = explode('/', $v);
+            $t[0] = $u[2];
+            $t[1] = $u[0];
+            $t[2] = $u[1];
+        }
+        if (!isset($t)) {
+            $t = array(0, 0, 0);
+        }
+        if (!isset($t[1])) {
+            $t[1] = '-1';
+        }
+        if (!isset($t[2])) {
+            $t[2] = '01';
+        }
+        $v = mktime($s[0], $s[1], $s[2], $t[1], $t[2], $t[0]);
+        return $v;
+    }
+    # 获取日期
+	public static function mkdate($num, $type = 2)
+    {
+        $date = $num;
+        $num = time() - $num;
+        if ($num <= 0) {
+            if ($type == 2) {
+                return '1秒前';
+            } else {
+                return '1S';
+            }
+        }
+        $config = array(
+            array(31536000, 'Y', '年'),
+            array(2592000, 'T', '个月'),
+            array(604800, 'W', '星期'),
+            array(86400, 'D', '天'),
+            array(3600, 'H', '小时'),
+            array(60, 'M', '分钟'),
+            array(1, 'S', '秒'),
+        );
+        if ($type == 2) {
+            foreach ($config as $k => $v) {
+                $value = intval($num / $v[0]);
+                if ($v[1] == 'D' && $value >= 7) {
+                    break;
+                }
+                if ($value != 0) {
+                    return $value . $v[2] . '前';
+                }
+            }
+            return date('Y-m-d H:i:s', $date);
+        } else {
+            $result = '';
+            foreach ($config as $k => $v) {
+                if ($num > $v[0]) {
+                    $value = intval($num / $v[0]);
+                    $num = $num - $v[0] * $value;
+                    $result .= $value . $v[1] . ' ';
+                }
+            }
+            return $result;
+        }
+    }
+    # 获取周的开始时间和结束时间
+    public static function week($time = false, $prefix = '-')
+    {
+        if (strpos($time, '-')) {
+            $time = self::mktime($time);
+        } elseif ($time > 0) {
+            $time = strtotime($prefix . $time . ' week');
+        } elseif (!$time) {
+            $time = time();
+        }
+        $start = self::maketime(date('Y-m-d 00:00:00', strtotime('this week Monday', $time)));
+        $end = self::maketime(date('Y-m-d 23:59:59', strtotime('this week Sunday', $time)));
+        return array($start, $end);
+    }
+
+    # 获取月的开始时间和结束时间
+    public static function month($time = false, $prefix = '-')
+    {
+        if (strpos($time, '-')) {
+            $time = self::mktime($time);
+        } elseif ($time > 0) {
+            $time = strtotime($prefix . $time . ' month');
+        } elseif (!$time) {
+            $time = time();
+        }
+        list($year, $month, $end) = explode('-', date('Y-m-t', $time));
+        $start = self::mktime($year . '-' . $month . '-01 00:00:00');
+        $end = self::mktime($year . '-' . $month . '-' . $end . ' 23:59:59');
+        return array($start, $end);
+    }
+    # 获取天的开始时间和结束时间
+    public static function day($time = false, $prefix = '-')
+    {
+        if (strpos($time, '-')) {
+            $time = self::mktime($time);
+        } elseif ($time > 0) {
+            $time = strtotime($prefix . $time . ' day');
+        } elseif (!$time) {
+            $time = time();
+        }
+        list($year, $month, $day) = explode('-', date('Y-m-d', $time));
+        $start = Dever::maketime($year . '-' . $month . '-' . $day . ' 00:00:00');
+        $end = Dever::maketime($year . '-' . $month . '-' . $day . ' 23:59:59');
+        return array($start, $end);
+    }
+    # 获取毫秒
+    public static function mtime()
+    {
+        list($msec, $sec) = explode(' ', microtime());
+        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
+        return $msectime;
+    }
+    # 获取第几周
+    public static function getWeek($time)
+    {
+        $week = abs(ceil((date('j', $time) - [0,6,5,4,3,2,1][date('w', strtotime(date('Y-m-01')))]) / 7));
+        return $week + 1;
+    }
+}

+ 1 - 5
src/Dever/String/Env.php → src/Dever/Helper/Env.php

@@ -1,4 +1,4 @@
-<?php namespace Dever\Support;
+<?php namespace Dever\Helper;
 class Env
 {
     public static function ua()
@@ -17,7 +17,6 @@ class Env
         $agent  = $_SERVER['HTTP_USER_AGENT'];
         $browser  = '';
         $version  = '';
-  
         if (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
             $browser  = 'OmniWeb';
             $version  = $regs[2];
@@ -58,7 +57,6 @@ class Env
             $browser  = 'MicroMessenger';
             $version  = '';
         }
-  
         if ($browser != '') {
             return $browser . ':' . $version;
         } else {
@@ -69,7 +67,6 @@ class Env
     {
         $agent = $_SERVER['HTTP_USER_AGENT'];
         $os = false;
-       
         if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
             $os = 'Windows 95';
         } elseif (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
@@ -201,7 +198,6 @@ class Env
                 $headers[str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($name, 5))))] = $value;
             }
         }
-
         return is_null($key) ? $headers : (isset($headers[$key]) ? $headers[$key] : null);
     }
 }

+ 1 - 1
src/Dever/Lang.php → src/Dever/Helper/Lang.php

@@ -1,4 +1,4 @@
-<?php namespace Dever;
+<?php namespace Dever\Helper;
 class Lang
 {
     private static $data = array();

+ 15 - 50
src/Dever/Support/Math.php → src/Dever/Helper/Math.php

@@ -1,4 +1,4 @@
-<?php namespace Dever\Support;
+<?php namespace Dever\Helper;
 class Math
 {
 	# 笛卡尔积
@@ -13,7 +13,6 @@ class Math
                         $v[$k1] = array($v1);
                     }
                 }
-                
                 $result[] = $v;
             }
         } else {
@@ -35,8 +34,6 @@ class Math
                 }
             }
         }
-        
-
         return $result;
     }
     # 计算距离
@@ -58,74 +55,42 @@ class Math
         }
         return $km;
     }
-
-    # 获取距离sql
-    public static function distanceSql($lng, $lat)
-    {
-        return 'round((st_distance(point(lng, lat), point('.$lng.', '.$lat.'))*111195)/1000, 2) as distance';
-    }
     # 将数值金额转换为中文大写金额
     public static function convertNum($amount, $type = 1) {
-        // 判断输出的金额是否为数字或数字字符串
-        if(!is_numeric($amount)){
-            return "要转换的金额只能为数字!";
+        if (!is_numeric($amount) || strlen($amount) > 12) {
+            return false;
         }
-
-        // 金额为0,则直接输出"零元整"
         if($amount == 0) {
             return "零元整";
         }
-
-        // 金额不能为负数
+        $result = '';
         if($amount < 0) {
-            return "要转换的金额不能为负数!";
+            $result = '负';
         }
-
-        // 金额不能超过万亿,即12位
-        if(strlen($amount) > 12) {
-            return "要转换的金额不能为万亿及更高金额!";
-        }
-
-        // 预定义中文转换的数组
         $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
-        // 预定义单位转换的数组
         $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');
-
-        // 将金额的数值字符串拆分成数组
         $amountArr = explode('.', $amount);
-
-        // 将整数位的数值字符串拆分成数组
         $integerArr = str_split($amountArr[0], 1);
-
-        // 将整数部分替换成大写汉字
-        $result = '';
-        $integerArrLength = count($integerArr);     // 整数位数组的长度
-        $positionLength = count($position);         // 单位数组的长度
-        for($i = 0; $i < $integerArrLength; $i++) {
-            // 如果数值不为0,则正常转换
-            if($integerArr[$i] != 0){
+        $integerArrLength = count($integerArr);
+        $positionLength = count($position);
+        for ($i = 0; $i < $integerArrLength; $i++) {
+            if ($integerArr[$i] != 0) {
                 $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
-            }else{
-                // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
-                if(($positionLength - $integerArrLength + $i + 1)%4 == 0){
+            } else {
+                if (($positionLength - $integerArrLength + $i + 1)%4 == 0) {
                     $result = $result . $position[$positionLength - $integerArrLength + $i];
                 }
             }
         }
-
-        // 如果小数位也要转换
-        if($type == 0) {
-            // 将小数位的数值字符串拆分成数组
+        if ($type == 0) {
             $decimalArr = str_split($amountArr[1], 1);
-            // 将角替换成大写汉字. 如果为0,则不替换
-            if($decimalArr[0] != 0){
+            if ($decimalArr[0] != 0){
                 $result = $result . $digital[$decimalArr[0]] . '角';
             }
-            // 将分替换成大写汉字. 如果为0,则不替换
-            if($decimalArr[1] != 0){
+            if ($decimalArr[1] != 0){
                 $result = $result . $digital[$decimalArr[1]] . '分';
             }
-        }else{
+        } else {
             $result = $result . '整';
         }
         return $result;

+ 42 - 0
src/Dever/Helper/Path.php

@@ -0,0 +1,42 @@
+<?php namespace Dever\Helper;
+use Dever;
+class Path
+{
+    public static function id($id, $path = '')
+    {
+        $id = abs(intval($id));
+        $sid = sprintf("%09d", $id);
+        $dir1 = substr($sid, 0, 3);
+        $dir2 = substr($sid, 3, 2);
+        $dir3 = substr($sid, 5, 2);
+        if ($path) {
+            $path .= DIRECTORY_SEPARATOR;
+        }
+        $path = Dever::path($dir1 . DIRECTORY_SEPARATOR . $dir2 . DIRECTORY_SEPARATOR . $dir3 . DIRECTORY_SEPARATOR);
+        return $path;
+    }
+    public static function month($path, $time = false)
+    {
+        if (!$time) {
+            $time = time();
+        }
+        if (is_numeric($time)) {
+            $time = date('Y_m_d', $time);
+        }
+        $date = explode('_', $time);
+        $path = Dever::path($path . DIRECTORY_SEPARATOR . $date[0] . DIRECTORY_SEPARATOR . $date[1] . DIRECTORY_SEPARATOR);
+        return $path;
+    }
+    public static function day($path, $time = false)
+    {
+        if (!$time) {
+            $time = time();
+        }
+        if (is_numeric($time)) {
+            $time = date('Y_m_d', $time);
+        }
+        $date = explode('_', $time);
+        $path = Dever::path($path . DIRECTORY_SEPARATOR . $date[0] . DIRECTORY_SEPARATOR . $date[1] . DIRECTORY_SEPARATOR . $date[2] . DIRECTORY_SEPARATOR);
+        return $path;
+    }
+}

+ 127 - 0
src/Dever/Helper/Redis.php

@@ -0,0 +1,127 @@
+<?php namespace Dever\Helper;
+use Dever\Debug;
+class Redis
+{
+    private static $handle;
+    private static $expire = 3600;
+    public static function connect()
+    {
+        if (!self::$handle) {
+            $config = \Dever::config('setting')['redis'] ?? false;
+            if (!$config) {
+                \Dever::error('redis error');
+            }
+            self::$expire = $config['expire'];
+            self::$handle = new \Redis;
+            self::$handle->pconnect($config["host"], $config["port"]);
+            if (isset($config['password']) && $config['password']) {
+                self::$handle->auth($config['password']);
+            }
+            self::$handle->setOption(\Redis::OPT_READ_TIMEOUT, -1);
+        }
+        return self::$handle;
+    }
+    public static function get($key)
+    {
+        return Debug::add(self::connect()->get($key), 'cache');
+    }
+    public static function set($key, $value, $expire = 0)
+    {
+        self::expire($expire);
+        return self::connect()->set($key, $value, self::$expire);
+    }
+    public static function lock($key, $value, $expire = 0)
+    {
+        self::expire($expire);
+        return self::connect()->set($key, $value, ['NX', 'EX' => $expire]);
+    }
+    public static function unlock($key, $value)
+    {
+        $script = <<< EOF
+        if redis.call("get", KEYS[1]) == ARGV[1] then
+            return redis.call("del", KEYS[1])
+        else
+            return 0
+        end
+        EOF;
+        return self::connect()->eval($script, [$key, $value], 1);    
+    }
+    public static function incr($key, $value = false)
+    {
+        if ($value) {
+            return self::connect()->incrby($key, $value);
+        }
+        return self::connect()->incr($key);
+    }
+    public static function decr($key, $value = false)
+    {
+        if ($value) {
+            return self::connect()->decrby($key, $value);
+        }
+        return self::connect()->decr($key);
+    }
+    public static function push($key, $value)
+    {
+        return self::connect()->lpush($key, $value);
+    }
+    public static function pop($key)
+    {
+        $data = self::connect()->brPop($key, 10);
+        if ($data) {
+            if (isset($data[1])) {
+                $data = $data[1];
+            }
+            return $data;
+        } else {
+            $pong = self::connect()->ping();
+            if ($pong != '+PONG') {
+                throw new \Exception('Redis ping failure!', 500);
+            }
+            usleep(100000);
+        }
+        return false;
+    }
+    public static function len($key)
+    {
+        return self::connect()->llen($key);
+    }
+    public static function hGet($key, $hkey = false)
+    {
+        if ($hkey) {
+            return Debug::add(self::connect()->hGet($key, $hkey), 'cache');
+        } else {
+            return Debug::add(self::connect()->hGetAll($key), 'cache');
+        }
+    }
+    public static function hDel($key, $hkey)
+    {
+        return self::connect()->hDel($key, $hkey);
+    }
+    public static function hExists($key, $hkey)
+    {
+        return self::connect()->hExists($key, $hkey);
+    }
+    public static function hKeys($key)
+    {
+        return self::connect()->hKeys($key);
+    }
+    public static function hSet($key, $hkey, $value, $expire = 0)
+    {
+        self::expire($expire);
+        return self::connect()->hKeys($key, $hkey, $value, self::$expire);
+    }
+    public static function delete($key)
+    {
+        return self::connect()->delete($key, 0);
+    }
+    public static function close()
+    {
+        return self::connect()->close();
+    }
+    private static function expire($expire)
+    {
+        if ($expire) {
+            self::$expire = $expire;
+        }
+    }
+}

+ 3 - 3
src/Dever/String/Regular.php → src/Dever/Helper/Rule.php

@@ -1,7 +1,7 @@
-<?php namespace Dever;
-class Regular
+<?php namespace Dever\Helper;
+class Rule
 {
-	public static function rule($method, $fix = '/', $rule = '')
+	public static function get($method, $fix = '/', $rule = '')
     {
         return $fix[0] . self::$method($rule) . $fix;
     }

+ 49 - 155
src/Dever/String/Helper.php → src/Dever/Helper/Str.php

@@ -1,20 +1,17 @@
-<?php namespace Dever\String;
-class Helper
+<?php namespace Dever\Helper;
+class String
 {
-    public static function encode($string, $key = "")
+    public static function encode($string, $key = '')
     {
-        return Encrypt::encode($string, $key);
+        return \Dever\Secure::encode($string, $key);
     }
-    public static function decode($string, $key = "")
+    public static function decode($string, $key = '')
     {
-        return Encrypt::decode($string, $key);
+        return \Dever\Secure::decode($string, $key);
     }
-    public static function timestamp()
+    public static function hide($string, $start = 3, $len = 4, $hide = '****')
     {
-        list($msec, $sec) = explode(' ', microtime());
-        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
-        $msec = substr($msectime, 0, 13);
-        return $msec;
+        return substr_replace($string, $hide, $start, $len);
     }
     public static function per($cash, $value)
     {
@@ -25,19 +22,24 @@ class Helper
         }
         return round($value, 2);
     }
-    public static function uuid()
+    public static function rand($len, $type = 4)
     {
-        mt_srand((double)microtime() * 10000);
-        $charid = strtoupper(self::id()); 
-        $hyphen = chr(45);        
-        $uuid   = chr(123)            
-                 .substr($charid, 0, 8).$hyphen               
-                 .substr($charid, 8, 4).$hyphen            
-                 .substr($charid,12, 4).$hyphen            
-                 .substr($charid,16, 4).$hyphen            
-                 .substr($charid,20,12)            
-                 .chr(125);
-        return $uuid;
+        $source = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
+        $config = array (
+            0 => array("min" => 0, "max" => 9), /// 全数字
+            1 => array("min" => 10, "max" => 35), /// 全小写
+            2 => array("min" => 36, "max" => 61), /// 全大写
+            3 => array("min" => 10, "max" => 61), /// 大小写
+            4 => array("min" => 0, "max" => 61), /// 数字+大小写
+        );
+        if (!isset($config[$type])) {
+            $type = 4;
+        }
+        $rand = "";
+        for ($i = 0; $i < $len; $i++) {
+            $rand .= $source[rand($config[$type]["min"], $config[$type]["max"])];
+        }
+        return $rand;
     }
     public static function order($prefix = '', $type = 1)
     {
@@ -56,10 +58,6 @@ class Helper
             }
         }
     }
-    public static function hide($string, $start = 3, $len = 4, $hide = '****')
-    {
-        return substr_replace($string, $hide, $start, $len);
-    }
     public static function code($num = 4)
     {
         $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
@@ -109,75 +107,11 @@ class Helper
             return $num;
         }
     }
-    public static function id()
-    {
-        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
-        return substr($charid, 0, 8) . substr($charid, 8, 4) . substr($charid, 12, 4) . substr($charid, 16, 4) . substr($charid, 20, 12);
-    }
-    public static function rand($len, $type = 4)
-    {
-        $source = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
-
-        $config = array (
-            0 => array("min" => 0, "max" => 9), /// 全数字
-            1 => array("min" => 10, "max" => 35), /// 全小写
-            2 => array("min" => 36, "max" => 61), /// 全大写
-            3 => array("min" => 10, "max" => 61), /// 大小写
-            4 => array("min" => 0, "max" => 61), /// 数字+大小写
-        );
-        if (!isset($config[$type])) {
-            $type = 4;
-        }
-
-        $rand = "";
-        for ($i = 0; $i < $len; $i++) {
-            $rand .= $source[rand($config[$type]["min"], $config[$type]["max"])];
-        }
-
-        return $rand;
-    }
-    public static function xss($data)
-    {
-        if (!is_string($data)) {
-            return $data;
-        }
-        $data = str_replace(array('&amp;', '&lt;', '&gt;'), array('&amp;amp;', '&amp;lt;', '&amp;gt;'), $data);
-        $data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
-        $data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
-        $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
-
-        // Remove any attribute starting with "on" or xmlns
-        $data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
-
-        // Remove javascript: and vbscript: protocols
-        $data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
-        $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
-        $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
-
-        // Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
-        $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
-        $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
-        $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
-
-        // Remove namespaced elements (we do not need them)
-        $data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);
-
-        do {
-            // Remove really unwanted tags
-            $old_data = $data;
-            //$data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
-            $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
-        } while ($old_data !== $data);
-
-        // we are done...
-        return $data;
-    }
     public static function idtostr($id)
     {
         if (!is_numeric($id) || $id < 0) {
             return false;
         }
-
         $id = substr("00000000" . $id, -8);
         $sandNum = $id % 10;
         srand($id);
@@ -219,7 +153,6 @@ class Helper
                 $retstr2 .= $str[3+$i*2];
             }
         }
-
         $retstr1 = "g".substr("00000000".hexdec($retstr1),-8);
         $retstr2 = "g".substr("00000000".hexdec($retstr2),-8);
         $ret1 = $ret2 = "";
@@ -273,45 +206,14 @@ class Helper
         }
         return $result;
     }
-    public static function strlen($string)
+    public static function length($string)
     {
         preg_match_all("/./us", $string, $match);
         return count($match[0]);
     }
-    public static function str_explode($value, $num = 2)
-    {
-        $len = mb_strlen($value);
-        $result = array();
-        for ($i = 0; $i < $len; $i = $i + $num) {
-            $result[$i / $num] = mb_substr($value, $i, $num);
-        }
-        return $result;
-    }
-    public static function replace($replace, $value, $content)
-    {
-        if (!$replace) {
-            return $value;
-        }
-        $content = str_replace($replace, $value, $content);
-        return $content;
-    }
-    public static function replace_array($replace, $value, $key = 'col')
-    {
-        $result = array();
-        foreach ($replace as $k => $v) {
-            if (isset($value[$k])) {
-                $v = $value[$k];
-                $k = $value[$k][$key];
-            }
-            if ($v) {
-                $result[$k] = $v;
-            }
-        }
-        return $result;
-    }
     public static function addstr($str, $index, $sub)
     {
-        $str = self::str_explode($str, 1);
+        $str = self::explode($str, 1);
         $length = count($str);
         $num = floor($length / $index);
         for ($a = 1; $a <= $num; $a++) {
@@ -325,6 +227,15 @@ class Helper
         }
         return implode('', $str);
     }
+    public static function explode($value, $num = 2)
+    {
+        $len = mb_strlen($value);
+        $result = array();
+        for ($i = 0; $i < $len; $i = $i + $num) {
+            $result[$i / $num] = mb_substr($value, $i, $num);
+        }
+        return $result;
+    }
     public static function ishtml($html)
     {
         if($html != strip_tags($html)) {
@@ -333,47 +244,30 @@ class Helper
             return false;
         }
     }
-    public static function filter($content)
-    {
-        if (strpos($content, 'font-family') !== false) {
-            $content = preg_replace('/font-family:([\s\S]*?);/i', '', $content);
-            $content = preg_replace('/"="([\s\S]*?)">/i', '">', $content);
-        }
-        return $content;
-    }
-    public static function pic_base64_encode($img_file, $type = 1)
+    public static function encodePic($file, $type = 1)
     {
-        $img_base64 = '';
-        if (file_exists($img_file)) {
-            $app_img_file = $img_file; // 图片路径
-            $img_info = getimagesize($app_img_file); // 取得图片的大小,类型等
-
-            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
-            $fp = fopen($app_img_file, "r"); // 图片是否可读权限
-
+        $base64 = '';
+        if (is_file($file)) {
+            $info = getimagesize($file);
+            $fp = fopen($file, "r");
             if ($fp) {
-                $filesize = filesize($app_img_file);
-                $content = fread($fp, $filesize);
-                $file_content = chunk_split(base64_encode($content)); // base64编码
-                switch ($img_info[2]) {           //判读图片类型
-                    case 1: $img_type = "gif";
+                $content = chunk_split(base64_encode(fread($fp, filesize($file))));
+                switch ($info[2]) {
+                    case 1: $img_type = 'gif';
                         break;
-                    case 2: $img_type = "jpg";
+                    case 2: $img_type = 'jpg';
                         break;
-                    case 3: $img_type = "png";
+                    case 3: $img_type = 'png';
                         break;
                 }
-
                 if ($type == 1) {
-                    $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
+                    $base64 = 'data:image/' . $img_type . ';base64,' . $content;
                 } else {
-                    $img_base64 = $file_content;//合成图片的base64编码
+                    $base64 = $content;
                 }
-
             }
             fclose($fp);
         }
-
-        return $img_base64;
+        return $base64;
     }
 }

+ 0 - 1
src/Dever/Import.php

@@ -34,7 +34,6 @@ class Import
             }
             if ($this->path == 'api') {
                 $this->param = Route::input();
-                $secure = $this->method . '_secure';
                 if (method_exists($this->class, $this->method . '_secure')) {
                     $key = false;
                     $token = $this->method . '_token';

+ 43 - 73
src/Dever/Log.php

@@ -2,83 +2,60 @@
 use Dever;
 class Log
 {
-    public static function add($msg, $type = 1)
+    public static function add($log, $type = 1)
     {
-        if (!Config::get('setting')['log']) {
+        if (!$config = Config::get('setting')['log']) {
             return;
         }
-        $log = 'dever';
-        if (is_array($msg)) {
-            foreach ($msg as $k => $v) {
-                if (is_array($v)) {
-                    foreach ($v as $k1 => $v1) {
-                        $log .= "&".$k . "_" . $k1 ."=" . self::filter($v1);
-                    }
-                } else {
-                    $log .= "&".$k."=" . self::filter($v);
-                }
-            }
-        } else {
-            $log = $msg;
-        }
-
-        return self::push($log, $type);
+        $config['level'] = $type;
+        return self::push(self::filter($log), $config);
     }
-    private static function push($log, $type = 1)
+    private static function push($log, $config)
     {
-        if (is_array(Config::get('setting')['log'])) {
-            $method = Config::get('setting')['log']['type'];
-        } else {
-            $method = 'syslog';
-        }
-        $method = 'push_' . $method;
-        return self::$method($log, $type);
+        $method = 'push_' . $config['type'];
+        return self::$method($log, $config);
     }
-    private static function push_http($log, $type)
+    private static function push_http($log, $config)
     {
         return false;
     }
-    private static function push_udp($log, $type)
+    private static function push_udp($log, $config)
     {
-        $class = '\\Dever\\Server\\Udp';
-        $class = new $class;
-        $class->client(Config::get('setting')['log']['host'], Config::get('setting')['log']['port']);
-        return $class->push($log);
+        $handle = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
+        if ($handle) {
+            socket_sendto($handle, $log, strlen($log), 0, $config['host'], $config['port']);
+            socket_close($handle);
+        }
     }
-    private static function push_syslog($log, $type)
+    private static function push_syslog($log, $config)
     {
-        if ($type == 1) {
-            $type = LOG_DEBUG;
+        if ($config['level'] == 1) {
+            $level = LOG_DEBUG;
             $name = LOG_LOCAL1;
-        } elseif ($type == 2) {
-            $type = LOG_NOTICE;
+        } elseif ($config['level'] == 2) {
+            $level = LOG_NOTICE;
             $name = LOG_LOCAL2;
-        } elseif ($type == 3) {
-            $type = LOG_INFO;
+        } elseif ($config['level'] == 3) {
+            $level = LOG_INFO;
             $name = LOG_LOCAL3;
         } else {
-            $type = LOG_INFO;
+            $level = LOG_INFO;
             $name = LOG_LOCAL4;
         }
         openlog(DEVER_APP_NAME, LOG_PID, $name);
-        $state = syslog($type, $log);
+        syslog($level, $log);
         closelog();
-        return $state;
     }
-    private static function push_file($log, $type)
+    private static function push_file($log, $config)
     {
-        $now = Dever::udate('Y-m-d'.'\T'.'H:i:s.u+08:00');
-        $project = DEVER_PROJECT;
-        $app = DEVER_APP_NAME;
-        $log = $now . ' ' . $project . ' ' . $app . ' ' . $log . "\r\n";
-        $file = self::getFileName($type);
-        $file = Path::get($file[0], $file[1] . $file[2]);
-        $size = 5242880;//默认5M
-        if (isset(Config::get('setting')['log']['size'])) {
-            $size = Config::get('setting')['log']['size'];
+        $log = date('Y-m-d H:i:s') . ' ' . DEVER_PROJECT . ' ' . DEVER_APP_NAME . ' ' . $log . "\r\n";
+        $file = self::getFile($config['level']);
+        $size = 5242880;
+        if (isset($config['size'])) {
+            $size = $config['size'];
         }
         $exists = false;
-        if (file_exists($file)) {
+        if (is_file($file)) {
             $exists = true;
         }
         if ($exists && $size <= filesize($file)) {
@@ -116,9 +93,9 @@ class Log
     }
     private static function get_file($day, $type)
     {
-        $file = self::getFileName($type, $day);
+        $file = self::file($type, $day);
         $content = '';
-        $path = $file[0] . $file[1];
+        $path = dirname($file);
         if (is_dir($path)) {
             $dir = scandir($path);
             foreach ($dir as $k => $v) {
@@ -137,35 +114,28 @@ class Log
         if (is_array($string)) {
             $string = json_encode($string);
         }
-        return str_replace(array("\t","\n","\r"),array(",",",",","),$string);
+        return $string;
     }
-    private static function getFileName($type, $file = '')
+    private static function file($level, $file = '')
     {
         if (!$file) {
             $file = date('Y_m_d_H');
         }
-        if (strstr($file, '-')) {
+        if (strpos($file, '-')) {
             $file = str_replace('-', '_', $file);
         }
-        $root = Path::day('logs', $file);
-
-        if ($type == 1) {
+        $date = explode('_', $file);
+        $path = Path::get('logs' . DIRECTORY_SEPARATOR . $date[0] . DIRECTORY_SEPARATOR . $date[1] . DIRECTORY_SEPARATOR . $date[2] . DIRECTORY_SEPARATOR);
+        $root = \Dever\Helper\Path::day('logs', $file);
+        if ($level == 1) {
             $prefix = 'debug';
-        } elseif ($type == 2) {
+        } elseif ($level == 2) {
             $prefix = 'notice';
-        } elseif ($type == 3) {
+        } elseif ($level == 3) {
             $prefix = 'info';
         } else {
-            $prefix = $type;
-        }
-
-        if (strstr($type, '/')) {
-            $path = rtrim($prefix, '/') . '/';
-            $file = $file . '.log';
-        } else {
-            $path = '';
-            $file = $prefix . '_' . $file . '.log';
+            $prefix = $level;
         }
-        return array($root, $path, $file);
+        return $path . $prefix . '_' . $file . '.log';
     }
 }

+ 17 - 5
src/Dever/Model.php

@@ -100,12 +100,15 @@ class Model
             }
         }
     }
-    public function select($param, $set = array())
+    public function select($param, $set = array(), $lock = false)
     {
         if (isset($set['num'])) {
             $set['limit'] = Paginator::init($set['num'], $set['page'] ?? 1, function()use($param){return $this->count($param);});
         }
-        $result = $this->store->select($this->config['table'], $param, $set, $this->config['struct']);
+        if ($lock && isset($this->config['type']) && $this->config['type'] == 'myisam') {
+            $lock = false;
+        }
+        $result = $this->store->select($this->config['table'], $param, $set, $this->config['struct'], $lock);
         if (isset($set['num']) && empty($set['page'])) {
             $result = $result->fetchAll();
             Paginator::status(empty($result));
@@ -116,9 +119,9 @@ class Model
     {
         return $this->store->count($this->config['table'], $param, $this->config['struct']);
     }
-    public function find($param, $set = array())
+    public function find($param, $set = array(), $lock = false)
     {
-        return $this->select($param, $set)->fetch();
+        return $this->select($param, $set, $lock)->fetch();
     }
     public function insert($data)
     {
@@ -127,8 +130,17 @@ class Model
         }
         return $this->store->insert($this->config['table'], $data, $this->config['struct']);
     }
-    public function update($param, $data)
+    public function update($param, $data, $lock = false)
     {
+        if ($lock && isset($this->config['struct']['lock'])) {
+            $info = $this->find($param, array('col' => 'id,lock'));
+            if ($info) {
+                $param['lock'] = $info['lock'];
+                $data['lock'] = array('+', 1);
+            } else {
+                return false;
+            }
+        }
         return $this->store->update($this->config['table'], $param, $data, $this->config['struct']);
     }
     public function delete($param)

+ 9 - 8
src/Dever/Output.php

@@ -21,18 +21,16 @@ class Output
             $result['page'] = $page;
         }
         if ($uuid) {
-            $result['uuid'] = Dever::string('uuid');
+            $result['uuid'] = Dever::uuid();
         }
-        return self::handle($result);
+        self::handle($result);
+        return $data;
     }
-    public static function error($msg, $param = array(), $code = 1)
+    public static function error($msg, $code = 1)
     {
         $result = array();
         $result['status'] = 2;
         $result['code'] = $code;
-        if (is_string($msg)) {
-            $msg = Lang::get($msg, $param);
-        }
         $result['msg'] = $msg;
         self::handle($result);
         die;
@@ -43,17 +41,20 @@ class Output
     }
     public static function format($data)
     {
+        if (is_array($data)) {
+            $data = htmlspecialchars(json_encode($data, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE));
+        }
         $content = "<pre>\n";
-        $content .= htmlspecialchars(print_r($data, true));
+        $content .= $data;
         $content .= "\n</pre>\n";
         return $content;
     }
     public static function handle(&$result)
     {
+        Debug::out($result);
         self::json($result);
         self::callback($result);
         self::func($result);
-        Debug::out($result);
         if (self::$format == 'json') {
             print_r($result);
         } else {

+ 0 - 164
src/Dever/Pagination/Html.php

@@ -1,164 +0,0 @@
-<?php namespace Dever\Pagination;
-/*
-# 定义父节点的类型、属性等(整个page的节点)
-$html->parent = array('div', 'class="half-bg-bottom page margin-bottom-30"');
-# 定义子节点的类型、属性等(每个page的节点)
-$html->child = array();
-# 定义上一页的名称、样式
-$html->prev = array('&lt;', 'pre');
-# 定义下一页的名称、样式
-$html->next = array('&gt;', 'next');
-# 定义每个页数的样式,当前页的样式 样式写在哪 是否和旧样式共用
-$html->page = array('page', 'current', 'current', true);
-# 定义开始页
-$html->start = false;
-# 定义结束页
-$html->end = false;
-# 定义跳转页
-$html->jump = false;
-# 定义扩展信息
-$html->ext = '';
-# 生成
-$html->create();
- */
-class Html
-{
-    public $parent;
-    public $child;
-    public $prev = array('prev', 'prev');
-    public $next = array('next', 'next');
-    public $page = array('page', 'current', '', false);
-    public $start = false;
-    public $end = false;
-    public $jump = false;
-    public $ext = '';
-    public $html = '';
-    private $paginator;
-    public function __construct(Paginator $paginator)
-    {
-        $this->paginator = $paginator;
-        $this->html = '';
-    }
-    public function get()
-    {
-        return $this->html;
-    }
-    public function create()
-    {
-        $html = '';
-        if (empty($current[2])) {
-            $current[2] = '';
-        }
-        $this->start()
-            ->prev()
-            ->page()
-            ->next()
-            ->end()
-            ->jump();
-        $this->html = $this->tag($this->parent, $this->html);
-    }
-    private function start()
-    {
-        if ($this->start && $this->paginator->current > 1) {
-            $this->html .= $this->set($this->start[1], 1, $this->start[0], $this->page[2]);
-        }
-        return $this;
-    }
-    private function prev()
-    {
-        if ($this->prev) {
-            $this->html .= $this->set($this->prev[1], $this->paginator->prev, $this->prev[0], $this->page[2]);
-        } elseif (isset($prev[2])) {
-            $this->html .= $this->set($this->prev[1], $this->paginator->current, $this->prev[0], $this->page[2]);
-        }
-        return $this;
-    }
-    private function page()
-    {
-        if ($this->page[1]) {
-            $i = $this->paginator->start;
-
-            for ($i; $i <= $this->paginator->end; $i++) {
-                $this->html .= $this->set($this->getPageClass($i), $i, $i, $this->page[2]);
-            }
-        }
-        return $this;
-    }
-    private function getPageClass($index)
-    {
-        $class = $this->page[0];
-        if ($index == $this->paginator->current) {
-            if (isset($this->page[3]) && $this->page[3] == true) {
-                $class = $this->page[1];
-            } else {
-                if ($class) {
-                    $class .= ' ';
-                }
-
-                $class .= $this->page[1];
-            }
-        }
-
-        return $class;
-    }
-    private function end()
-    {
-        if ($this->end && $this->paginator->current < $this->paginator->page) {
-            $this->html .= $this->set($this->end[1], $this->paginator->page, $this->end[0], $this->page[2]);
-        }
-        return $this;
-    }
-    private function next()
-    {
-        if ($this->next) {
-            $this->html .= $this->set($this->next[1], $this->paginator->next, $this->next[0], $this->page[2]);
-        } elseif (isset($next[2])) {
-            $this->html .= $this->set($this->next[1], $this->paginator->end, $this->next[0], $this->page[2]);
-        }
-        return $this;
-    }
-    private function jump()
-    {
-        if ($this->jump) {
-            $click = 'onclick="var link=\'' . $this->paginator->href('{1}') . '\';location.href=link.replace(\'{1}\', document.getElementById(\'dever_page\').value)"';
-            $this->html .= str_replace('{click}', $click, $this->jump);
-        }
-        return $this;
-    }
-    public function set($class, $num, $name, $type = '')
-    {
-        if ($type == 'parent') {
-            $this->child[1] = 'class="' . $class . '"';
-            $class = '';
-        }
-        return $this->tag($this->child, $this->getContent($class, $num, $name));
-    }
-    private function getContent($class, $num, $name)
-    {
-        if ($this->child && $this->child[0] == 'a') {
-            $this->child[1] = $this->attr($class, $this->paginator->href($num));
-            $content = $name;
-        } else {
-            $content = $this->tag(array('a', $this->attr($class, $this->paginator->href($num))), $name);
-        }
-
-        return $content;
-    }
-    public function tag($tag, $content)
-    {
-        if (!$tag) {
-            return $content;
-        }
-        $attr = '';
-        if (is_array($tag)) {
-            $temp = $tag;unset($tag);
-            $tag = $temp[0];
-            $attr = $temp[1];
-        }
-        return '<' . $tag . ' ' . $attr . '>' . $content . '</' . $tag . '>';
-    }
-    public function attr($class, $href)
-    {
-        return ' class="' . $class . '" href="' . $href . '" ';
-    }
-}

+ 0 - 303
src/Dever/Pagination/Paginator.php

@@ -1,303 +0,0 @@
-<?php namespace Dever\Pagination;
-use Dever\Url;
-use Dever\Input;
-use Dever\Route;
-class Paginator
-{
-    const PAGE = 'page/';
-    public $total;
-    public $html = '';
-    public $start;
-    public $end;
-    public $num;
-    public $first_num = 0;
-    public $maxpage = 10;
-    public $page;
-    public $prev;
-    public $next;
-    public $current;
-    public $template;
-    public $link;
-    public $array;
-    protected static $instance;
-    public static function getInstance($key = 'current')
-    {
-        if (empty(self::$instance[$key])) {
-            self::$instance[$key] = new self();
-        }
-        return self::$instance[$key];
-    }
-    public static function getPage($key = 'current', $total = false, $template = '')
-    {
-        if (is_numeric($total) && $total > 0) {
-            self::getInstance($key)->total($total);
-            self::getInstance($key)->offset(1);
-            self::getInstance($key)->template($key);
-            self::getInstance($key)->link();
-        }
-        $result = self::getInstance($key)->handle($template);
-        if ($total == 'NEXT') {
-            if (self::getInstance($key)->next) {
-                $result = self::getInstance($key)->href(self::getInstance($key)->next);
-            } else {
-                $result = '';
-            }
-        }
-        return $result;
-    }
-    public static function getTotal($key = 'current')
-    {
-        return self::getInstance($key)->total();
-    }
-    public static function getHtml($key = 'current', $template = '')
-    {
-        return self::getPage($key, false, $template);
-    }
-    public function toArray()
-    {
-        if (empty($this->array)) {
-            $total = $this->total();
-            if ($total > 0) {
-                $current = $this->current();
-                $this->setArray($total, $current);
-            }
-        }
-        return $this->array;
-    }
-    private function setArray($total, $current)
-    {
-        $totalPage = $this->getAllPage();
-        $status = 1;
-        if ($current >= $totalPage) {
-            $status = 0;
-        }
-        $next = $this->next();
-        $link = '';
-        if ($status == 1) {
-            $link = $this->href($next);
-        }
-        $this->array = array
-        (
-            'total' => intval($total),
-            'current_page' => intval($current),
-            'total_page' => $totalPage,
-            'next_page' => $next,
-            'prev_page' => $this->prev(),
-            'html' => $this->handle(),
-            'status' => $status,
-            'link' => $link,
-        );
-    }
-    public function current($name = 'pg')
-    {
-        $this->current = Input::get($name, 1);
-        if ($this->total && $this->current > $this->total) {
-            $this->current = $this->total;
-        }
-
-        return $this->current;
-    }
-    public function setMaxPage($maxpage = 10)
-    {
-        $this->maxpage = $maxpage;
-    }
-    public function getAllPage()
-    {
-        if (!$this->total) {
-            return 0;
-        }
-        if ($this->first_num > 0) {
-            $this->page = ceil(($this->total - $this->first_num) / $this->num) + 1;
-        } else {
-            $this->page = ceil($this->total / $this->num);
-        }
-        return $this->page;
-    }
-    public function offset($num, $first_num = 0)
-    {
-        $this->num = $num;
-        $current = $this->current();
-        if ($first_num > 0) {
-            $this->first_num = $first_num;
-            if ($current == 1) {
-                $this->num = $first_num;
-                $first_num = 0;
-            } else {
-                $current = $current - 1;
-            }
-        }
-        $offset = $first_num + $this->num * ($current-1);
-        
-        return $offset;
-    }
-    public function total($total = false)
-    {
-        if (!$total) {
-            return $this->total ? $this->total : 0;
-        }
-        $this->total = $total;
-    }
-    public function maxpage($maxpage)
-    {
-        $this->maxpage = $maxpage;
-    }
-    public function link($link = '')
-    {
-        if (!$link) {
-            $link = Uri::$url;
-        }
-        $this->linkReplaceStr($link, 'pg');
-        $this->linkReplaceStr($link, 'pt');
-        $this->linkSearch($link);
-        return $this->link = $link;
-    }
-    private function linkSearch(&$link)
-    {
-        $search = Input::prefix('search_');
-        if ($search) {
-            foreach ($search as $k => $v) {
-                if (is_array($v)) {
-                    $v = implode(',', $v);
-                }
-                if ($v && strpos($link, $k) === false) {
-                    $link .= '&' . $k . '=' . $v;
-                }
-            }
-        }
-    }
-    private function linkReplaceStr(&$link, $string)
-    {
-        if (strpos($link, $string . '=') !== false) {
-            $link = preg_replace('/[?|&]' . $string . '=(\d+)/i', '', $link);
-        }
-    }
-    public function template($template)
-    {
-        $this->template = $template;
-    }
-    public function data($content, $total = 0)
-    {
-        $this->total = $total;
-        if ($content) {
-            if ($this->total <= 0) {
-                $this->total = count($content);
-            }
-            $this->current();
-            $data = isset($content[$this->current - 1]) ? $content[$this->current - 1] : array();
-            return $data;
-        }
-        return array();
-    }
-    public function sqlCount($sql, $offset, $total = 0, $db, $data)
-    {
-        $this->total = $total;
-        if ($this->total <= 0) {
-            $this->sqlCountQuery($sql, $db, $data);
-        }
-        $data_sql = $sql . ' LIMIT ' . $offset . ', ' . $this->num;
-        $result = $db->query($data_sql, $data)->fetchAll();
-        return $result;
-    }
-    private function sqlCountQuery($sql, $db, $data)
-    {
-        $sql = mb_strtolower($sql);
-        if (strstr($sql, ' from ')) {
-            $temp = explode(' from ', $sql);
-        }
-        if (isset($temp[1])) {
-            if (strstr($temp[1], ' order ')) {
-                $temp = explode(' order ', $temp[1]);
-                $sql = $temp[0];
-            } else {
-                $sql = $temp[1];
-            }
-            if (strstr($sql, 'group')) {
-                $sql = 'SELECT count(1) as num FROM (SELECT count(1) FROM '.$sql.' ) a ';
-            } else {
-                $sql = 'SELECT count(1) as num FROM ' . $sql;
-            }
-            $this->total = $db->query($sql, $data)->fetchColumn();
-        }
-    }
-    public function handle($template = '')
-    {
-        if ($this->html) {
-            return $this->html;
-        }
-        if ($this->total < 1) {
-            return '';
-        }
-        $this->getAllPage();
-        if ($this->page < $this->current) {
-            $this->current = $this->page;
-        }
-        if ($this->page <= 0) {
-            return '';
-        }
-        if ($this->total > $this->num) {
-            if ($this->current > 1) {
-                $this->prev = $this->current - 1;
-            }
-            if ($this->current < $this->page) {
-                $this->next = $this->current + 1;
-            }
-            if ($this->page <= $this->maxpage) {
-                $this->start = 1;
-                $this->end = $this->page;
-            } else {
-                $page = intval($this->maxpage / 2);
-                if ($this->current < $page) {
-                    $this->start = 1;
-                } elseif ($this->current <= ($this->page - $this->maxpage)) {
-                    $this->start = $this->current - $page;
-                } elseif ($this->current > $this->page - $this->maxpage && $this->current <= $this->page - $page) {
-                    $this->start = $this->current - $page;
-                } elseif ($this->current > $this->page - $page) {
-                    $this->start = $this->page - $this->maxpage + 1;
-                }
-                $this->end = $this->start + $this->maxpage - 1;
-
-                if ($this->start < 1) {
-                    $this->end = $this->current + 1 - $this->start;
-                    $this->start = 1;
-                    if (($this->end - $this->start) < $this->maxpage) {
-                        $this->end = $this->maxpage;
-                    }
-                } elseif ($this->end > $this->page) {
-                    $this->start = $this->page - $this->maxpage + 1;
-                    $this->end = $this->page;
-                }
-            }
-        }
-        return $this->getTemplate($template);
-    }
-    public function getTemplate($template = '')
-    {
-        if ($this->html) {
-            return $this->html;
-        }
-        $template = $template ? $template : $this->template;
-        $file = DEVER_APP_PATH . self::PAGE . $template . '.php';
-        if (is_file($file)) {
-            $html = new Html($this);
-            $page = $this;
-            include $file;
-            return $this->html = $html->get();
-        }
-        return '';
-    }
-    public function next()
-    {
-        return $this->current < $this->page ? $this->current + 1 : $this->page;
-    }
-    public function prev()
-    {
-        return $this->current > 1 ? $this->current - 1 : 1;
-    }
-    public function href($page = false)
-    {
-        $page = $page ? $page : $this->current;
-        //return Url::get($this->link . '&pg=' . $page . '&pt=' . $this->total) . $this->ext;
-        return Url::get($this->link . '?pg=' . $page, DEVER_APP_NAME);
-    }
-}

+ 5 - 66
src/Dever/Path.php

@@ -1,76 +1,15 @@
 <?php namespace Dever;
 class Path
 {
-    public static function id($id, $path = '')
+    public static function get($path)
     {
-        $id = abs(intval($id));
-        $sid = sprintf("%09d", $id);
-        $dir1 = substr($sid, 0, 3);
-        $dir2 = substr($sid, 3, 2);
-        $dir3 = substr($sid, 5, 2);
-        if ($path) {
-            $path .= DIRECTORY_SEPARATOR;
+        $path = self::data() . DEVER_PROJECT . DIRECTORY_SEPARATOR . $path;
+        $dir = dirname($path);
+        if (!is_dir($dir)) {
+            mkdir($dir, 0777, true);
         }
-        $path = self::get($dir1 . DIRECTORY_SEPARATOR . $dir2 . DIRECTORY_SEPARATOR . $dir3 . DIRECTORY_SEPARATOR);
         return $path;
     }
-    public static function month($path, $time = false)
-    {
-        if (!$time) {
-            $time = time();
-        }
-        if (is_numeric($time)) {
-            $time = date('Y_m_d', $time);
-        }
-        $date = explode('_', $time);
-        $path = self::get($path . DIRECTORY_SEPARATOR . $date[0] . DIRECTORY_SEPARATOR . $date[1] . DIRECTORY_SEPARATOR);
-        return $path;
-    }
-    public static function day($path, $time = false)
-    {
-        if (!$time) {
-            $time = time();
-        }
-        if (is_numeric($time)) {
-            $time = date('Y_m_d', $time);
-        }
-        $date = explode('_', $time);
-        $path = self::get($path . DIRECTORY_SEPARATOR . $date[0] . DIRECTORY_SEPARATOR . $date[1] . DIRECTORY_SEPARATOR . $date[2] . DIRECTORY_SEPARATOR);
-        return $path;
-    }
-    public static function get($file, $path = '')
-    {
-        if (!$path) {
-            $path = self::data() . DEVER_PROJECT . DIRECTORY_SEPARATOR;
-        }
-        self::createPath($path);
-
-        if ($file && strpos($file, DIRECTORY_SEPARATOR) !== false) {
-            self::create($path, $file);
-        } else {
-            $path .= $file;
-        }
-
-        return $path;
-    }
-    private static function create(&$path, $file)
-    {
-        $array = explode(DIRECTORY_SEPARATOR, $file);
-        $count = count($array) - 2;
-        for ($i = 0; $i <= $count; $i++) {
-            $path .= $array[$i] . DIRECTORY_SEPARATOR;
-            self::createPath($path);
-        }
-        $path .= $array[$i];
-    }
-    private static function createPath($path)
-    {
-        if (!is_dir($path)) {
-            mkdir($path);
-            @chmod($path, 0755);
-            @system('chmod -R 777 ' . $path);
-        }
-    }
     public static function data()
     {
         if (isset(Config::get('setting')['data'])) {

+ 1 - 1
src/Dever/Project.php

@@ -45,6 +45,6 @@ class Project
         if (isset(self::$content[$app])) {
             return self::$content[$app];
         }
-        Output::error('app not exists', array($app));
+        Output::error('app not exists:' . $app);
     }
 }

+ 23 - 24
src/Dever/Route.php

@@ -1,5 +1,4 @@
 <?php namespace Dever;
-use Dever\Output;
 class Route
 {
     protected static $data = array();
@@ -53,34 +52,31 @@ class Route
         }
         $project = Project::load($project_name);
         if (!$project) {
-            Output::error('project not exists', array($project_name));
+            Output::error('project not exists:' . $project_name);
         }
         if (!$uri) {
             return $project['url'];
         }
-        if (Config::get('setting')['route']) {
-            $route = Config::get('route', $project_name);
-            if ($route) {
-                if ($search = array_search($uri, $route)) {
-                    $uri = $search;
+        if ($route = Config::get('setting')['route']) {
+            if ($search = array_search($uri, $route)) {
+                $uri = $search;
+            }
+            if ($param) {
+                $query = '';
+                $data = array();
+                $i = 1;
+                foreach ($param as $k => $v) {
+                    $query .= $k . '=$' . $i . '&';
+                    $data[$i] = $v;
+                    $i++;
                 }
-                if ($param) {
-                    $query = '';
-                    $data = array();
-                    $i = 1;
-                    foreach ($param as $k => $v) {
-                        $query .= $k . '=$' . $i . '&';
-                        $data[$i] = $v;
+                $query = rtrim($query, '&');
+                if ($key = array_search($uri . '?' . $query, $route)) {
+                    $i = 0;
+                    $uri = preg_replace_callback('/\(.*?\)/', function($param) use($data, &$i) {
                         $i++;
-                    }
-                    $query = rtrim($query, '&');
-                    if ($key = array_search($uri . '?' . $query, $route)) {
-                        $i = 0;
-                        $uri = preg_replace_callback('/\(.*?\)/', function($param) use($data, &$i) {
-                            $i++;
-                            return $data[$i];
-                        }, $key);
-                    }
+                        return $data[$i];
+                    }, $key);
                 }
             }
         } elseif ($param) {
@@ -95,6 +91,9 @@ class Route
         }
         self::match();
         self::filter();
+        if (isset(self::$data['uuid']) && isset(Config::get('setting')['redis']) && !\Dever\Helper\Redis::lock(self::$data['uuid'], 1, 10)) {
+            Output::error('route repeat');
+        }
         return self::$data;
     }
     protected static function command()
@@ -141,7 +140,7 @@ class Route
         if (!isset(self::$data['l'])) {
             Output::error('route not exists');
         }
-        if (Config::get('setting')['route'] && $route = Config::get('route')) {
+        if ($route = Config::get('setting')['route']) {
             $value = self::$data['l'];
             if (isset($route[$value])) {
                 self::$data['l'] = $route[$value];

+ 131 - 201
src/Dever/Secure.php

@@ -1,71 +1,29 @@
-<?php
-/**
- * This file is part of Dever.
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the MIT-LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @author    rabin<rabin@shemic.com>
- * @copyright rabin<rabin@shemic.com>
- * @link      http://www.dever.cc/
- * @license   http://www.opensource.org/licenses/mit-license.php MIT License
- */
-namespace Dever;
+<?php namespace Dever;
 use Dever;
-use Dever\String\Encrypt;
-use Dever\Data\Model;
-/**
- * Class Secure
- * @package Dever
- */
 class Secure
 {
-    /**
-     * @var int
-     */
     const TIME = 300;
-
-    /**
-     * @var string
-     */
-    const PATH =  'api/';
-
-    /**
-     * @var string
-     */
     private static $token = 'dever_api';
-
-    /**
-     * @var string
-     */
-    private static $log;
-
-    /**
-     * login
-     * @param  string $uid
-     * @return string
-     */
     public static function login($uid, $extend = false)
     {
         $auth = '';
-        $data = array($uid, time(), $extend);
-        if ($data) {
-            $auth = base64_encode(Encrypt::encode(implode("\t", $data), self::$token));
+        $data = Dever::json_encode(array($uid, time(), $extend));
+        return self::encode($data, self::$token);
+    }
+    public static function checkLogin($signature)
+    {
+        $auth = Dever::json_decode(self::decode($signature, self::$token));
+        if (isset($auth[0]) && isset($auth[1]) && $auth[0] && $auth[0] > 0) {
+            if (time() - $auth[1] < self::TIME) {
+                return array('uid' => $auth[0], 'time' => $auth[1], 'extend' => $auth[2]);
+            }
         }
-        return $auth;
+        return false;
     }
-
-    /**
-     * get
-     * @param array $request
-     * @param string $key
-     * @return array
-     */
     public static function get($request, $key = '')
     {
         if ($key) {
-            Config::get('setting')['token'] = $key;
+            self::$token = $key;
         }
         $time = self::timestamp();
         $nonce = self::nonce();
@@ -77,35 +35,28 @@ class Secure
         );
         return $request;
     }
-
-    /**
-     * check
-     * @param array $request
-     * @param array $param
-     * @param string $key
-     * @return string
-     */
     public static function check($request, $param = array(), $key = '')
     {
         if (empty($request['signature']) || empty($request['nonce'])) {
             Output::error('api signature not exists');
         }
-
+        if (isset($request['l'])) {
+            unset($request['l']);
+        }
+        if (isset($request['shell'])) {
+            unset($request['shell']);
+        }
         if ($key) {
-            Config::get('setting')['token'] = $key;
+            self::$token = $key;
         }
-
-        self::checkSignatureExits($request['signature']);
-
+        self::repeat($request['signature'], self::TIME);
         if (empty($request['time'])) {
             return self::checkLogin($request['signature']);
         }
         if (time() - $request['time'] > self::TIME) {
-            Output::error('api signature not exists');
+            Output::error('api signature has expired');
         }
-
         $signature_check = $request['signature'];
-
         if ($param && isset($param['request'])) {
             foreach ($param['request'] as $k => $v) {
                 if (isset($request[$k])) {
@@ -118,56 +69,12 @@ class Secure
             $temp['nonce'] = $request['nonce'];
             $request = $temp;
         }
-
         $signature = self::signature($request['time'], $request['nonce'], $request);
-
         if ($signature_check != $signature) {
-            Output::error('api signature not exists');
+            Output::error('invalid signature');
         }
-
         return $signature;
     }
-
-    /**
-     * checkLogin
-     * @param array $signature
-     * @param bool $state
-     * @param bool $max
-     * @return array
-     */
-    public static function checkLogin($signature, $state = true, $max = false)
-    {
-        if (is_numeric($signature)) {
-            return Dever::$data['user'] = array('uid' => $signature, 'time' => time());
-        }
-        $auth = $user = array();
-        if ($signature) {
-            $auth = explode("\t", Encrypt::decode(base64_decode($signature), self::$token));
-        }
-
-        if ((empty($auth) || count($auth) < 3)) {
-            $auth = array(0, false, false);
-        }
-        list($uid, $time, $extend) = $auth;
-        Dever::$data['user'] = array('uid' => $uid, 'time' => $time, 'extend' => $extend);
-
-        if (!empty($uid)) {
-            if ($max == false || ($max > 0 && (time() - $time) < $max)) {
-                return Dever::$data['user'];
-            }
-        }
-        if ($state) {
-            Output::error('api signature not exists');
-        }
-    }
-
-    /**
-     * signature
-     * @param string $time
-     * @param string $nonce
-     * @param array $request
-     * @return string
-     */
     public static function signature($time, $nonce, $request = array())
     {
         if (isset($request['signature'])) {
@@ -177,7 +84,6 @@ class Secure
         $request['time'] = $time;
         $request['nonce'] = $nonce;
         ksort($request);
-
         $signature_string = '';
         foreach ($request as $k => $v) {
             if (is_array($v)) {
@@ -185,112 +91,136 @@ class Secure
             }
             $signature_string .= $k . '=' . $v . '&';
         }
-        $signature_string = substr($signature_string, 0, -1);
+        $signature_string = rtrim($signature_string, '&');
         return md5($signature_string);
     }
-
-    /**
-     * token
-     * @return string
-     */
     public static function token()
     {
-        if (Config::get('setting')['token']) {
-            self::$token = Config::get('setting')['token'];
-        }
         return self::$token;
     }
-
-    /**
-     * nonce
-     * @return string
-     */
     public static function nonce()
     {
         return substr(sha1(microtime()), rand(10, 15));
     }
-
-    /**
-     * timestamp
-     * @return string
-     */
     public static function timestamp()
     {
-        list($msec, $sec) = explode(' ', microtime());
-        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
-        return $msectime;
+        return \Dever\Helper\Date::mtime();
     }
-
-    /**
-     * doc
-     * @param string $api
-     * @param array $request
-     * @param array $response
-     * @return mixed
-     */
-    static public function doc($api, $request, $response)
+    public static function repeat($value, $expire)
     {
-        if (strstr($api, 'manage')) {
-            return;
-        }
-        if (is_array($response) && isset($response[0])) {
-            $response = array_shift($response);
+        if (isset(Config::get('setting')['redis']) && !\Dever\Helper\Redis::lock($value, 1, $expire)) {
+            Output::error('api signature repeat');
         }
-        $data['api'] = $api;
-        $data['request'] = $request;
-        $data['response'] = $response;
-        Command::log('auth.api', $data);
     }
-
-    /**
-     * log
-     * @param string $api
-     * @param array $request
-     * @param array $response
-     * @return mixed
-     */
-    static public function log($api, $request, $response)
+    public static function encode($string, $key = "")
     {
-        $data['url'] = Url::get();
-        $data['api'] = $api;
-        $data['request'] = $request;
-        //$data['response'] = $response;
-        Log::add($msg, 3);
+        $ckey_length = 5;
+        if (!$key) {
+            $key = Config::get('base')->token;
+            if ($key) {
+                $key = sha1($key);
+            } else {
+                $key = sha1(self::$key);
+            }
+        }
+        $keya = md5(substr($key, 0, 16));
+        $keyb = md5(substr($key, 16, 16));
+        $keyc = ''; //md5串后4位,每次不一样
+        if ($ckey_length) {
+            $keyc = substr(md5(microtime()), -$ckey_length);
+        }
+        $cryptkey = $keya . md5($keya . $keyc); //两个md5串
+        $key_length = strlen($cryptkey); //64
+        $string = sprintf('%010d', time()) . substr(md5($string . $keyb), 0, 16) . $string;
+        $string_length = strlen($string);
+        $result = '';
+        $box = range(0, 255);
+        $rndkey = array();
+        for ($i = 0; $i <= 255; $i++) {
+            $rndkey[$i] = ord($cryptkey[$i % $key_length]); //生成一个255个元素的数组
+        }
+        for ($j = $i = 0; $i < 256; $i++) {
+            //将$box数组转换为无序并且个数不变的数据
+            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
+            $tmp = $box[$i];
+            $box[$i] = $box[$j];
+            $box[$j] = $tmp;
+        }
+        for ($a = $j = $i = 0; $i < $string_length; $i++) {
+            $a = ($a + 1) % 256;
+            $j = ($j + $box[$a]) % 256;
+            $tmp = $box[$a];
+            $box[$a] = $box[$j];
+            $box[$j] = $tmp;
+            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
+        }
+        return $keyc . str_replace('=', '', self::base64_encode($result));
     }
-
-    /**
-     * checkSignatureExits
-     * @param string $signature
-     * @return mixed
-     */
-    static public function checkSignatureExits($signature)
+    public static function decode($string, $key = "")
     {
-        $type = Config::get('setting')['signature'];
-        if (!$type) {
-            return;
-        }
-        $type = 'file';
-        if (Porject::load('manage') && $type == 'db') {
-            $where['signature'] = $signature;
-            $info = Model::load('manage/signature')->find($where);
-            if ($info) {
-                Output::error('api signature not repeat');
+        $ckey_length = 5;
+        if (!$key) {
+            $key = Config::get('base')->token;
+            if ($key) {
+                $key = sha1($key);
             } else {
-                Model::load('manage/signature')->insert($where);
+                $key = sha1(self::$key);
             }
+        }
+        $keya = md5(substr($key, 0, 16));
+        $keyb = md5(substr($key, 16, 16));
+        $keyc = '';//和encrypt时的$keyc一样
+        if ($ckey_length) {
+            $keyc = substr($string, 0, $ckey_length);
+        }
+        $cryptkey = $keya . md5($keya . $keyc);
+        $key_length = strlen($cryptkey);
+        $string = self::base64_decode(substr($string, $ckey_length));
+        $string_length = strlen($string);
+        $result = '';
+        $box = range(0, 255);
+        $rndkey = array();
+        for ($i = 0; $i <= 255; $i++) {
+            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
+        }
+        for ($j = $i = 0; $i < 256; $i++) {
+            //和encrypt时的$box一样
+            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
+            $tmp = $box[$i];
+            $box[$i] = $box[$j];
+            $box[$j] = $tmp;
+        }
+        for ($a = $j = $i = 0; $i < $string_length; $i++) {
+            //核心操作,解密
+            $a = ($a + 1) % 256;
+            $j = ($j + $box[$a]) % 256;
+            $tmp = $box[$a];
+            $box[$a] = $box[$j];
+            $box[$j] = $tmp;
+            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
+        }
+        if (substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
+            return substr($result, 26);
         } else {
-            $path = Path::month('signature');
-            $file = $path . 'signature_' . date('Y_m_d');
-            $config = array();
-            if (is_file($file)) {
-                $config = include($file);
-                if (isset($config[$signature])) {
-                    Output::error('api signature not repeat');
-                }
-            }
-            $config[$signature] = 1;
-            $content = '<?php return ' . var_export($config, true) . ';';
-            file_put_contents($file, $content);
+            return '';
+        }
+    }
+    public static function base64_encode($string)
+    {
+        if (!$string) {
+            return false;
+        }
+        $encodestr = base64_encode($string);
+        $encodestr = str_replace(array('+', '/'), array('-', '_'), $encodestr);
+        return $encodestr;
+    }
+    public static function base64_decode($string)
+    {
+        if (!$string) {
+            return false;
         }
+        $string = str_replace(array('-', '_'), array('+', '/'), $string);
+        $decodestr = base64_decode($string);
+        return $decodestr;
     }
 }

+ 0 - 5
src/Dever/Server.php

@@ -1,5 +0,0 @@
-<?php namespace Dever;
-class Server
-{
-    
-}

+ 0 - 64
src/Dever/Server/Rpc.php

@@ -1,64 +0,0 @@
-<?php namespace Dever\Server;
-use Dever\Import;
-use Dever\Output;
-class Rpc
-{
-	static $client = array();
-	static public function init()
-	{
-		self::server();
-		die;
-	}
-	static public function server()
-	{
-		$service = new \Yar_Server(new Rpc_Api());
-		$service->handle();
-	}
-	static public function client($link)
-	{
-		if (empty(self::$client[$link])) {
-			ini_set("yar.timeout",60000);
-			self::$client[$link] = new \Yar_Client($link);
-		}
-		
-		return self::$client[$link];
-	}
-	static public function api($link, $method, $param = array())
-	{
-		self::client($link);
-
-		$data = self::$client[$link]->api($method, $param);
-
-		if (isset($data['page']) && $data['page']) {
-			Output::page('current', $data['page']);
-			return $data['data'];
-		}
-
-		return $data;
-	}
-	static public function loop($link, $method, $param = array())
-	{
-		Yar_Concurrent_Client::call($link, $method, $param, "callback");
-		Yar_Concurrent_Client::call($link, $method, $param, "callback");
-		Yar_Concurrent_Client::call($link, $method, $param, "callback");
-		Yar_Concurrent_Client::loop(); //send
-
-		return $data;
-	}
-}
-class Rpc_Api
-{
-    public function api($method, $param = array())
-    {
-    	$data = Import::load($method, $param);
-    	$page = Output::page();
-    	if ($page) {
-    		return array('data' => $data, 'page' => $page);
-    	}
-        return $data;
-    }
-    protected function client_can_not_see()
-    {
-
-    }
-}

+ 0 - 298
src/Dever/Server/Swoole.php

@@ -1,298 +0,0 @@
-<?php namespace Dever\Server;
-use Dever\Path;
-use Dever\Import;
-use Dever\Output;
-use Dever\Route;
-use Dever\Config;
-use Dever\Debug;
-use Dever\Support\Command;
-use Swoole\Server as Server;
-use Swoole\Client as Client;
-class Swoole
-{
-    protected $log = '/var/log/dever/swoole_';
-    protected $client = array();
-    protected $callback;
-    protected $ip;
-    protected $port;
-    static protected $instance;
-    static public function getInstance($port = 30000, $ip = '0.0.0.0')
-    {
-        $key = $ip . ':' . $port;
-        if (empty(self::$instance[$key])) {
-            self::$instance[$key] = new self($port, $ip);
-        }
-
-        return self::$instance[$key];
-    }
-    public function __construct($port = 30000, $ip = '0.0.0.0')
-    {
-        $this->setPort($port);
-        $this->setIp($ip);
-    }
-    private function setIp($ip)
-    {
-        $this->ip = $ip;
-    }
-    private function setPort($port)
-    {
-        $this->port = $port;
-    }
-    private function path()
-    {
-        $path = DEVER_APP_PATH;
-
-        return Path::get($path . 'process/');
-    }
-    public function reload($config = false, $callback = array())
-    {
-        $content_server = '';
-        if ($config) {
-            $_SERVER['DEVER_SERVER'] = $config;
-            $content_server = "\$_SERVER['DEVER_SERVER'] = '".$config."';";
-        }
-        if ($this->ip && $this->port) {
-            $server = $this->port;
-            $entry = defined('DEVER_ENTRY') ? DEVER_ENTRY : 'index.php';
-            $content = "<?php
-            define('DEVER_DAEMON', true);".$content_server."
-            include(dirname(__FILE__) . DIRECTORY_SEPARATOR . '../".$entry."');
-            \$ip = '".$this->ip."';
-            \$port = '".$this->port."';
-            \$callback = ".var_export($callback, true).";
-            Dever::tcp(\$port, \$ip)->server(\$callback);";   
-            $file = $this->path() . $server . '.php';
-            file_put_contents($file, $content);
-            Command::kill($file);
-            return Command::run('php ' . $file, '');
-        }
-        return false;
-    }
-    public function daemon()
-    {
-        /*
-        $cron = 'count=`ps -fe |grep "tcp.start" | grep -v "grep" | grep "master" | wc -l`
-
-        echo $count
-        if [ $count -lt 1 ]; then
-        ps -eaf |grep "tcp.start" | grep -v "grep"| awk \'{print $2}\'|xargs kill -9
-        sleep 2
-        ulimit -c unlimited
-        php /data/webroot/server.php
-        echo "restart";
-        echo $(date +%Y-%m-%d_%H:%M:%S) >'.self::$log.'restart.log
-        fi';
-        */
-        $process = $this->path();
-        $path = scandir($process);
-        foreach ($path as $k => $v) {
-            if (strpos($v, '.php')) {
-                $v = $process . $v;
-                $state = Command::process($v);
-                if (!$state) {
-                    Command::run('php ' . $v);
-                }
-            }
-        }
-    }
-    public function server($callback = false)
-    {
-        $server = new Server($this->ip, $this->port, SWOOLE_BASE, SWOOLE_SOCK_TCP);
-        $config = array
-        (
-            'worker_num' => 8,
-            'daemonize' => true,
-            'max_request' => 0,
-            'dispatch_mode' => 2,
-            'log_file' => $this->log . 'run.log',
-
-            # 启用task
-            //'task_worker_num' => 1,
-            //'task_max_request' => 0,
-
-            # 确定数据完整性
-            //'open_length_check' => true,
-            //'open_eof_check' => true,
-            //'open_eof_split' => true,
-            //'package_eof' => '"eof":1}',
-            
-            # 确定心跳,确定死链接 ,每30秒检测一次心跳,如果60秒内没有数据发送,则切断链接
-            //'open_tcp_keepalive' => true,
-            //'heartbeat_check_interval' => 30,
-            //'heartbeat_idle_time' => 60,
-
-            # debug开启
-            //'debug_mode'=> 1
-        );
-        if (Config::get('host')->apiServer) {
-            $config = array_merge($config, Config::get('host')->apiServer);
-        }
-
-        $this->callback = $callback;
-        if ($this->callback) {
-            $this->callback['ip'] = $this->ip;
-            $this->callback['port'] = $this->port;
-        }
-
-        $server->set($config);
-
-        $server->on('start', array($this, 'server_start'));
-        $server->on('connect', array($this, 'server_connect'));
-        $server->on('receive', array($this, 'server_receive'));
-        $server->on('close', array($this, 'server_close'));
-        //$server->on('task', array($this, 'server_task'));
-        //$server->on('finish', array($this, 'server_finish'));
-        $server->on('shutdown', array($this, 'server_shutdown'));
-
-        $server->start();
-    }
-    public function server_start($server)
-    {
-        //echo "Service:Start...";
-        if (isset($this->callback['start'])) {
-            Import::load($this->callback['start'], array($server, $this->callback));
-        }
-    }
-    public function server_shutdown($server)
-    {
-        if (isset($this->callback['shutdown'])) {
-            Import::load($this->callback['shutdown'], array($server, $this->callback));
-        }
-        //echo "Service:Shutdown...";
-    }
-    public function server_connect($server, $fd)
-    {
-        if (isset($this->callback['connect'])) {
-            Import::load($this->callback['connect'], array($server, $fd, $this->callback));
-        }
-        //echo "Client:Connect.\n";
-    }
-    public function server_receive($server, $fd, $from_id, $data)
-    {
-        $data = json_decode($data, true);
-        # 直接转发给客户端
-        if ($data['method'] == 'send' && isset($data['param']['tcp_id']) && isset($data['param']['send'])) {
-            if (is_array($data['param']['send'])) {
-                $data['param']['send']['tcp_id'] = $data['param']['tcp_id'];
-                $data['param']['send'] = json_encode($data['param']['send']);
-            }
-            $server->send($data['param']['tcp_id'], $data['param']['send']);
-            unset($data['param']['tcp_id']);
-        } else {
-            if (isset($this->callback['receive'])) {
-                $state = Import::load($this->callback['receive'], array($server, $fd, $data, $this->callback));
-
-                if (!$state) {
-                    $server->close($fd);
-                    return;
-                }
-            }
-            if (isset($data['param']['token'])) {
-                $data['param']['tcp_id'] = $fd;
-            }
-
-            if (isset(Config::get('host')->apiServer['backend'])) {
-                list($project, $interface) = explode('/', $data['method']);
-                $send = Command::daemon($interface . '?' . http_build_query($data['param']), $project, 'index.php');
-
-                $send = $send[0];
-            } else {
-                Input::set('pg', 0);
-                Input::set('pt', 0);
-            	$send = Import::load($data['method'], $data['param']);
-                if (is_array($send)) {
-                    $page = Export::page('current', false, false);
-                    if ($page) {
-                        $send = array('data' => $send, 'page' => $page);
-                    }
-                    //$send['eof'] = 1;
-                    $send = json_encode($send);
-                }
-            }
-
-            $server->send($fd, $send);
-        }
-        if (isset(Config::get('host')->apiServer['pconnect'])) {
-            $data['param']['tcp_id'] = 1;
-        }
-        if (empty($data['param']['tcp_id'])) {
-            $server->close($fd);
-        }
-    }
-    public function server_close($server, $fd)
-    {
-        if (isset($this->callback['close'])) {
-            Import::load($this->callback['close'], array($server, $fd, $this->callback));
-        }
-        //echo "Client: Close.\n";
-    }
-    private function client($time = 0, $callback = false)
-    {
-    	$time = $time > 0 ? $time : 500;
-        if (!$callback) {
-            $client = new Client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
-            $state = $client->connect($this->ip, $this->port, $time);
-            if (!$state) {
-                return false;
-            }
-        } else {
-        	$this->callback = $callback;
-            if ($this->callback) {
-                $this->callback['ip'] = $this->ip;
-                $this->callback['port'] = $this->port;
-            }
-            $client = new Client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
-            $client->on('connect', array($this, 'client_connect'));
-            $client->on('receive', array($this, 'client_receive'));
-            $client->on('error', array($this, 'client_error'));
-            $client->on('close', array($this, 'client_close'));
-            $client->connect($this->ip, $this->port, $time);
-        }
-
-        return $client;
-    }
-    public function client_connect($client)
-    {
-        if (isset($this->callback['connect'])) {
-            Import::load($this->callback['connect'], array($client, $this->callback));
-        }
-    }
-    public function client_receive($client, $data)
-    {
-        if (isset($this->callback['receive'])) {
-            return Import::load($this->callback['receive'], array($client, $data, $this->callback));
-        }
-        return false;
-    }
-    public function client_error($client)
-    {
-        if (isset($this->callback['error'])) {
-            Import::load($this->callback['error'], array($client, $this->callback));
-        }
-    }
-    public function client_close($client)
-    {
-        if (isset($this->callback['close'])) {
-            Import::load($this->callback['close'], array($client, $this->callback));
-        }
-    }
-    public function api($method, $param = array(), $time = 0, $size = 65535, $flag = true)
-    {
-        $client = $this->client($time);
-        if (!$client) {
-            return false;
-        }
-        $send = array('method' => $method, 'param' => $param);
-        $client->send(json_encode($send));
-        $data = $client->recv($size, $flag);
-        if ($data && is_string($data) && strpos('{', $data) !== false) {
-            $data = json_decode($data, true);
-        }
-        $client->close();
-        if (isset($data['page']) && $data['page']) {
-            Export::page('current', $data['page']);
-            return $data['data'];
-        }
-        return $data;
-    }
-}

+ 0 - 79
src/Dever/Server/Udp.php

@@ -1,79 +0,0 @@
-<?php namespace Dever\Server;
-class Udp
-{
-    public function push($msg)
-    {
-        if (is_array($msg)) {
-            $msg = json_encode($msg);
-        }
-        $this->send($msg);
-        $this->close();
-        return true;
-    }
-    public function start($port, $callback)
-    {
-        $this->bind($port);
-        $this->recv();
-    }
-    public function client($host, $port)
-    {
-        $this->config($host, $port);
-        $this->create();
-    }
-    public function server($host, $port)
-    {
-        ob_implicit_flush();
-        $this->config($host, $port);
-        $this->create();
-    }
-    private function recv()
-    {
-        while (true) {
-            $from = "";
-            $port = 0;
-            socket_recvfrom($this->handle, $data, 1024, 0, $from, $port);
-            echo $data;
-            usleep(1000);
-        }
-    }
-    private function create()
-    {
-        $this->handle = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
-        if ($this->handle === false) {
-            echo "socket_create() failed:reason:" . socket_strerror(socket_last_error()) . "\n";
-            die;
-        }
-    }
-    private function bind($port)
-    {
-        $this->config($port);
-        $ok = socket_bind($this->handle, $this->host, $this->port);
-        if ($ok === false) {
-            echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error($this->handle));
-            die;
-        }
-    }
-    private function send($msg)
-    {
-        $this->config();
-        $len = strlen($msg);
-        $input = Input::getInput('debug');
-        if ($input) {
-            echo $msg;
-        }
-        try {
-            socket_sendto($this->handle, $msg, $len, 0, $this->host, $this->port);
-        } catch(Exception $e) {
-            echo 'Udp Error: ' .$e->getMessage();
-        }
-    }
-    private function close()
-    {
-        socket_close($this->handle);
-    }
-    private function config($host, $port)
-    {
-        $this->host = $host;
-        $this->port = $port;
-    }
-}

+ 11 - 4
src/Dever/String/Sql.php → src/Dever/Sql.php

@@ -1,4 +1,4 @@
-<?php namespace Dever\String;
+<?php namespace Dever;
 class Sql
 {
     public static function setColOrder($order)
@@ -120,7 +120,7 @@ class Sql
             return 'ALTER TABLE `' . $table . '` ADD PARTITION ' . $sql;
         }
     }
-    public static function select($table, $param, &$bind, $set = array(), $field = array())
+    public static function select($table, $param, &$bind, $set = array(), $field = array(), $lock = false)
     {
         $col = '*';
         $rule = '';
@@ -150,6 +150,9 @@ class Sql
                 $rule .= ' LIMIT ' . $set['limit'];
             }
         }
+        if ($lock) {
+            $rule .= ' FOR UPDATE';
+        }
         return 'SELECT ' . $col . ' FROM ' . $table . self::where($param, $bind, $field) . $rule;
     }
     public static function where($param, &$bind, $field = array())
@@ -239,8 +242,8 @@ class Sql
             }
             $a = '';
             if (is_array($v)) {
-                $a = $v[1];
-                $v = $v[0];
+                $a = $v[0];
+                $v = $v[1];
             }
             $sql .= '`' . $k . '`=`' . $k . '`' . $a . ':' . $k . ',';
             $bind[':'.$k] = $v;
@@ -263,4 +266,8 @@ class Sql
         $sql .= implode(',', $insert) . ',';
         return rtrim($sql, ',');
     }
+    public static function distance($lng, $lat)
+    {
+        return 'round((st_distance(point(lng, lat), point('.$lng.', '.$lat.'))*111195)/1000, 2) as distance';
+    }
 }

+ 1 - 1
src/Dever/Store/Base.php

@@ -37,7 +37,7 @@ class Base
             if (strstr($sql, 'select') && strpos($v, ',')) {
                 $v = 'in('.$v.')';
             } else {
-                $v = '"' . $v . '"';
+                $v = '\'' . $v . '\'';
             }
             $sql = str_replace($k, $v, $sql);
         }

+ 3 - 4
src/Dever/Store/Pdo.php

@@ -1,8 +1,7 @@
 <?php namespace Dever\Store;
-use Dever;
 use Dever\Debug;
 use Dever\Output;
-use Dever\String\Sql;
+use Dever\Sql;
 class Pdo extends Base
 {
     protected function connect($setting, $partition)
@@ -106,10 +105,10 @@ class Pdo extends Base
         }
         return $handle;
     }
-    public function select($table, $param, $set, $field)
+    public function select($table, $param, $set, $field, $lock)
     {
         $bind = array();
-        $sql = Sql::select($table, $param, $bind, $set, $field);
+        $sql = Sql::select($table, $param, $bind, $set, $field, $lock);
         return $this->query($sql, $bind);
     }
     public function count($table, $param, $field)

+ 0 - 134
src/Dever/String/Encrypt.php

@@ -1,134 +0,0 @@
-<?php namespace Dever\String;
-class Encrypt
-{
-    private static $key = 'qwertyuiop12345asdfghjkl67890zxcvbnm';
-    public static function encode($string, $key = "")
-    {
-        $ckey_length = 5;
-
-        if (!$key) {
-            $key = Config::get('base')->token;
-            if ($key) {
-                $key = sha1($key);
-            } else {
-                $key = sha1(self::$key);
-            }
-        }
-
-        $keya = md5(substr($key, 0, 16));
-        $keyb = md5(substr($key, 16, 16));
-        $keyc = ''; //md5串后4位,每次不一样
-        if ($ckey_length) {
-            $keyc = substr(md5(microtime()), -$ckey_length);
-        }
-        $cryptkey = $keya . md5($keya . $keyc); //两个md5串
-        $key_length = strlen($cryptkey); //64
-
-        $string = sprintf('%010d', time()) . substr(md5($string . $keyb), 0, 16) . $string;
-        $string_length = strlen($string);
-
-        $result = '';
-        $box = range(0, 255);
-
-        $rndkey = array();
-        for ($i = 0; $i <= 255; $i++) {
-            $rndkey[$i] = ord($cryptkey[$i % $key_length]); //生成一个255个元素的数组
-        }
-
-        for ($j = $i = 0; $i < 256; $i++) {
-            //将$box数组转换为无序并且个数不变的数据
-            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
-            $tmp = $box[$i];
-            $box[$i] = $box[$j];
-            $box[$j] = $tmp;
-        }
-
-        for ($a = $j = $i = 0; $i < $string_length; $i++) {
-            $a = ($a + 1) % 256;
-            $j = ($j + $box[$a]) % 256;
-            $tmp = $box[$a];
-            $box[$a] = $box[$j];
-            $box[$j] = $tmp;
-            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
-        }
-
-        return $keyc . str_replace('=', '', self::base64_encode($result));
-
-    }
-    public static function decode($string, $key = "")
-    {
-        $ckey_length = 5;
-
-        if (!$key) {
-            $key = Config::get('base')->token;
-            if ($key) {
-                $key = sha1($key);
-            } else {
-                $key = sha1(self::$key);
-            }
-        }
-
-        $keya = md5(substr($key, 0, 16));
-        $keyb = md5(substr($key, 16, 16));
-        $keyc = '';//和encrypt时的$keyc一样
-        if ($ckey_length) {
-            $keyc = substr($string, 0, $ckey_length);
-        }
-        $cryptkey = $keya . md5($keya . $keyc);
-        $key_length = strlen($cryptkey);
-
-        $string = self::base64_decode(substr($string, $ckey_length));
-        $string_length = strlen($string);
-
-        $result = '';
-        $box = range(0, 255);
-
-        $rndkey = array();
-        for ($i = 0; $i <= 255; $i++) {
-            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
-        }
-
-        for ($j = $i = 0; $i < 256; $i++) {
-            //和encrypt时的$box一样
-            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
-            $tmp = $box[$i];
-            $box[$i] = $box[$j];
-            $box[$j] = $tmp;
-        }
-
-        for ($a = $j = $i = 0; $i < $string_length; $i++) {
-            //核心操作,解密
-            $a = ($a + 1) % 256;
-            $j = ($j + $box[$a]) % 256;
-            $tmp = $box[$a];
-            $box[$a] = $box[$j];
-            $box[$j] = $tmp;
-            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
-        }
-
-        if (substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
-            return substr($result, 26);
-        } else {
-            return '';
-        }
-
-    }
-    public static function base64_encode($string)
-    {
-        if (!$string) {
-            return false;
-        }
-        $encodestr = base64_encode($string);
-        $encodestr = str_replace(array('+', '/'), array('-', '_'), $encodestr);
-        return $encodestr;
-    }
-    public static function base64_decode($string)
-    {
-        if (!$string) {
-            return false;
-        }
-        $string = str_replace(array('-', '_'), array('+', '/'), $string);
-        $decodestr = base64_decode($string);
-        return $decodestr;
-    }
-}

+ 0 - 113
src/Dever/Support/Command.php

@@ -1,113 +0,0 @@
-<?php namespace Dever\Support;
-use Dever\Import;
-use Dever\Project;
-use Dever\Config;
-class Command
-{
-    public static function daemon($interface, $app = false, $file = 'index.php', $daemon = true)
-    {
-        if (strpos($interface, 'http://') !== false) {
-            return self::run('curl "' . $interface . '"');
-        }
-        if (!$app) {
-            $app = DEVER_APP_NAME;
-        }
-        $app = Project::load($app);
-        $path = isset($app['setup']) ? $app['setup'] : $app['path'];
-        if (isset($app['entry'])) {
-            $file = $app['entry'];
-        }
-        if ($project) {
-            if (strpos($path, 'http://') !== false) {
-                //self::curl($path . $interface);
-                return self::run('curl "' . $path . $interface . '"', $daemon);
-            } else {
-                # ?和&无法解析
-                $php = Config::get('base')->php;
-                if (isset($project['php']) && $project['php']) {
-                    $php = $project['php'];
-                }
-                $interface = str_replace(array('?', '&'), array('__', '^'), $interface);
-                return self::run($php . ' ' . $path . $file . ' -send ' . $interface, $daemon);
-            }
-        }
-        return false;
-    }
-    public static function cron($name, $ldate, $interface, $time = 0, $project = false, $update = true)
-    {
-        if ($ldate > 0) {
-            $ldate = date('Y-m-d H:i:s', $ldate);
-        }
-        $info = Import::load('manage/cron-getOne', array('where_project' => $project, 'where_interface' => $interface));
-        if ($info) {
-            if ($update) {
-                $update = array();
-                $update['set_name'] = $name;
-                $update['set_ldate'] = $ldate;
-                $update['set_interface'] = $interface;
-                $update['set_time'] = $time;
-                $update['set_project'] = $project;
-                $update['set_state'] = 1;
-                $update['where_id'] = $info['id'];
-
-                Import::load('manage/cron-update', $update);
-            }
-        } else {
-            $update = array();
-            $update['add_name'] = $name;
-            $update['add_ldate'] = $ldate;
-            $update['add_interface'] = $interface;
-            $update['add_time'] = $time;
-            $update['add_project'] = $project;
-
-            Import::load('manage/cron-insert', $update);
-        }
-    }
-    public static function kill($command)
-    {
-        $shell = "ps -ef | grep " . $command . " | grep -v grep | awk '{print $2}' | xargs kill -9";
-
-        self::run($shell);
-    }
-    public static function run($shell, $daemon = true)
-    {
-        if ($daemon) {
-            $shell .= ' 1>/dev/null 2>&1 &';
-        }
-
-        $result = exec($shell);
-
-        return $result;
-    }
-    public static function shell($shell)
-    {
-        $path = Config::data() . 'shell/';
-        $path = Path::get($path);
-        $name = md5($shell);
-        $file = $path . $name;
-        $shell = '#!/usr/bin/env sh ' . "\n" . $shell;
-        file_put_contents($file, $shell);
-        exec('chmod +x ' . $file);
-        return $file;
-    }
-    public static function process($command, $count = false)
-    {
-        $shell = "ps -ef | grep " . $command . " | grep -v grep";
-
-        if ($count) {
-            $shell .= ' | wc -l';
-        }
-
-        $result = self::run($shell, false);
-
-        return $result;
-    }
-    public static function log($api, $param = array(), $type = '', $project = 'manage')
-    {
-        $server = $_SERVER['DEVER_SERVER'];
-
-        //self::daemon($api . '?dever_server=' . $server . '&type='.$type.'&param=' . base64_encode(json_encode($param)), $project);
-
-        Import::load($project . '/' . $api, $param);
-    }
-}

+ 0 - 229
src/Dever/Support/Date.php

@@ -1,229 +0,0 @@
-<?php namespace Dever\Support;
-class Date
-{
-	public static function mdate($num, $type = 2)
-    {
-        $date = $num;
-        $num = time() - $num;
-
-        if ($num <= 0) {
-            if ($type == 2) {
-                return '1秒前';
-            } else {
-                return '1S';
-            }
-        }
-
-        $config = array
-            (
-            //array(31536000, 'Y', '年'),
-            //array(2592000, 'T', '个月'),
-            //array(604800, 'W', '星期'),
-            array(86400, 'D', '天'),
-            array(3600, 'H', '小时'),
-            array(60, 'M', '分钟'),
-            array(1, 'S', '秒'),
-        );
-
-        if ($type == 2) {
-            foreach ($config as $k => $v) {
-                $value = intval($num / $v[0]);
-                if ($v[1] == 'D' && $value >= 7) {
-                    break;
-                }
-                if ($value != 0) {
-                    return $value . $v[2] . '前';
-                }
-            }
-
-            return date('Y-m-d H:i:s', $date);
-        } else {
-            $result = '';
-
-            foreach ($config as $k => $v) {
-                if ($num > $v[0]) {
-                    $value = intval($num / $v[0]);
-                    $num = $num - $v[0] * $value;
-                    $result .= $value . $v[1] . ' ';
-                }
-            }
-
-            return $result;
-        }
-    }
-    public static function ddate($num)
-    {
-        $date = date('Ymd');
-        $cdate = date('Ymd', $num);
-
-        if ($cdate == $date) {
-            return date('H:i', $num);
-        } else {
-            $value = intval((time() - $num) / 86400);
-            if ($value == 1) {
-                return '昨天' . date('H:i', $num);
-            } else {
-                $year = date('Y');
-                $cyear = date('Y');
-                if ($year == $cyear) {
-                    return date('m月d日H:i', $num);
-                } else {
-                    return date('Y-m-d H:i', $num);
-                }
-            }
-        }
-        return date('Y-m-d H:i', $num);
-    }
-    public static function maketime($v)
-    {
-        if (!$v) {
-            return '';
-        }
-        if (is_numeric($v)) {
-            return $v;
-        }
-        if (is_array($v)) {
-            $v = $v[1];
-        }
-        if (strstr($v, 'T')) {
-            $v = str_replace(array('T', 'Z'), ' ', $v);
-        }
-        if (strstr($v, ' ')) {
-            $t = explode(' ', $v);
-            $v = $t[0];
-            $s = explode(':', $t[1]);
-        } else {
-            $s = array(0, 0, 0);
-        }
-        if (!isset($s[1])) {
-            $s[1] = 0;
-        }
-        if (!isset($s[2])) {
-            $s[2] = 0;
-        }
-        if (strstr($v, '-')) {
-            $t = explode('-', $v);
-        } elseif (strstr($v, '/')) {
-            $u = explode('/', $v);
-            $t[0] = $u[2];
-            $t[1] = $u[0];
-            $t[2] = $u[1];
-        }
-        if (!isset($t)) {
-            $t = array(0, 0, 0);
-        }
-        if (!isset($t[1])) {
-            $t[1] = '-1';
-        }
-        if (!isset($t[2])) {
-            $t[2] = '01';
-        }
-        $v = mktime($s[0], $s[1], $s[2], $t[1], $t[2], $t[0]);
-        return $v;
-    }
-    public static function udate($format = 'u', $utimestamp = null)
-    {
-        if (is_null($utimestamp)) {
-            $utimestamp = microtime(true);
-        }
-        $timestamp = floor($utimestamp);
-        $milliseconds = round(($utimestamp - $timestamp) * 1000000);
-        return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
-    }
-    # 获取周的开始时间和结束时间
-    public static function week($num = 0, $prefix = '-')
-    {
-        if ($num > 0) {
-            $time = strtotime($prefix . $num.' week');
-        } else {
-            $day = Dever::input('day');
-            if ($day) {
-                $time = Dever::maketime($day);
-            } else {
-                $time = time();
-            }
-        }
-        list($year, $month, $day, $week) = explode('-', date('Y-m-d-w', $time));
-
-        $start = ($day-$week+1) . ' 00:00:00';
-        $end = ($day-$week+7) . ' 23:59:59';
-
-        $start = Dever::maketime($year . '-' . $month . '-' . $start);
-        $end = Dever::maketime($year . '-' . $month . '-' . $end);
-
-        return array($start, $end);
-    }
-
-    # 获取月的开始时间和结束时间
-    public static function month($num = 0, $prefix = '-')
-    {
-        if ($num > 0) {
-            $time = strtotime($prefix . $num.' month');
-        } else {
-            $day = Dever::input('day');
-            if ($day) {
-                $time = Dever::maketime($day);
-            } else {
-                $time = time();
-            }
-        }
-        list($year, $month, $end) = explode('-', date('Y-m-t', $time));
-
-        $start = '01 00:00:00';
-        $end = $end . ' 23:59:59';
-
-        $start = Dever::maketime($year . '-' . $month . '-' . $start);
-        $end = Dever::maketime($year . '-' . $month . '-' . $end);
-        return array($start, $end);
-    }
-
-    # 获取天的开始时间和结束时间
-    public static function day($num = 0, $prefix = '-')
-    {
-        if ($num > 0) {
-            $time = strtotime($prefix . $num.' day');
-        } else {
-            $day = Dever::input('day');
-            if ($day) {
-                $time = Dever::maketime($day);
-            } else {
-                $time = time();
-            }
-        }
-        list($year, $month, $day) = explode('-', date('Y-m-d', $time));
-
-        $start = $day . ' 00:00:00';
-        $end = $day . ' 23:59:59';
-
-        $start = Dever::maketime($year . '-' . $month . '-' . $start);
-        $end = Dever::maketime($year . '-' . $month . '-' . $end);
-        return array($start, $end);
-    }
-
-    public static function showDay($day)
-    {
-        if (strstr($day, '-')) {
-            return $day;
-        }
-        if (strlen($day) == 10) {
-            return date('Y-m-d', $day);
-        }
-        
-        return substr($day, 0, 4) . '-' . substr($day, 4);
-    }
-    # 获取毫秒
-    public static function msectime()
-    {
-        list($msec, $sec) = explode(' ', microtime());
-        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
-        return $msectime;
-    }
-
-    # 获取第几周
-    public static function getWeek($time)
-    {
-        $week = abs(ceil((date('j', $time) - [0,6,5,4,3,2,1][date('w', strtotime(date('Y-m-01')))]) / 7));
-
-        return $week + 1;
-    }
-}

+ 0 - 317
src/Dever/Support/Excel.php

@@ -1,317 +0,0 @@
-<?php namespace Dever\Support;
-use Dever;
-use Dever\Output;
-set_time_limit(0);
-class Excel
-{
-    protected static $instance;
-    private $cell = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ', 'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DH', 'DI', 'DJ', 'DK', 'DL', 'DM', 'DN', 'DO', 'DP', 'DQ', 'DR', 'DS', 'DT', 'DU', 'DV', 'DW', 'DX', 'DY', 'DZ', 'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'EG', 'EH', 'EI', 'EJ', 'EK', 'EL', 'EM', 'EN', 'EO', 'EP', 'EQ', 'ER', 'ES', 'ET', 'EU', 'EV', 'EW', 'EX', 'EY', 'EZ');
-
-    public static function getInstance()
-    {
-        if (empty(self::$instance)) {
-            self::$instance = new self();
-        }
-        return self::$instance;
-    }
-    private static function load($suffix, $method = false)
-    {
-        if ($method == 'excel') {
-            $method = false;
-        }
-        if (!$method) {
-            if (Dever::project('excel')) {
-                Dever::apply('vendor/autoload', 'excel');
-                $method = 'excel';
-            } else {
-                $method = 'csv';
-            }
-        }
-
-        $method .= '_' . $suffix;
-        return $method;
-    }
-    public static function export($data = array(), $header = array(), $fileName = '', $sheet = 0, $sheetName = '', $return = false, $xls = false, $method = false)
-    {
-        $type = Dever::input('excel_type');
-        if ($type == 1) {
-            if ($data) {
-                foreach ($data as $k => $v) {
-                    foreach ($v as $k1 => $v1) {
-                        if (isset($header[$k1])) {
-                            $t = $header[$k1];
-                            if (strstr($t, '身份证') || strstr($t, '手机') || strstr($t, '电话') || strstr($t, '编号') || strstr($t, '编码')) {
-                                $data[$k][$k1] .= "\t";
-                            }
-                        }
-                        if (is_numeric($data[$k][$k1])) {
-                            $data[$k][$k1] = round($v1, 4);
-                        }
-                    }
-                }
-            }
-            return array('body' => $data, 'head' => $header, 'filename' => $fileName);
-        }
-        $method = self::load('export', $method);
-        return self::getInstance()->$method($data, $header, $fileName, $sheet, $sheetName, $return, $xls);
-    }
-    public static function import($file, $sheet = 0, $offset = 0, $method = false)
-    {
-        $method = self::load('import', $method);
-        return self::getInstance()->$method($file, $sheet, $offset);
-    }
-    private function excel_import($file = '', $sheet = 0, $offset = 0)
-    {
-        $file = mb_convert_encoding($file, "UTF-8", "gbk");
-        if(empty($file) OR !file_exists($file)) {
-            Export::alert('file not exists!');
-        }
-        try {
-            $type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file);
-            $read = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($type);
-            //$read->setReadDataOnly(true);
-            $excel = $read->load($file);
-        } catch (\Exception $e) {
-            Export::alert('加载文件发生错误:"'.$file.'": '. $e->getMessage());
-        }
-        $sheet = $excel->getSheet($sheet);
-        $columnH = $sheet->getHighestColumn();
-        $columnCnt = array_search($columnH, $this->cell);
-        if (!$columnCnt) {
-            $columnCnt = $offset - 1;
-        }
-        if ($columnCnt < 0) {
-            $columnCnt = 0;
-        }
-        $rowCnt = $sheet->getHighestRow();
-      
-        $data = array();
-        for ($_row = 1; $_row <= $rowCnt; $_row++) {
-            for ($_column = 0; $_column <= $columnCnt; $_column++) {
-                $cellId = $this->cell[$_column].$_row;
-                //$cellValue = $sheet->getCell($cellId)->getValue();
-                $cellValue = $sheet->getCell($cellId)->getCalculatedValue();
-                if ($cellValue instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText) {
-                    $cellValue = $cellValue->__toString();
-                }
-                $data[$_row][$this->cell[$_column]] = $cellValue;
-            }
-        }
-        $draws = $sheet->getDrawingCollection();
-        //处理图片
-        foreach ($draws as $img) {
-            list($startColumn, $startRow) = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::coordinateFromString($img->getCoordinates());//获取图片所在行和列
-            $pic = Dever::load('upload/save')->copy($img->getPath(), 1);
-            //插入代码
-            //$startColumn = $this->decimal($startColumn);//由于图片所在位置的列号为字母,转化为数字
-            $data[$startRow][$startColumn] = $pic['url'];
-        }
-
-        return $data;  
-    }
-    private function csv_import($file, $lines = 0, $offset = 0)
-    {
-        if (!$fp = fopen($file, 'r')) {
-            return false;
-        }
-        $i = $j = 0;
-        while (false !== ($line = fgets($fp))) {
-            if ($i++ < $offset) {
-                continue;
-            }
-            break;
-        }
-        $data = array();
-        while (($j++ < $lines) && !feof($fp)) {
-            $data[] = fgetcsv($fp);
-        }
-        fclose($fp);
-        return $data;
-    }
-    private function excel_export($data = array(), $header = array(), $fileName = '', $sheet = 0, $sheetName = '', $return = false, $xls = false)
-    {
-        if (!$xls) {
-            $xls = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
-        }
-
-        if ($sheet > 0) {
-            $xls->createSheet();
-        }
-        $act = $xls->setActiveSheetIndex($sheet);
-
-        if ($sheetName) {
-            $act->setTitle($sheetName);
-        }
-        
-        $row = 1;
-        if($header) {
-            $i = 0;
-            if (isset($header['top'])) {
-                foreach($header['top'] as $v) {
-                    $act->setCellValue($this->cell[$i] . $row, $v);
-                    $act->getColumnDimension($this->cell[$i])->setWidth(30);
-                    $i++;
-                }
-                $row++;
-                unset($header['top']);
-            }
-            $i = 0;
-            foreach($header as $v) {
-                $act->setCellValue($this->cell[$i] . $row, $v);
-                $act->getColumnDimension($this->cell[$i])->setWidth(30);
-                $i++;
-            }
-            $row++;
-        }
-
-        if($data) {
-            $i = 0;
-            $height = $max = 80;
-            if (Dever::config('host')->project && isset(Dever::config('host')->project['upload'])) {
-                $project = Dever::config('host')->project;
-                $project['upload'] = array();
-                Dever::config('host')->project = $project;
-            }
-            foreach($data as $v) {
-                $j = 0;
-                foreach($v as $cell) {
-                    //$cell = strip_tags($cell);
-                    $html = Dever::ishtml($cell);
-                    if ($html) {
-                        $wizard = new \PhpOffice\PhpSpreadsheet\Helper\Html;
-                        $cell = $wizard->toRichTextObject('<?xml encoding="UTF-8">' . $cell);
-                    }
-                    if (!$html && (strstr($cell, '.jpg') || strstr($cell, '.gif') || strstr($cell, '.png'))) {
-                        $key = ($i+$row);
-                        $value = false;
-
-                        if (strpos($cell, '||')) {
-                            $t = explode('||', $cell);
-                            $cell = $t[1];
-                            $value = $t[0];
-                        }
-                        $temp = explode(',', $cell);
-
-                        foreach ($temp as $ck => $cv) {
-                            $objDrawing[$ck] = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
-                            if (Dever::project('upload')) {
-                                $cv = str_replace('.jpg', '_t1.jpg', $cv);
-                                $cv = str_replace('.png', '_t1.png', $cv);
-                                $cv = Dever::load('upload/view')->get($cv);
-                            }
-                            $cv = Dever::local($cv);
-                            if (!is_file($cv)) {
-                                continue;
-                            }
-                            $objDrawing[$ck]->setPath($cv);
-                            $objDrawing[$ck]->setHeight($height);
-                            //$objDrawing[$ck]->setWidth(150);
-                            $objDrawing[$ck]->setCoordinates($this->cell[$j] . ($i+$row));
-                            $objDrawing[$ck]->setOffsetX(12);
-                            if ($ck == 0) {
-                                $offsetY = 5;
-                            } else {
-                                $offsetY = $offsetY + $height + 5;
-                            }
-                            $objDrawing[$ck]->setOffsetY($offsetY);
-                            $objDrawing[$ck]->setWorksheet($act);
-                        }
-                        if ($value) {
-                            $act->setCellValue($this->cell[$j] . ($i+$row), $value);
-                        }
-                        
-                        $th = $height * count($temp);
-                        if ($th > $max) {
-                            $max = $th;
-                        }
-                        $act->getRowDimension($i+$row)->setRowHeight($max);
-                        
-                    } else {
-                        if (!$cell) {
-                            //$cell = "";
-                        }
-                        if (is_numeric($cell) && mb_strlen($cell) >= 10) {
-                            $cell .= "\t";
-                        }
-                        $act->setCellValue($this->cell[$j] . ($i+$row), $cell);
-                        $act->getStyle($this->cell[$j] . ($i+$row))->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
-                    }
-                    
-                    $act->getColumnDimension($this->cell[$j])->setAutoSize(true);
-                    $act->getColumnDimension($this->cell[$j])->setWidth(30);
-                    $j++;
-                }
-                $i++;
-            }
-        }
-
-        if ($header && $return) {
-            return $xls;
-        }
-
-        if (!$fileName) {
-            $fileName = uniqid(time(),true);
-        }
-        
-        $write = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($xls);
-        ob_end_clean();
-        header('Content-Type: application/vnd.ms-excel');
-        header('pragma:public');
-        header("Content-Disposition:attachment;filename=$fileName.xlsx");
-        $write->save('php://output');
-    }
-    private function csv_export($data = array(), $header = array(), $fileName = '', $sheet = 0, $sheetName = '', $return = false, $xls = false)
-    {
-        header('Content-Type: application/vnd.ms-excel;charset=gb2312,\uFEFF');
-        header('Content-Disposition: attachment;filename='.$fileName.'.csv');
-        header('Cache-Control: max-age=0');
-        header('Content-Transfer-Encoding: binary'); 
-        $fp = fopen('php://output', 'a');
-        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
-        if (isset($header['top'])) {
-            fputcsv($fp, $header['top']);
-            unset($header['top']);
-        }
-        if (!empty($header)) {
-            fputcsv($fp, $header);
-        }
-        $num = 0;
-        //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
-        $limit = 100000;
-        //逐行取出数据,不浪费内存
-        $count = count($data);
-        if ($count > 0) {
-            for ($i = 0; $i < $count; $i++) {
-                if (isset($data[$i])) {
-                    $num++;
-                    //刷新一下输出buffer,防止由于数据过多造成问题
-                    if ($limit == $num) {
-                        ob_flush();
-                        flush();
-                        $num = 0;
-                    }
-                    $row = $data[$i];
-                    foreach ($row as $k => $v) {
-                        if (is_numeric($row[$k]) && mb_strlen($row[$k]) >= 10) {
-                            $row[$k] .= "\t";
-                        }
-                    }
-                    
-                    fputcsv($fp, $row);
-                }
-            }
-        }
-        fclose($fp);
-    }
-    public function decimal($abc)
-    {
-        $ten = 0;
-        $len = strlen($abc);
-        for($i=1;$i<=$len;$i++){
-            $char = substr($abc,0-$i,1);//反向获取单个字符
-            $int = ord($char);
-            $ten += ($int-65)*pow(26,$i-1);
-        }
-        return $ten;
-    }
-}

+ 0 - 1724
src/Dever/Support/Img.php

@@ -1,1724 +0,0 @@
-<?php namespace Dever\Support;
-
-use Dever;
-
-class Img
-{
-    /**
-     * @desc 使用的图片转换类型,默认是gd库,也可以用imagemagick,值为im
-     * @var string
-     */
-    private $_type = 'gd';//另一个值是im
-
-    /**
-     * @desc 进行缩略图 值为'600_100,100_200'
-     * @var string
-     */
-    private $_thumb = '';
-
-    /**
-     * @desc 进行裁切图 值为'600_100,100_200'
-     * @var string
-     */
-    private $_crop = '';
-
-    /**
-     * @desc 如果文件存在,值为true则强制再次操作,默认为false
-     * @var string
-     */
-    private $_setup = false;
-
-    /**
-     * @desc 图片水平位置 0=>100 1=>100
-     * @var string
-     */
-    private $_position = array();
-
-    /**
-     * @desc 源文件
-     * @var string
-     */
-    private $_source;
-    
-    /**
-     * @desc 裁切图片时候需要抛弃的大小
-     * @var string
-     */
-    private $_dropSize = array();
-
-    /**
-     * @desc 目标文件
-     * @var string
-     */
-    private $_dest = array();
-
-    /**
-     * @desc 添加水印图片
-     * @var array
-     */
-    private $_mark = array();
-
-    /**
-     * @desc 添加文字
-     * @var array
-     */
-    private $_txt = array();
-
-    /**
-     * @desc image的源信息
-     * @var array
-     */
-    private $_image = null;
-
-    /**
-     * @desc image的类型
-     * @var array
-     */
-    private $_imageType = null;
-    
-    /**
-     * @desc 图片压缩的清晰度
-     * @var int
-     */
-    private $_quality = 20;
-
-    /**
-     * @desc 生成的图片名
-     * @var int
-     */
-    private $_name = null;
-
-    /**
-     * @desc 设置图片库类型
-     * @param type(string) 类型
-     */
-    public function setType($type)
-    {
-        $this->_type = $type;
-        return $this;
-    }
-    
-    /**
-     * @desc 设置清晰度
-     * @param quality(int) 清晰度
-     */
-    public function setQuality($quality)
-    {
-        $this->_quality = $quality;
-        return $this;
-    }
-
-    /**
-     * @desc 设置强制功能
-     * @param setup(bool) 是否强制再次生成重复的文件
-     */
-    public function setSetup($setup)
-    {
-        $this->_setup = $setup;
-        return $this;
-    }
-
-    /**
-     * @desc 设置缩略图
-     * @param *
-     */
-    public function setThumb($thumb)
-    {
-        $this->_thumb = $thumb;
-        
-        return $this;
-    }
-
-    /**
-     * @desc 设置裁切图
-     * @param *
-     */
-    public function setCrop($crop)
-    {
-        $this->_crop = $crop;
-        return $this;
-    }
-
-    /**
-     * @desc 设置生成的文件名
-     * @param *
-     */
-    public function setName($name)
-    {
-        if (is_string($name)) $name = explode(',', $name);
-        $this->_name = $name;
-        return $this;
-    }
-
-    /**
-     * @desc 设置位置
-     * @param *
-     */
-    public function setPosition($position)
-    {
-        $this->_position = $position;
-        return $this;
-    }
-
-    /**
-     * @desc 设置水印
-     * @param *
-     */
-    public function setMark($mark)
-    {
-        $this->_mark = $mark;
-        $this->_check('mark', 'water');
-        $this->_check('mark', 'position');
-        return $this;
-    }
-
-    /**
-     * @desc 设置文字
-     * @param *
-     */
-    public function setTxt($txt)
-    {
-        $this->_txt = $txt;
-        
-        return $this;
-    }
-
-    /**
-     * @desc 设置源文件
-     * @param *
-     */
-    public function setSource($source)
-    {
-        if (!$source) {
-            return $this;
-        }
-        $this->_source = $source;
-        $this->_image();
-        return $this;
-    }
-
-    /**
-     * @desc 获取生成的图片名字
-     * @param *
-     */
-    public function getName($name = false, $key = false)
-    {
-        if ($this->_name) {
-            if ($key) {
-                return $this->_name[$key];
-            }
-            return $this->_name[0];
-        } else {
-            return $this->_source . $name;
-        }
-    }
-
-    /**
-     * @desc 获取目标文件
-     * @param *
-     */
-    public function getDest($key = false)
-    {
-        $this->_destroy();
-        return ($key && isset($this->_dest[$key])) ? $this->_dest[$key] : $this->_dest;
-    }
-    
-    /**
-     * @desc 获取宽高
-     * @param *
-     */
-    public function getSize($source)
-    {
-        $this->setSource($source);
-        $this->_image();
-        return array($this->_image->getImageWidth(), $this->_image->getImageHeight());
-    }
-
-    /**
-     * @desc 添加水印图
-     * @param *
-     */
-    public function mark($source, $water, $setup = false, $name = false)
-    {
-        if ($setup == true) {
-            $this->setSetup($setup);
-        }
-        $this->setSource($source);
-        if (!$this->_image) {
-            return $source;
-        }
-        if ($name) $this->setName($name);
-        $this->setMark($water);
-        //if($position) $this->setPosition($position);
-        $this->loadMethod('mark');
-        return $this->getDest('mark');
-    }
-    
-    /**
-     * @desc 对图片进行压缩处理
-     * @param *
-     */
-    public function compress($source, $quality = 75, $name = false)
-    {
-        $this->setSource($source);
-        if (!$this->_image) {
-            return $source;
-        }
-        if ($name) $this->setName($name);
-        $this->setQuality($quality);
-        $this->loadMethod('compress');
-        return $this->getDest('compress');
-    }
-
-    /**
-     * @desc 对图片进行webp转换
-     * @param *
-     */
-    public function webp($source, $quality = 75, $name = false)
-    {
-        $this->setSource($source);
-        if (!$this->_image) {
-            return $source;
-        }
-        if ($name) $this->setName($name);
-        $this->setQuality($quality);
-        $this->loadMethod('webp');
-        return $this->getDest('webp');
-    }
-
-    /**
-     * @desc 对图片进行jpg转换
-     * @param *
-     */
-    public function jpg($source, $quality = 75, $name = false)
-    {
-        $this->setSource($source);
-        if (!$this->_image) {
-            return $source;
-        }
-        if ($name) $this->setName($name);
-        $this->setQuality($quality);
-        $this->loadMethod('jpg');
-        return $this->getDest('jpg');
-    }
-
-    /**
-     * @desc 创建背景图
-     * @param *
-     */
-    public function create($file, $w, $h, $t = 1)
-    {
-        /*
-        $this->_type = 'im';
-        if (!class_exists('\Imagick')) {
-            $this->_type = 'gd';
-        }*/
-        $this->_type = 'gd';
-        $method = '_' . $this->_type . '_create';
-        $this->_image = $this->$method($w, $h, $t);
-        imagejpeg($this->_image, $file);
-        return $file;
-    }
-
-    /**
-     * @desc 构造函数 可批量建立
-     * @param *
-     */
-    public function __construct($source = false, $method = array(), $setup = false, $name = false)
-    {
-        if ($source && $method) {
-            $this->init($source, $method, $setup, $name);
-        }
-    }
-
-    /**
-     * @desc 批量建立
-     * @param *
-     */
-    public function init($source, $method, $setup = false, $name = false)
-    {
-        if ($setup == true) {
-            $this->setSetup($setup);
-        }
-        $this->setSource($source);
-        if (!$this->_image) {
-            return $source;
-        }
-        if ($name) $this->setName($name);
-        foreach ($method as $k => $v) {
-            $k = $v['method'];
-            $m = 'set' . ucfirst($k);
-            $this->$m($v);
-            $this->loadMethod($k);
-        }
-        $this->_name = false;
-        return $this->getDest();
-    }
-
-    /**
-     * @desc 建立缩略图(原比例缩略)
-     * @param *
-     */
-    public function thumb($source, $thumb, $setup = false, $name = false)
-    {
-        if ($setup == true) {
-            $this->setSetup($setup);
-        }
-        $this->setSource($source);
-        if (!$this->_image) {
-            return $source;
-        }
-        if ($name) $this->setName($name);
-        $this->setThumb($thumb);
-        $this->loadMethod('thumb');
-        $this->_name = false;
-        return $this->getDest('thumb');
-    }
-
-    /**
-     * @desc 建立剪切图(从图中剪切)
-     * @param *
-     */
-    public function crop($source, $crop, $position = false, $setup = false, $name = false)
-    {
-        if ($setup == true) {
-            $this->setSetup($setup);
-        }
-        $this->setSource($source);
-        if (!$this->_image) {
-            return $source;
-        }
-        if ($position) $this->setPosition($position);
-        if ($name) $this->setName($name);
-        $this->setCrop($crop);
-        $this->loadMethod('crop');
-        $this->_name = false;
-        return $this->getDest('crop');
-    }
-    
-    /**
-     * @desc 建立剪切图(从图中剪切)
-     * @param *
-     */
-    public function thumbAndCrop($source, $size, $dropSize = array(), $position = false, $setup = true, $name = false)
-    {
-        if ($setup == true) {
-            $this->setSetup($setup);
-        }
-        
-        $this->setSource($source);
-        if (!$this->_image) {
-            return $source;
-        }
-        if ($position) $this->setPosition($position);
-        if ($name) $this->setName($name);
-        $this->setCrop($size);
-        
-        if ($this->_imageType != 'gif') {
-            $this->setThumb($size);
-            $this->_next = true;
-            $this->loadMethod('thumb');
-            $this->_dropSize = $dropSize;
-        }
-        
-        $this->loadMethod('crop');
-        return $this->getDest('crop');
-    }
-
-    /**
-     * @desc 加入文字
-     * @param *
-     */
-    public function txt($source, $txt, $setup = false, $name = false)
-    {
-        if ($setup == true) {
-            $this->setSetup($setup);
-        }
-        $this->setSource($source);
-        if ($name) $this->setName($name);
-        $this->setTxt($txt);
-        $this->loadMethod('txt');
-        return $this->getDest('txt');
-    }
-
-    /**
-     * @desc 载入方法
-     * @param *
-     */
-    public function loadMethod($method)
-    {
-        if ($this->_type == 'im' && !class_exists('\Imagick')) $this->_type = 'gd';
-        $method = '_' . $this->_type . '_create_' . $method;
-        $this->$method();
-    }
-
-    /**
-     * @desc 对变量进行检测
-     * @param name(string) 变量名称
-     */
-    private function _check($name, $key = false)
-    {
-        $name = '_' . $name;
-        if ($name == '_mark') {
-            if (!isset($this->_mark[$key])) {
-                $this->_mark[$key] = 0;
-            }
-            return $this->_mark[$key];
-        }
-        if (isset($this->$name) && $this->$name) {
-            if ($key == false) {
-                return $this->$name;
-            } else {
-                return $this->{$name}[$key];
-            }
-        } else {
-            $this->_error($name . ' error');
-        }
-    }
-
-    /**
-     * @desc 匹配错误
-     * @param *
-     */
-    private function _error($string, $type = 1)
-    {
-        $errstr = '' ;
-        $errstr .= "Img Tool Error:" . $string . "\n";
-        Dever::log($errstr);
-        return $errstr;
-    }
-
-    /**
-     * @desc 获取文件源信息
-     * @param *
-     */
-    private function _image()
-    {
-        $this->_check('source');
-        if (!class_exists('\Imagick')) {
-            $this->_type = 'gd';
-        }
-        if (!$this->_image) {
-            $method = '_' . $this->_type . '_';
-            if (is_array($this->_source)) {
-                $method .= 'create';
-                $this->_image = $this->$method($this->_source[0], $this->_source[1], 1);
-            } else {
-                $method .= 'get';
-                $this->_image = $this->$method($this->_source);
-            }
-            if ($this->_type == 'im' && $this->_image) {
-                $this->_imageType = strtolower($this->_image->getImageFormat());
-            }
-        }
-        
-        return $this->_image;
-    }
-    
-    /*********************
-     * gd库函数
-     *********************/
-
-    /**
-     * @desc 水印
-     * @param *
-     */
-    private function _gd_create_mark()
-    {
-        $this->_check('image');
-        $this->_check('mark', 'water');
-        $this->_check('mark', 'position');
-
-        $this->_dest['mark'] = $this->getName('_mark.jpg');
-
-        if ($this->_setup == true || !file_exists($this->_dest['mark'])) {
-            if (isset($this->_mark['radius'])) {
-                $water = $this->_gd_radius($this->_mark['water'], $this->_mark['radius']);
-            } else {
-                $water  = $this->_gd_get($this->_mark['water']);
-            }
-
-            $source_x = imagesx($this->_image);
-            $source_y = imagesy($this->_image);
-            $water_x = imagesx($water);
-            $water_y = imagesy($water);
-            $width = isset($this->_mark['width']) ? $this->_mark['width'] : $water_x;
-            $height = isset($this->_mark['height']) ? $this->_mark['height'] : $water_y;
-
-            if (isset($this->_mark['width']) || isset($this->_mark['height'])) {
-                $water_w = $water_x/$water_y;
-                $water_h = $water_y/$water_x;
-
-                if ($water_x > $width) {
-                    $dest_x = $width;
-                    $dest_y = $width*$water_h;
-                } elseif ($height > 0 && $water_y > $height) {
-                    $dest_x = $height*$water_w;
-                    $dest_y = $height;
-                } else {
-                    $dest_x = $water_x;
-                    $dest_y = $water_y;
-                }
-
-                $water = $this->_gd_copy($water,$dest_x,$dest_y,$water_x,$water_y,0,0,false,2);
-
-                $xy = $this->get_position($source_x, $source_y, $dest_x, $dest_y);
-                $water_x = $dest_x;
-                $water_y = $dest_y;
-            } else {
-                $xy = $this->get_position($source_x, $source_y, $width, $height);
-            }
-
-            if ($xy[0] == -1) {
-                # 水印平铺 gd的先不做了
-                $xy[0] = $xy[1] = 0;
-            }
-            if ($xy[2] == false) {
-                $this->_gd_destroy($water);
-                return;
-            }
-            $im = $this->_gd_copy($water, $water_x, $water_y, 0, 0, $xy[0], $xy[1], $this->_image);
-
-            imagejpeg($im, $this->_dest['mark']);
-
-            $this->_gd_destroy($water);
-        }
-    }
-
-    /**
-     * @desc 建立缩略图
-     * @param *
-     */
-    private function _gd_create_thumb()
-    {
-        $this->_check('image');
-        $this->_check('thumb');
-        if (!is_array($this->_thumb)) {
-            $array = explode(',',$this->_thumb);
-        } else {
-            $array = $this->_thumb;
-        }
-        $source_x = imagesx($this->_image);
-        $source_y = imagesy($this->_image);
-        $source_w = $source_x/$source_y;
-        $source_h = $source_y/$source_x;
-        foreach ($array as $k => $v) {
-            $this->_dest['thumb'][$k] = $this->getName('_' . $v . '_thumb.jpg', $k);
-            if ($this->_setup == true || !file_exists($this->_dest['thumb'][$k])) {
-                $offset = explode('_',$v);
-                if (isset($offset[2]) && $offset[2] == 1) {
-                    //完全等比例
-                    if ($source_x > $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif ($offset[1] > 0 && $source_y > $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } else {
-                        $dest_x = $source_x;
-                        $dest_y = $source_y;
-                    }
-                } elseif (isset($offset[2]) && $offset[2] == 2) {
-                    //按照一定比例
-                    if ($offset[0] == 0 && $offset[1] > 0) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($offset[1] > 0 && $source_x > $source_y && $source_y > $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($source_y > $source_x && $source_x > $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif ($source_y == $source_x && $offset[0] == $offset[1]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[1];
-                    } elseif ($source_x > $source_y && $source_y < $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif($source_y > $source_x && $source_x < $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif($source_x > $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } else {
-                        $dest_x = $source_x;
-                        $dest_y = $source_y;
-                    }
-                } elseif (isset($offset[2]) && $offset[2] == 3) {
-                    //按照比例缩放,如有多余则留白(或黑...如果实在留不了白的话)
-                    $b = $offset[0]/$offset[1];
-                    $l = $source_x/$source_y;
-                    
-                    if ($b > $l) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } else {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    }
-                } elseif (isset($offset[2]) && $offset[2] == 4) {
-                    //按照一定比例
-                    if ($offset[0] == 0 && $offset[1] > 0) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif($offset[1] > 0 && $source_x > $source_y && $source_y >= $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($source_y > $source_x && $source_x >= $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif ($source_y == $source_x && $offset[0] < $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($source_y == $source_x && $offset[0] > $offset[1]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif ($source_y == $source_x && $offset[0] == $offset[1]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[1];
-                    } elseif ($source_x > $source_y && $source_y < $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($source_y > $source_x && $source_x < $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } else {
-                        $dest_x = $source_x;
-                        $dest_y = $source_y;
-                    }
-                } else {
-                    //直接放大和缩小
-                    $dest_x = $offset[0];
-                    $dest_y = $offset[1];
-                }
-
-                $im = $this->_gd_copy($this->_image,$dest_x,$dest_y,$source_x,$source_y,0,0,false,1);
-
-                imagejpeg($im, $this->_dest['thumb'][$k]);
-                $this->_gd_destroy($im);
-            }
-        }
-    }
-
-    /**
-     * @desc 建立原图压缩图
-     * @param *
-     */
-    private function _gd_create_compress()
-    {
-        $this->_dest['compress'] = $this->_source;
-    }
-
-    /**
-     * @desc 建立剪切图
-     * @param *
-     */
-    private function _gd_create_crop()
-    {
-        $this->_check('image');
-        $this->_check('crop');
-        //$this->_check('position');
-        if (!is_array($this->_crop)) {
-            $array = explode(',',$this->_crop);
-        } else {
-            $array = $this->_crop;
-        }
-        $source_x = imagesx($this->_image);
-        $source_y = imagesy($this->_image);
-        foreach ($array as $k => $v) {
-            $this->_dest['crop'][$k] = $this->getName('_' . $v . '_crop.jpg', $k);
-            if ($this->_setup == true || !file_exists($this->_dest['crop'][$k])) {
-                $x = 0;
-                $y = 0;
-
-                $offset = explode('_',$v);
-                if (isset($this->_dropSize[$k]) && $this->_dropSize[$k]) {
-                    $offset[0] += $this->_dropSize[$k];
-                    $offset[1] += $this->_dropSize[$k];
-                }
-                
-                if ($this->_position) {
-                    if (!is_array($this->_position)) {
-                        list($x, $y) = $this->get_position($source_x, $source_y, $offset[0], $offset[1], 'crop');
-                    } else {
-                        # 加入根据百分比计算裁图
-                        if ($this->_position[0] <= 0) {
-                            $this->_position[0] = $source_x/2 - $offset[0]/2;
-                        } elseif (strstr($this->_position[0], '%')) {
-                            $this->_position[0] = $source_x * intval(str_replace('%', '', $this->_position[0]))/100;
-                        }
-                        if ($this->_position[1] <= 0) {
-                            $this->_position[1] = $source_y/2 - $offset[1]/2;
-                        } elseif (strstr($this->_position[1], '%')) {
-                            $this->_position[1] = $source_y * intval(str_replace('%', '', $this->_position[1]))/100;
-                        }
-                        $x = $this->_position[0];
-                        $y = $this->_position[1];
-                    }
-                } else {
-                    $x = $source_x/2 - $offset[0]/2;
-                    $y = $source_y/2 - $offset[1]/2;
-                }
-                if ($x < 0) {
-                    $x = 0;
-                }
-                if ($y < 0) {
-                    $y = 0;
-                }
-
-                $im = $this->_gd_copy($this->_image,$offset[0],$offset[1],$offset[0],$offset[1],$x,$y);
-
-                imagejpeg($im, $this->_dest['crop'][$k]);
-                $this->_gd_destroy($im);
-            }
-        }
-    }
-    
-    /**
-     * @desc 添加水印文字
-     * @param *
-     */
-    private function _gd_create_txt()
-    {
-        $this->_check('source');
-        $this->_check('image');
-        //$this->_check('txt','file');
-        $this->_check('txt','color');
-        $this->_check('txt','size');
-        $this->_check('txt','angle');
-        $this->_check('txt','name');
-        $this->_check('txt', 'position');
-        //$this->_check('txt','left');
-        //$this->_check('txt','top');
-        //$this->_check('txt','bgcolor');
-        //$this->_check('txt','font');
-
-        $this->_dest['txt'] = isset($this->_txt['file']) ? $this->_txt['file'] : $this->getName('_txt.jpg');
-
-        if ($this->_setup == true || !file_exists($this->_dest['txt'])) {
-
-            $color = $this->_txt['color'];
-
-            $fontFile = isset($this->_txt['font']) ? $this->_txt['font'] : "SIMSUN.TTC";
-
-            $this->_txt['autowrap'] = 0;
-            if (isset($this->_txt['width']) && $this->_txt['width'] > 0) {
-                $this->_txt['name'] = $this->_gd_autowrap($this->_txt['size'], $this->_txt['angle'], $fontFile, $this->_txt['name'], $this->_txt['width']);
-            }
-            
-            $position = imagettfbbox($this->_txt['size'], $this->_txt['angle'], $fontFile, $this->_txt['name']);
-            if ($position) {
-                $source_x = imagesx($this->_image);
-                $source_y = imagesy($this->_image);
-                $water_x = $position[2] - $position[0];
-                $water_y = $position[1] - $position[7];
-
-                $xy = $this->get_position($source_x, $source_y, $water_x, $water_y, 'txt');
-            }
-
-            $this->_txt['left'] = isset($xy[0]) ? $xy[0] : 0;
-            $this->_txt['top'] = isset($xy[1]) ? $xy[1] : 0;
-
-            if (!empty($color) && (strlen($color)==7)) { 
-                $R = hexdec(substr($color,1,2)); 
-                $G = hexdec(substr($color,3,2)); 
-                $B = hexdec(substr($color,5)); 
-                putenv('GDFONTPATH=' . realpath('.'));
-                
-                imagettftext($this->_image, $this->_txt['size'],$this->_txt['angle'], $this->_txt['left'], $this->_txt['top'] + $this->_txt['autowrap'], imagecolorallocate($this->_image, $R, $G, $B),$fontFile,$this->_txt['name']);
-            }
-
-            imagejpeg($this->_image, $this->_dest['txt']);
-        }
-    }
-
-    /**
-     * @desc 文字自动换行
-     * @param *
-     */
-    private function _gd_autowrap($fontsize, $angle, $fontface, $string, $width) {
-        // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
-        $content = "";
-
-        // 将字符串拆分成一个个单字 保存到数组 letter 中
-        for ($i=0;$i<mb_strlen($string);$i++) {
-            $letter[] = mb_substr($string, $i, 1);
-        }
-
-        foreach ($letter as $l) {
-            $teststr = $content." ".$l;
-            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
-            // 判断拼接后的字符串是否超过预设的宽度
-            if (($testbox[2] > $width) && ($content !== "")) {
-                $content .= "\n";
-                $this->_txt['autowrap'] += $this->_txt['size'];
-            }
-            $content .= $l;
-        }
-        return $content;
-    }
-
-    /**
-     * @desc 销毁资源
-     * @param *
-     */
-    private function _gd_destroy($im)
-    {
-        imagedestroy($im);
-        return;
-    }
-
-    /**
-     * @desc copy
-     * @param *
-     */
-    private function _gd_copy($im,$w,$h,$x,$y,$l,$t,$dim = false,$ti = 1)
-    {
-        if ($dim == false) {
-            $dim = $this->_gd_create($w, $h,$ti); // 创建目标图gd2
-            imagecopyresized($dim,$im,0,0,$l,$t,$w,$h,$x,$y);
-        } else {
-
-            imagecopy($dim, $im, $l,$t, 0, 0, $w,$h);
-            //imagecopyresampled($dim, $im, $l,$t, 0, 0, $w,$h,$x,$y);
-        }
-        return $dim;
-    }
-
-    /**
-     * @desc 获取数据源
-     * @param *
-     */
-    private function _gd_get($image)
-    {
-        ini_set("memory_limit", "2048M");
-        /*
-        if (!is_file($image)) {
-            return false;
-        }
-        */
-        $imgstream = file_get_contents($image);
-        $im = imagecreatefromstring($imgstream);
-        return $im;
-    }
-
-    /**
-     * @desc 创建背景图
-     * @param *
-     */
-    private function _gd_create($w,$h,$t = 1)
-    {
-        $dim = imagecreatetruecolor($w,$h); // 创建目标图gd2
-
-        //透明背景
-        if ($t == 2) {
-            
-            imagealphablending($dim, false);
-            imagesavealpha($dim,true);
-            $transparent = imagecolorallocatealpha($dim, 255, 255, 255, 127);
-            imagefilledrectangle($dim, 0, 0, $w, $h, $transparent);
-            
-        }
-        //空白背景
-        elseif ($t == 1) {
-            $wite = ImageColorAllocate($dim,255,255,255);//白色
-            imagefilledrectangle($dim, 0, 0, $w,$h, $wite);
-            imagefilledrectangle($dim, $w, $h, 0,0, $wite);
-            ImageColorTransparent($dim, $wite);
-        }
-        
-        return $dim;
-    }
-
-    /*********************
-     * im库函数
-     *********************/
-
-    /**
-     * @desc 创建背景图
-     * @param *
-     */
-    private function _im_create($w,$h,$t = 1)
-    {
-        $img = new \Imagick();
-        //透明背景
-        if ($t == 2) {
-            $color_transparent = new \ImagickPixel('#transparent'); //transparent 透明色
-        }
-        //空白背景
-        elseif ($t == 1) {
-            $color_transparent = new \ImagickPixel('#ffffff'); //白色
-        }
-
-        $img->newImage($w, $h, $color_transparent, 'jpg');
-        
-        return $img;
-    }
-
-    /**
-     * @desc 建立缩略图
-     * @param *
-     */
-    private function _im_create_thumb()
-    {
-        $this->_check('source');
-        $this->_check('image');
-        $this->_check('thumb');
-        $source_x   = $this->_image->getImageWidth();
-        $source_y   = $this->_image->getImageHeight();
-        $source_w = $source_x/$source_y;
-        $source_h = $source_y/$source_x;
-
-        if (!is_array($this->_thumb)) {
-            $array = explode(',',$this->_thumb);
-        } else {
-            $array = $this->_thumb;
-        }
-        foreach ($array as $k => $v) {
-            $this->_dest['thumb'][$k] = $this->getName('_' . $v . '_thumb.jpg', $k);
-
-            if ($this->_setup == true || !file_exists($this->_dest['thumb'][$k])) {
-                $offset = explode('_',$v);
-
-                if (isset($offset[2]) && $offset[2] == 1) {
-                    //完全等比例
-                    if ($source_x > $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif ($offset[1] > 0 && $source_y > $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } else {
-                        $dest_x = $source_x;
-                        $dest_y = $source_y;
-                    }
-                } elseif (isset($offset[2]) && $offset[2] == 2) {
-                    //按照一定比例
-                    if ($offset[0] == 0 && $offset[1] > 0) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($offset[1] > 0 && $source_x > $source_y && $source_y > $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($source_y > $source_x && $source_x > $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif ($source_y == $source_x && $offset[0] == $offset[1]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[1];
-                    } elseif ($source_x > $source_y && $source_y < $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif($source_y > $source_x && $source_x < $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif($source_x > $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } else {
-                        $dest_x = $source_x;
-                        $dest_y = $source_y;
-                    }
-                } elseif (isset($offset[2]) && $offset[2] == 3) {
-                    //按照比例缩放,如有多余则留白(或黑...如果实在留不了白的话)
-                    $b = $offset[0]/$offset[1];
-                    $l = $source_x/$source_y;
-                    
-                    if ($b > $l) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } else {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    }
-                } elseif (isset($offset[2]) && $offset[2] == 4) {
-                    //按照一定比例
-                    if ($offset[0] == 0 && $offset[1] > 0) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif($offset[1] > 0 && $source_x > $source_y && $source_y >= $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($source_y > $source_x && $source_x >= $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif ($source_y == $source_x && $offset[0] < $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($source_y == $source_x && $offset[0] > $offset[1]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } elseif ($source_y == $source_x && $offset[0] == $offset[1]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[1];
-                    } elseif ($source_x > $source_y && $source_y < $offset[1]) {
-                        $dest_x = $offset[1]*$source_w;
-                        $dest_y = $offset[1];
-                    } elseif ($source_y > $source_x && $source_x < $offset[0]) {
-                        $dest_x = $offset[0];
-                        $dest_y = $offset[0]*$source_h;
-                    } else {
-                        $dest_x = $source_x;
-                        $dest_y = $source_y;
-                    }
-                } else {
-                    //直接放大和缩小
-                    $dest_x = $offset[0];
-                    $dest_y = $offset[1];
-                }
-                //echo $dest_y;die;
-                $this->_image = $this->_im_get($this->_source);  
-                $this->_image->thumbnailImage($dest_x, $dest_y);
-                
-                if (isset($offset[2]) && $offset[2] == 3) {
-                    /* 按照缩略图大小创建一个有颜色的图片 */  
-                    $canvas = $this->_im_get();  
-                    $color = new \ImagickPixel("white");
-                    $canvas->newImage($offset[0], $offset[1], $color, 'png');
-                    //$canvas->paintfloodfillimage('transparent',2000,NULL,0,0);
-                    /* 计算高度 */  
-                    $x = ($offset[0] - $dest_x)/2;  
-                    $y = ($offset[1] - $dest_y)/2;  
-                    /* 合并图片  */  
-                    $canvas->compositeImage($this->_image, \Imagick::COMPOSITE_OVER, $x, $y);
-                    
-                    $canvas->setCompression(\Imagick::COMPRESSION_JPEG); 
-                    $canvas->setCompressionQuality(100);
-
-                    $canvas->writeImage($this->_dest['thumb'][$k]);
-
-                    
-                    if (isset($offset[3]) && $offset[3] && $this->_dest['thumb'][$k]) {
-                        $offset[3] = $offset[3] * 1024;
-                        $size = abs(filesize($this->_dest['thumb'][$k]));
-                        if ($size > $offset[3]) {
-                            $this->_compress($canvas, $offset[3], 80, $this->_dest['thumb'][$k]);
-                        }
-                    }
-                    
-                    $canvas = false;
-                } else {
-                    //$this->_image->setCompression(\Imagick::COMPRESSION_JPEG); 
-                    $this->_image->setCompressionQuality(90);
-                    if ($this->_imageType == 'gif') {
-                        $this->_image->writeImages($this->_dest['thumb'][$k], true);
-                    } else {
-                        $this->_image->writeImage($this->_dest['thumb'][$k]);
-                    }
-                }
-            }
-        }
-        
-        $this->_name = false;
-    }
-    /**
-     * @desc 建立原图压缩图
-     * @param *
-     */
-    private function _im_create_compress()
-    {
-        $this->_check('source');
-        $this->_check('quality');
-        $this->_dest['compress'] = $this->getName('_compress.jpg');
-        
-        $this->_image->stripImage();
-        if (strstr($this->_dest['compress'], '.png')) {
-            $this->_image->setImageType(\Imagick::IMGTYPE_PALETTE);
-            $this->_image->writeImage($this->_dest['compress']);      
-        } else {
-            $this->_image->setCompression(\Imagick::COMPRESSION_JPEG); 
-            $this->_image->setImageCompressionQuality($this->_quality);
-            $this->_image->writeImage($this->_dest['compress']);
-        }
-    }
-    
-    /**
-     * @desc 对图片进行压缩
-     * @param *
-     */
-    private function _compress($canvas, $max, $num, $file)
-    {
-        $num = $num - 10;
-        $temp = $file . '_temp_'.$num.'.jpg';
-        $canvas->setCompressionQuality($num);
-        $canvas->stripImage();
-        
-        $canvas->writeImage($temp);
-            
-        $size = abs(filesize($temp));
-        if ($size > $max && $num > 0) {
-            @unlink($temp);
-            return $this->_compress($canvas, $max, $num, $file);
-        } else {
-            $canvas->destroy();
-            @copy($temp, $file);
-            @unlink($temp);
-        }
-    }
-
-    /**
-     * @desc 设置webp格式
-     * @param *
-     */
-    private function _im_create_webp()
-    {
-        $this->_check('source');
-        $this->_dest['webp'] = $this->getName('.webp');
-
-        //apk add libwebp-tools
-        //Dever::run('cwebp -q 75 '.$this->_source.' -o ' . $this->_dest['webp']);
-
-        $this->_image->setImageFormat('webp');
-        $this->_image->writeImage($this->_dest['webp']);
-    }
-
-    /**
-     * @desc 设置jpg格式
-     * @param *
-     */
-    private function _im_create_jpg()
-    {
-        $this->_check('source');
-        $this->_dest['jpg'] = $this->getName('.jpg');
-
-        //apk add libwebp-tools
-        //Dever::run('cwebp -q 75 '.$this->_source.' -o ' . $this->_dest['webp']);
-
-        $this->_image->setImageFormat('jpg');
-        $this->_image->writeImage($this->_dest['jpg']);
-    }
-
-    /**
-     * @desc 建立裁切图
-     * @param *
-     */
-    private function _im_create_crop()
-    {
-        $this->_check('source');
-        $this->_check('image');
-        $this->_check('crop');
-        
-        if (!is_array($this->_crop)) {
-            $array = explode(',',$this->_crop);
-        } else {
-            $array = $this->_crop;
-        }
-
-        foreach ($array as $k => $v) {
-            if ($this->_name) {
-                $this->_dest['crop'][$k] = $this->getName('_' . $v . '_crop.jpg', $k);
-            } else {
-                $this->_dest['crop'][$k] = (isset($this->_dest['thumb'][$k]) && $this->_dest['thumb'][$k]) ? $this->_dest['thumb'][$k] : $this->getName('_' . $v . '_crop.jpg', $k);
-            }
-            
-            if ($this->_dropSize) {
-                $this->_image = $this->_im_get($this->_dest['crop'][$k]);
-                $source_x   = $this->_image->getImageWidth();
-                $source_y   = $this->_image->getImageHeight();
-            } else {
-                $imageInfo = getimagesize($this->_source);
-                $source_x   = $imageInfo[0];
-                $source_y   = $imageInfo[1];
-            }
-            
-            if ($this->_setup == true || !file_exists($this->_dest['crop'][$k])) {
-                $offset = explode('_',$v);
-                if (isset($this->_dropSize[$k]) && $this->_dropSize[$k]) {
-                    $offset[0] += $this->_dropSize[$k];
-                    $offset[1] += $this->_dropSize[$k];
-                }
-                
-                if ($this->_position) {
-                    if (!is_array($this->_position)) {
-                        list($x, $y) = $this->get_position($source_x, $source_y, $offset[0], $offset[1], 'crop');
-                    } else {
-                        # 加入根据百分比计算裁图
-                        if ($this->_position[0] <= 0) {
-                            $this->_position[0] = $source_x/2 - $offset[0]/2;
-                        } elseif (strstr($this->_position[0], '%')) {
-                            $this->_position[0] = $source_x * intval(str_replace('%', '', $this->_position[0]))/100;
-                        }
-                        if ($this->_position[1] <= 0) {
-                            $this->_position[1] = $source_y/2 - $offset[1]/2;
-                        } elseif (strstr($this->_position[1], '%')) {
-                            $this->_position[1] = $source_y * intval(str_replace('%', '', $this->_position[1]))/100;
-                        }
-                        $x = $this->_position[0];
-                        $y = $this->_position[1];
-                    }
-                    
-                } else {
-                    $x = $source_x/2 - $offset[0]/2;
-                    $y = $source_y/2 - $offset[1]/2;
-                }
-                if ($x < 0) {
-                    $x = 0;
-                }
-                if ($y < 0) {
-                    $y = 0;
-                }
-
-                if ($this->_imageType == 'gif') {
-                    $this->_im_gif($offset[0], $offset[1], $x, $y);
-                } else {  
-                    $this->_image->cropImage($offset[0], $offset[1], $x, $y);
-                }
-                
-                if (isset($offset[2]) && $offset[2] == 3 && isset($offset[3]) && $offset[3] > 0) {
-                    $this->_image->writeImage($this->_dest['crop'][$k]);
-                    $offset[3] = $offset[3] * 1024;
-                    $size = abs(filesize($this->_dest['crop'][$k]));
-                    if ($size > $offset[3]) {
-                        $this->_compress($this->_image, $offset[3], 80, $this->_dest['crop'][$k]);
-                    }
-                } else {
-                    //$this->_image->setCompression(\Imagick::COMPRESSION_JPEG); 
-                    $this->_image->setCompressionQuality(90);
-                    if ($this->_imageType == 'gif') {
-                        $this->_image->writeImages($this->_dest['crop'][$k], true);
-                    } else {
-                        $this->_image->writeImage($this->_dest['crop'][$k]);
-                    }
-                }
-            }
-        }
-    }
-
-    private function _im_gif($w, $h, $x, $y, $d = false, $num = false)
-    {
-        $canvas = $this->_im_get();
-
-        $canvas->setFormat("gif");
-
-        $this->_image->coalesceImages();
-        
-        $num = $num ? $num : $this->_image->getNumberImages();
-
-        for ($i = 0; $i < $num; $i++) {
-            $this->_image->setImageIndex($i);
-                    
-            $img = $this->_im_get();
-            $img->readImageBlob($this->_image);
-            
-            if ($d != false) {
-                $img->drawImage($d);
-            } else {
-                $img->cropImage($w, $h, $x, $y);
-            }
-
-            $canvas->addImage($img);
-            $canvas->setImageDelay($img->getImageDelay());
-            if($d == false) $canvas->setImagePage($w, $h, 0, 0);
-            
-            $img->destroy();
-            
-            unset($img);
-        }
-        
-        $this->_image->destroy();
-        $this->_image = $canvas;
-    }
-
-    /**
-     * @desc 建立水印
-     * @param *
-     */
-    private function _im_create_mark()
-    {
-        $this->_check('source');
-        $this->_check('image');
-        $this->_check('mark', 'water');
-        $this->_check('mark', 'position');
-
-        $this->_dest['mark'] = $this->getName('_mark.jpg');
-
-        if ($this->_setup == true || !file_exists($this->_dest['mark'])) {
-            if (isset($this->_mark['radius'])) {
-                $water = $this->_im_radius($this->_mark['water'], $this->_mark['radius']);
-            } else {
-                $water = $this->_im_get($this->_mark['water']);
-            }
-            $draw = new \ImagickDraw();
-
-            $source_x   = $this->_image->getImageWidth();
-            $source_y   = $this->_image->getImageHeight();
-            $water_x = $water->getImageWidth();
-            $water_y = $water->getImageHeight();
-            $width = isset($this->_mark['width']) ? $this->_mark['width'] : $water_x;
-            $height = isset($this->_mark['height']) ? $this->_mark['height'] : $water_y;
-
-            $water_b = $water_x/$water_y;
-            $mark_b = $width/$height;
-
-            if ($water_b == $mark_b) {
-                # 直接缩放即可
-                $xy = $this->get_position($source_x, $source_y, $width, $height);
-                $water->thumbnailImage($width, $height);
-            } elseif (isset($this->_mark['width']) || isset($this->_mark['height'])) {
-                $water_w = $water_x/$water_y;
-                $water_h = $water_y/$water_x;
-
-                if ($water_x > $width) {
-                    $dest_x = $width;
-                    $dest_y = $width*$water_h;
-                } elseif ($height > 0 && $water_y > $height) {
-                    $dest_x = $height*$water_w;
-                    $dest_y = $height;
-                } else {
-                    $dest_x = $water_x;
-                    $dest_y = $water_y;
-                }
-
-                //$water->thumbnailImage($dest_x, $dest_y);
-                list($x, $y) = $this->get_position($water_x, $water_y, $width, $height, 'crop', 5);
-                $water->cropImage($width, $height, $x, $y);
-
-                $xy = $this->get_position($source_x, $source_y, $dest_x, $dest_y);
-                $water_x = $dest_x;
-                $water_y = $dest_y;
-            } else {
-                $xy = $this->get_position($source_x, $source_y, $width, $height);
-            }
-
-            if ($xy[0] == -1) {
-                # 水印平铺
-                $image = new \Imagick();
-                $image->newImage($source_x, $source_y, new \ImagickPixel( "none" ));
-                $image->setImageFormat("jpg");
-                $water = $image->textureImage($water);
-                $width = $source_x;
-                $height = $source_y;
-                $xy[0] = $xy[1] = 0;
-            }
-            if ($xy[2] == false) {
-                //$this->_destroy($water);
-                return;
-            }
-
-            $draw->composite($water->getImageCompose(), $xy[0], $xy[1], $width, $height, $water);
-      
-            if ($this->_imageType == 'gif') {
-                $this->_im_gif(0, 0, 0, 0, $draw);
-            } else {
-                $this->_image->drawImage($draw);
-            }
-    
-            $this->_image->writeImage($this->_dest['mark']);
-        }
-    }
-
-    /**
-     * @desc 建立文字
-     * @param *
-     */
-    private function _im_create_txt()
-    {
-        $this->_check('source');
-        $this->_check('image');
-        //$this->_check('txt','file');
-        $this->_check('txt','color');
-        $this->_check('txt','size');
-        $this->_check('txt','angle');
-        $this->_check('txt','name');
-        $this->_check('txt', 'position');
-        //$this->_check('txt','left');
-        //$this->_check('txt','top');
-        //$this->_check('txt','bgcolor');
-        //$this->_check('txt','font');
-
-        $this->_dest['txt'] = isset($this->_txt['file']) ? $this->_txt['file'] : $this->getName('_txt.jpg');
-
-        if ($this->_setup == true || !file_exists($this->_dest['txt'])) {
-
-            $fontFile = isset($this->_txt['font']) ? $this->_txt['font'] : "SIMSUN.TTC";
-            
-            $this->_txt['autowrap'] = 0;
-            if (isset($this->_txt['width']) && $this->_txt['width'] > 0) {
-                $this->_txt['name'] = $this->_gd_autowrap($this->_txt['size'], $this->_txt['angle'], $fontFile, $this->_txt['name'], $this->_txt['width']);
-            }
-
-            $draw = new \ImagickDraw();
-            if ($fontFile) {
-                $draw->setFont($fontFile);
-
-                $position = imagettfbbox($this->_txt['size'], $this->_txt['angle'], $fontFile, $this->_txt['name']);
-                if ($position) {
-                    $source_x   = $this->_image->getImageWidth();
-                    $source_y   = $this->_image->getImageHeight();
-                    $water_x = $position[2] - $position[0];
-                    $water_y = $position[1] - $position[7];
-
-                    $xy = $this->get_position($source_x, $source_y, $water_x, $water_y, 'txt');
-                }
-            }
-            
-            if (isset($this->_txt['size'])) {
-                $draw->setFontSize($this->_txt['size']);
-            }
-            if (isset($this->_txt['color'])) {
-                $draw->setFillColor($this->_txt['color']);
-            }
-            if (isset($this->_txt['bgcolor'])) {
-                $draw->setTextUnderColor($this->_txt['bgcolor']);
-            }
-
-            $this->_txt['left'] = isset($xy[0]) ? $xy[0] : 0;
-            $this->_txt['top'] = isset($xy[1]) ? $xy[1] : 0;
-              
-            $draw->setGravity(\Imagick::GRAVITY_NORTHWEST); 
-            if ($this->_imageType == 'gif') {  
-                foreach ($this->_image as $frame) {
-                    $frame->annotateImage($draw, $this->_txt['left'], $this->_txt['top'], $this->_txt['angle'], $this->_txt['name']);
-                }
-            } else {
-                $this->_image->annotateImage($draw, $this->_txt['left'], $this->_txt['top'] + $this->_txt['autowrap'], $this->_txt['angle'], $this->_txt['name']);
-            }
-
-            $this->_image->writeImage($this->_dest['txt']);
-        }
-    }
-
-    /**
-     * @desc 获取数据源
-     * @param *
-     */
-    private function _im_get($image = false)
-    {
-        $image = Dever::local($image);
-        if ($image && strstr($image, 'http')) {
-            $content = file_get_contents($image);
-            $im = new \Imagick();
-            $im->readImageBlob($content);
-        } elseif ($image) {
-            if (!Dever::is_file($image)) {
-                return false;
-            }
-            $im = new \Imagick($image);
-        } else {
-            $im = new \Imagick();
-        }
-        
-        return $im;
-    }
-
-    /**
-     * @desc 圆角图片
-     * @param *
-     */
-    private function _im_radius($img = '', $radius = -1)
-    {
-        $image = $this->_im_get($img);
-        $image->setImageFormat('png');
-        if ($radius == -1) {
-            $x = $image->getImageWidth() / 2;
-            $y = $image->getImageHeight() / 2;
-        } else {
-            $x = $image->getImageWidth() - $radius;
-            $y = $image->getImageHeight() - $radius;
-        }
-        $image->roundCorners($x, $y);
-        return $image;
-    }
-
-    /**
-     * @desc 圆角图片
-     * @param *
-     */
-    private function _gd_radius($imgpath = '', $radius = 0)
-    {
-        $ext     = pathinfo($imgpath);
-        $src_img = null;
-        switch ($ext['extension']) {
-        case 'jpg':
-            $src_img = imagecreatefromjpeg($imgpath);
-            break;
-        case 'png':
-            $src_img = imagecreatefrompng($imgpath);
-            break;
-        }
-        $wh = getimagesize($imgpath);
-        $w  = $wh[0];
-        $h  = $wh[1];
-        $radius = $radius <= 0 ? (min($w, $h) / 2) : $radius;
-        $img = imagecreatetruecolor($w, $h);
-        //这一句一定要有
-        imagesavealpha($img, true);
-        //拾取一个完全透明的颜色,最后一个参数127为全透明
-        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
-        imagefill($img, 0, 0, $bg);
-        $r = $radius; //圆 角半径
-        for ($x = 0; $x < $w; $x++) {
-            for ($y = 0; $y < $h; $y++) {
-                $rgbColor = imagecolorat($src_img, $x, $y);
-                if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
-                    //不在四角的范围内,直接画
-                    imagesetpixel($img, $x, $y, $rgbColor);
-                } else {
-                    //在四角的范围内选择画
-                    //上左
-                    $y_x = $r; //圆心X坐标
-                    $y_y = $r; //圆心Y坐标
-                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
-                        imagesetpixel($img, $x, $y, $rgbColor);
-                    }
-                    //上右
-                    $y_x = $w - $r; //圆心X坐标
-                    $y_y = $r; //圆心Y坐标
-                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
-                        imagesetpixel($img, $x, $y, $rgbColor);
-                    }
-                    //下左
-                    $y_x = $r; //圆心X坐标
-                    $y_y = $h - $r; //圆心Y坐标
-                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
-                        imagesetpixel($img, $x, $y, $rgbColor);
-                    }
-                    //下右
-                    $y_x = $w - $r; //圆心X坐标
-                    $y_y = $h - $r; //圆心Y坐标
-                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
-                        imagesetpixel($img, $x, $y, $rgbColor);
-                    }
-                }
-            }
-        }
-        return $img;
-    }
-
-    public function get_position($source_x, $source_y, $water_x, $water_y, $type = 'mark', $position = '')
-    {
-        $l = 0;
-        $t = 0;
-        $state = 1;
-
-        if ($type == 'crop') {
-            $position = $position ? $position : $this->_position;
-            $offset = 0;
-        } else {
-            $this->_check($type, 'position');
-            $this->_check($type, 'offset');
-            $method = '_' . $type;
-            $position = $position ? $position : $this->{$method}['position'];
-            $offset = $this->{$method}['offset'];
-        }
-        
-        if ($position && is_array($position)) {
-            $l = $position[0];
-            $t = $position[1];
-        } elseif ($position) {
-            switch ($position) {
-                case 1:
-                    //左上
-                    break;
-                case 2:
-                    //左下
-                    $t = $source_y - $water_y;
-                    break;
-                case 3:
-                    //右上
-                    $l = $source_x - $water_x;
-                    break;
-                case 4:
-                    //右下
-                    $l = $source_x - $water_x;
-                    $t = $source_y - $water_y;
-                    break;
-                case 5:
-                    //中间
-                    $l = $source_x/2 - $water_x/2;
-                    $t = $source_y/2 - $water_y/2;
-                    break;
-                case 6:
-                    //上中
-                    $l = $source_x/2 - $water_x/2;
-                    break;
-                case 7:
-                    //下中
-                    $l = $source_x/2 - $water_x/2;
-                    $t = $source_y - $water_y;
-                    break;
-                case 8:
-                    //左中
-                    $t = $source_y/2 - $water_y/2;
-                    break;
-                case 9:
-                    //右中
-                    $l = $source_x - $water_x;
-                    $t = $source_y/2 - $water_y/2;
-                    break;
-                case 10:
-                    //平铺
-                    $l = -1;
-                    $t = -1;
-                    break;
-                default :
-                    $state = false;
-                    break;
-            }
-        }
-
-
-        if (!$l) {
-            $l = 0;
-        }
-        if (!$t) {
-            $t = 0;
-        }
-
-        if ($offset && is_array($offset)) {
-            $l = $l + $offset[0];
-            $t = $t + $offset[1];
-        } else {
-            $l = $l + $offset;
-            $t = $t + $offset;
-        }
-        return array($l, $t, $state);
-    }
-    
-    /**
-     * @desc 判断是否网络文件,如果是,则生成一个本地路径
-     * @param $file 网络文件地址
-     * @param $path 生成的路径,默认为项目根目录下的'data/upload'
-     */
-    private function _setFileName($file, $path = '/upload/')
-    {
-        if (strstr($file, 'http://')) {
-            $array = explode('/', $file);
-            $filename = $array[count($array)-1];
-            $file = Dever::path(Dever::path(Dever::path(Dever::path(Dever::data() . $path) . date("Y") . '/') . date("m") . '/') . date("d") . '/') . $filename;
-        }
-        return $file;
-    }
-    
-    /**
-     * @desc 对网络文件进行拷贝复制到本地
-     * @param $file 网络文件地址
-     * @param $path 生成的路径,默认为项目根目录下的'data/upload'
-     */
-    public function copyFile($file, $path = '/upload/')
-    {
-        if (strstr($file, 'http://')) {
-            $new = $this->_setFileName($file, $path);
-            if (!is_file($new)) {
-                $content = file_get_contents($file);
-                file_put_contents($new, $content);
-            }
-            $file = $new;
-        }
-        return $file;
-    }
-
-    /**
-     * @desc 销毁资源
-     * @param *
-     */
-    private function _destroy()
-    {
-        if ($this->_type == 'gd') {
-            imagedestroy($this->_image);
-        }
-        
-        $this->_image = false;
-    }
-}

+ 64 - 0
src/Dever/View.php

@@ -0,0 +1,64 @@
+<?php namespace Dever;
+class View
+{
+    public static function show($file, $data, $app = '', $path = 'assets')
+    {
+        if (!$app) {
+            $app = DEVER_APP_NAME;
+        }
+        $project = Project::load($app);
+        $template = self::template();
+        $path = $path . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR;
+        $host = $project['url'] . $path;
+        $compile = Path::get('compile' . DIRECTORY_SEPARATOR . $app . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR . $file . '.php');
+        Debug::add($compile, 'template');
+        if (Debug::$shell) {
+            return $data;
+        }
+        $template = $project['path'] . $path . 'template' . DIRECTORY_SEPARATOR . $file . '.html';
+        if (!is_file($template)) {
+            Output::error('file not exists');
+        }
+        $create = true;
+        if (is_file($compile) && filemtime($compile) >= filemtime($template)) {
+            $create = false;
+        }
+        if ($create) {
+            self::create($template, $compile);
+        }
+        include($compile);die;
+    }
+    private static function template()
+    {
+        $template = 'default';
+        if (isset(Config::get('setting')['template']['name']) && Config::get('setting')['template']['name']) {
+            $template = Config::get('setting')['template']['name'];
+            if (strpos($template, ',')) {
+                $temp = explode(',', $template);
+                if (\Dever\Helper\Env::mobile()) {
+                    $template = $temp[1];
+                } else {
+                    $template = $temp[0];
+                }
+            }
+        }
+        return $template;
+    }
+    private static function create($template, $compile)
+    {
+        $content = file_get_contents($template);
+        if (isset(Config::get('setting')['template']['replace'])) {
+            foreach (Config::get('setting')['template']['replace'] as $k => $v) {
+                $content = str_replace($k, $v, $content);
+            }
+        }
+        $content = str_replace('{endforeach}', '<?php endforeach;?>', $content);
+        $content = str_replace('{endif}', '<?php endif;?>', $content);
+        $content = preg_replace('/{foreach(.*?)}/', '<?php foreach($1):?>', $content);
+        $content = preg_replace('/{if(.*?)}/', '<?php if($1):?>', $content);
+        $content = preg_replace('/{\$([a-zA-Z0-9_\'\"\[\]\s]+)}/', '<?php echo \$$1; ?>', $content);
+        $content = preg_replace('/{\$(.*?)([\=|\-|\-\-|\+|\+\+|\*|\/])(.*?)}/', '<?php \$$1$2$3; ?>', $content);
+        $content = preg_replace('/{Dever::(.*?)}/', '<?php echo Dever::$1; ?>', $content);
+        file_put_contents($compile, '<!--power by dever '.date('Y-m-d H:i:s').'-->'.$content);
+    }
+}