diff --git a/niucloud/config/app.php b/niucloud/config/app.php new file mode 100644 index 00000000..3dada4b4 --- /dev/null +++ b/niucloud/config/app.php @@ -0,0 +1,32 @@ + env('app.host', ''), + // 应用的命名空间 + 'app_namespace' => '', + // 是否启用路由 + 'with_route' => true, + // 默认应用 + 'default_app' => 'index', + // 默认时区 + 'default_timezone' => 'Asia/Shanghai', + + // 应用映射(自动多应用模式有效) + 'app_map' => [], + // 域名绑定(自动多应用模式有效) + 'domain_bind' => [], + // 禁止URL访问的应用列表(自动多应用模式有效) + 'deny_app_list' => [], + + // 异常页面的模板文件 + 'exception_tmpl' => app()->getThinkPath() . 'tpl/think_exception.tpl', + + // 错误显示信息,非调试模式有效 + 'error_message' => '页面错误!请稍后再试~', + // 显示错误信息 + 'show_error_msg' => false, +]; diff --git a/niucloud/config/cache.php b/niucloud/config/cache.php new file mode 100644 index 00000000..34f9e1aa --- /dev/null +++ b/niucloud/config/cache.php @@ -0,0 +1,51 @@ + env('cache.driver', 'file'), + + // 缓存连接方式配置 + 'stores' => [ + 'file' => [ + // 驱动方式 + 'type' => 'File', + // 缓存保存目录 + 'path' => app()->getRuntimePath() . 'cache' . DIRECTORY_SEPARATOR, + // 缓存前缀 + 'prefix' => '', + // 缓存有效期 0表示永久缓存 + 'expire' => 0, + // 缓存标签前缀 + 'tag_prefix' => 'tag:', + // 序列化机制 例如 ['serialize', 'unserialize'] + 'serialize' => [], + ], + // 更多的缓存连接 + // redis + 'redis' => [ + // 驱动方式 + 'type' => 'redis', + // 服务器地址 + 'host' => env('redis.redis_hostname', '127.0.0.1'), + // 端口 + 'port' => env('redis.port', '6379'), + // 密码 + 'password' => env('redis.redis_password', ''), + // 缓存有效期 0表示永久缓存 + 'expire' => 0 , + // 缓存前缀 + 'prefix' => '', + // 缓存标签前缀 + 'tag_prefix' => 'tag:', + // 数据库 0号数据库 + 'select' => env('redis.select', 0), + 'serialize' => [], + // 服务端主动关闭 + 'timeout' => 0 + ], + ], +]; diff --git a/niucloud/config/captcha.php b/niucloud/config/captcha.php new file mode 100644 index 00000000..39d7fbc9 --- /dev/null +++ b/niucloud/config/captcha.php @@ -0,0 +1,39 @@ + 4, + // 验证码字符集合 + 'codeSet' => '1234567890', + // 验证码过期时间 + 'expire' => 1800, + // 是否使用中文验证码 + 'useZh' => false, + // 是否使用算术验证码 + 'math' => false, + // 是否使用背景图 + 'useImgBg' => false, + //验证码字符大小 + 'fontSize' => 14, + // 是否使用混淆曲线 + 'useCurve' => true, + //是否添加杂点 + 'useNoise' => true, + // 验证码字体 不设置则随机 + 'fontttf' => '', + //背景颜色 + 'bg' => [243, 251, 254], + // 验证码图片高度 + 'imageH' => 36, + // 验证码图片宽度 + 'imageW' => 100, + + // 添加额外的验证码设置 + // verify => [ + // 'length'=>4, + // ... + //], +]; diff --git a/niucloud/config/console.php b/niucloud/config/console.php new file mode 100644 index 00000000..244e1bf5 --- /dev/null +++ b/niucloud/config/console.php @@ -0,0 +1,24 @@ + [ + 'addon:install' => 'app\command\Addon\Install', + 'addon:uninstall' => 'app\command\Addon\Uninstall', + 'menu:refresh' => 'app\command\Menu', + //消息队列 自定义命令 + 'queue:work' => 'app\command\queue\Queue', + 'queue:restart' => 'app\command\queue\Queue', + 'queue:listen' => 'app\command\queue\Queue', + + //计划任务 自定义命令 + 'cron:schedule' => 'app\command\schedule\Schedule', + + //wokrerman的启动停止和重启 + 'workerman' => 'app\command\workerman\Workerman', + ], +]; +return (new DictLoader("Console"))->load($data); diff --git a/niucloud/config/cookie.php b/niucloud/config/cookie.php new file mode 100644 index 00000000..d3b3aab9 --- /dev/null +++ b/niucloud/config/cookie.php @@ -0,0 +1,20 @@ + 0, + // cookie 保存路径 + 'path' => '/', + // cookie 有效域名 + 'domain' => '', + // cookie 启用安全传输 + 'secure' => false, + // httponly设置 + 'httponly' => false, + // 是否使用 setcookie + 'setcookie' => true, + // samesite 设置,支持 'strict' 'lax' + 'samesite' => '', +]; diff --git a/niucloud/config/cron.php b/niucloud/config/cron.php new file mode 100644 index 00000000..e5a24290 --- /dev/null +++ b/niucloud/config/cron.php @@ -0,0 +1,5 @@ + [] +]; \ No newline at end of file diff --git a/niucloud/config/database.php b/niucloud/config/database.php new file mode 100644 index 00000000..d15ca88b --- /dev/null +++ b/niucloud/config/database.php @@ -0,0 +1,63 @@ + env('database.driver', 'mysql'), + + // 自定义时间查询规则 + 'time_query_rule' => [], + + // 自动写入时间戳字段 + // true为自动识别类型 false关闭 + // 字符串则明确指定时间字段类型 支持 int timestamp datetime date + 'auto_timestamp' => true, + + // 时间字段取出后的默认时间格式 + 'datetime_format' => 'Y-m-d H:i:s', + + // 时间字段配置 配置格式:create_time,update_time + 'datetime_field' => '', + + // 数据库连接配置信息 + 'connections' => [ + 'mysql' => [ + // 数据库类型 + 'type' => env('database.type', 'mysql'), + // 服务器地址 + 'hostname' => env('database.hostname', '127.0.0.1'), + // 数据库名 + 'database' => env('database.database', ''), + // 用户名 + 'username' => env('database.username', 'root'), + // 密码 + 'password' => env('database.password', ''), + // 端口 + 'hostport' => env('database.hostport', '3306'), + // 数据库连接参数 + 'params' => [], + // 数据库编码默认采用utf8 + 'charset' => env('database.charset', 'utf8mb4'), + // 数据库表前缀 + 'prefix' => env('database.prefix', 'ns_'), + + // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) + 'deploy' => 0, + // 数据库读写是否分离 主从式有效 + 'rw_separate' => false, + // 读写分离后 主服务器数量 + 'master_num' => 1, + // 指定从服务器序号 + 'slave_no' => '', + // 是否严格检查字段是否存在 + 'fields_strict' => true, + // 是否需要断线重连 + 'break_reconnect' => false, + // 监听SQL + 'trigger_sql' => env('app_debug', true), + // 开启字段缓存 + 'fields_cache' => false, + ], + + // 更多的数据库配置信息 + ], +]; diff --git a/niucloud/config/filesystem.php b/niucloud/config/filesystem.php new file mode 100644 index 00000000..965297e8 --- /dev/null +++ b/niucloud/config/filesystem.php @@ -0,0 +1,24 @@ + env('filesystem.driver', 'local'), + // 磁盘列表 + 'disks' => [ + 'local' => [ + 'type' => 'local', + 'root' => app()->getRuntimePath() . 'storage', + ], + 'public' => [ + // 磁盘类型 + 'type' => 'local', + // 磁盘路径 + 'root' => app()->getRootPath() . 'public/storage', + // 磁盘路径对应的外部URL路径 + 'url' => '/storage', + // 可见性 + 'visibility' => 'public', + ], + // 更多的磁盘配置信息 + ], +]; diff --git a/niucloud/config/gateway_worker.php b/niucloud/config/gateway_worker.php new file mode 100644 index 00000000..21d1ebe2 --- /dev/null +++ b/niucloud/config/gateway_worker.php @@ -0,0 +1,45 @@ + +// +---------------------------------------------------------------------- +// +---------------------------------------------------------------------- +// | Workerman设置 仅对 php think worker:gateway 指令有效 +// +---------------------------------------------------------------------- +return [ + // 扩展自身需要的配置 + 'protocol' => 'websocket', // 协议 支持 tcp udp unix http websocket text + 'host' => '0.0.0.0', // 监听地址 + 'port' => 2348, // 监听端口 + 'socket' => '', // 完整监听地址 + 'context' => [], // socket 上下文选项 + 'register_deploy' => true, // 是否需要部署register + 'businessWorker_deploy' => true, // 是否需要部署businessWorker + 'gateway_deploy' => true, // 是否需要部署gateway + + // Register配置 + 'registerAddress' => '127.0.0.1:1236', + + // Gateway配置 + 'name' => 'thinkphp', + 'count' => 1, + 'lanIp' => '127.0.0.1', + 'startPort' => 2000, + 'daemonize' => false, + 'pingInterval' => 30, + 'pingNotResponseLimit' => 0, + 'pingData' => '{"type":"ping"}', + + // BusinsessWorker配置 + 'businessWorker' => [ + 'name' => 'BusinessWorker', + 'count' => 1, + 'eventHandler' => '\think\worker\Events', + ], + +]; diff --git a/niucloud/config/imgcaptcha.php b/niucloud/config/imgcaptcha.php new file mode 100644 index 00000000..4374d0cd --- /dev/null +++ b/niucloud/config/imgcaptcha.php @@ -0,0 +1,30 @@ + '', //自定义字体包路径, 不填使用默认值 + //文字验证码 + 'click_world' => [ + 'backgrounds' => [] + ], + //滑动验证码 + 'block_puzzle' => [ + 'backgrounds' => [], //背景图片路径, 不填使用默认值 + 'templates' => [], //模板图 + 'offset' => 10, //容错偏移量 + ], + //水印 + 'watermark' => [ + 'fontsize' => 12, + 'color' => '#ffffff', + 'text' => '' + ], + 'cache' => [ + 'constructor' => [Cache::class, 'instance'] + ] +]; diff --git a/niucloud/config/install.php b/niucloud/config/install.php new file mode 100644 index 00000000..2c6420c7 --- /dev/null +++ b/niucloud/config/install.php @@ -0,0 +1,79 @@ + 'NIUCLOUD-ADMIN', + // logo + 'logo' => 'logo.jpg', + // 官网地址 + 'website_url' => 'https://www.niucloud.com', + // 论坛地址 + 'bbs_url' => 'http://bbs.niucloud.com', + // 编译帮助手册 + 'build_manual' => 'https://www.kancloud.cn/niushop/niucloud-admin-app/3199825', + // 安装协议 + 'agreement' => '版权所有 (c)2023,niucloud-admin保留所有权利。 +

+ 感谢您选择niucloud-admin【以下简称niucloud】,niucloud-admin后台采用thinkphp6+php8+mysql,前端采用uniapp前后端分离的技术开发,全部源码开放。
+ 为了使您正确并合法的使用本软件,请您在使用前务必阅读清楚下面的协议条款: +

+

+ 一、本协议适用于niucloud-admin框架以及框架内所有应用,使用前请您务必仔细阅读本协议须知并勾选接受或者不接受,如不接受此协议,那么您无权利继续注册并使用本协议涉及的所有服务,如果您继续注册,登录,订阅等行为,则视为默认接受本协议。niucloud官方对本授权协议拥有最终解释权。 +

+

+ 二、协议许可权利 +

    +
  1. 1、用户接受并承诺遵守本协议才可登录niucloud-admin官网订购应用,如果用户不同意,那么不允许在niucloud-admin官网注册账号并登录体验。
  2. +
  3. 2、用户必须是具有独立民事责任行为能力的自然人、法人或其他组织个人。若用户不具备前述资格,那么该用户及其监护人应承担导致的一切后果。并且官方有权利对其账号进行冻结,对官方造成的利益损害有权进行申诉索赔。
  4. +
  5. 3、用户可登录niucloud-admin官网下载并安装免费版应用。
  6. +
  7. 4、若需要安装付费版应用,用户需要登录niucloud-admin官网付费并订购付费版应用后才可下载安装。
  8. +
  9. 5、在更新niucloud-admin框架到最新版时,请务必对原整站内容进行备份,否则niucloud官方对升级过程中造成的数据丢失等问题不承担任何责任。
  10. +
  11. 6、niucloud官方下架应用造成的无法更新,官方不承担任何责任。
  12. +
  13. 7、niucloud官方因商业需求,暂停应用的更新,官方不承担任何责任。
  14. +
  15. 8、niucloud官网有权根据需要不时地制订、修改本协议或各类规则,并以公示的方式进行公告,不再单独通知用户。变更后的协议和规则一经公布后,立即自动生效。如用户不同意相关变更,应当立即停止使用niucloud-admin付费应用。如果用户继续订阅、使用niucloud-admin付费应用,即表示用户接受经修订的协议。
  16. +
+

+

+ 三、协议规定的约束和限制 +

    +
  1. 1、请尊重开发人员劳动成果,严禁对本框架进行转卖、销售或二次开发后转卖、销售等商业行为。
  2. +
  3. 2、任何企业和个人不允许对程序代码以任何形式任何目的再发布。
  4. +
  5. 3、基于niucloud-admin应用从事的任何商业行为,都与niucloud官方无关。
  6. +
  7. 4、授权niucloud-admin付费应用时,必须要确保授权信息主体录入的准确性,否则出现的法律纠纷与niucloud官方无关,需要自行解决。
  8. +
  9. 5、应用金额以最终结算价格为准,已售出的应用不做任何差价补偿。
  10. +
  11. 6、如果用户利用特殊手段以低价或者免费获得付费应用,niucloud官方有权对应用进行回收。
  12. +
  13. 7、niucloud-admin付费应用一旦完成交易下载源码,不得以任何形式和理由进行退款,请在购买前仔细阅读本协议。
  14. +
  15. 8、基于niucloud-admin框架进行应用的开发,必须保留框架版权信息。
  16. +
+

+

+ 四、知识产权声明 +

    +
  1. 1、niucloud-admin框架应用源代码所有权和著作权归niucloud官方所有,基于niucloud-admin框架开发的应用,所有权和著作权归应用开发商所有。
  2. +
  3. 2、niucloud-admin框架所依托的代码、文字、图片等著作权、专利权及其他知识产权均归niucloud官方所有,除另外有特别声明。
  4. +
+

+ +

五、有限担保和免责声明

+

+ 本软件及所附带的文件是作为不提供任何明确的或隐含的赔偿或担保的形式提供的。
+ 用户出于自愿而使用本软件,您必须了解使用本软件的风险,在尚未购买产品技术服务之前,我们不承诺对免费用户提供任何形式的技术支持、使用担保,也不承担任何因使用本软件而产生问题的相关责任。 + 电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装niucloud-admin框架,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。 +

', + // 站点名称 + 'admin_site_name' => 'NIUCLOUD ADMIN', + // admin 端登录页默认图 + 'admin_login_bg' => 'install/img/niushop_login_index_left.jpg', + // admin 端默认logo + 'admin_logo' => 'install/img/logo.jpg' +]; diff --git a/niucloud/config/lang.php b/niucloud/config/lang.php new file mode 100644 index 00000000..24fb387e --- /dev/null +++ b/niucloud/config/lang.php @@ -0,0 +1,27 @@ + env('lang.default_lang', 'zh-cn'), + // 允许的语言列表 + 'allow_lang_list' => ['zh-cn', 'en'], + // 多语言自动侦测变量名 + 'detect_var' => 'lang', + // 是否使用Cookie记录 + 'use_cookie' => false, + // 多语言cookie变量 + 'cookie_var' => 'lang', + // 多语言header变量 + 'header_var' => 'lang', + 'extend_list' => [ + ], + // Accept-Language转义为对应语言包名称 + 'accept_language' => [ + 'zh-hans-cn' => 'zh-cn', + ], + // 是否支持语言分组 + 'allow_group' => true, +]; diff --git a/niucloud/config/log.php b/niucloud/config/log.php new file mode 100644 index 00000000..ea24ff9d --- /dev/null +++ b/niucloud/config/log.php @@ -0,0 +1,45 @@ + env('log.channel', 'file'), + // 日志记录级别 + 'level' => [], + // 日志类型记录的通道 ['error'=>'email',...] + 'type_channel' => [], + // 关闭全局日志写入 + 'close' => false, + // 全局日志处理 支持闭包 + 'processor' => null, + + // 日志通道列表 + 'channels' => [ + 'file' => [ + // 日志记录方式 + 'type' => 'File', + // 日志保存目录 + 'path' => '', + // 单文件日志写入 + 'single' => false, + // 独立日志级别 + 'apart_level' => [], + // 最大日志文件数量 + 'max_files' => 0, + // 使用JSON格式记录 + 'json' => false, + // 日志处理 + 'processor' => null, + // 关闭通道日志写入 + 'close' => false, + // 日志输出格式化 + 'format' => '[%s][%s] %s', + // 是否实时写入 + 'realtime_write' => false, + ], + // 其它日志通道配置 + ], + +]; diff --git a/niucloud/config/middleware.php b/niucloud/config/middleware.php new file mode 100644 index 00000000..7e1972f5 --- /dev/null +++ b/niucloud/config/middleware.php @@ -0,0 +1,8 @@ + [], + // 优先级设置,此数组中的中间件会按照数组中的顺序优先执行 + 'priority' => [], +]; diff --git a/niucloud/config/niucloud.php b/niucloud/config/niucloud.php new file mode 100644 index 00000000..1d15de69 --- /dev/null +++ b/niucloud/config/niucloud.php @@ -0,0 +1,16 @@ + [ + 'code' => env('niucloud.code', ''),//授权码 + 'secret' => env('niucloud.secret', ''),//授权秘钥 + ], + 'http' => [ + 'max_retries' => 1,// 重试次数,默认 1,指定当 http 请求失败时重试的次数。 + 'retry_delay' => 1000,//重试延迟间隔(单位:ms),默认 500 + 'timeout' => 5.0,//最大运行时间(超时) + 'verify' => false,//请求时验证SSL证书行为。设置成 true 启用SSL证书验证,默认使用操作系统提供的CA包。设置成 false 禁用证书验证(这是不安全的!)。设置成字符串启用验证,并使用该字符串作为自定义证书CA包的路径。 + ], + 'response_type' => 'array', + +]; diff --git a/niucloud/config/oauth.php b/niucloud/config/oauth.php new file mode 100644 index 00000000..e34704ed --- /dev/null +++ b/niucloud/config/oauth.php @@ -0,0 +1,26 @@ + 'wechat', + //驱动厂商列表及参数-第三方授权 + 'drivers' => [ + //微信公众号 + 'wechat' => [ + + ], + //微信小程序 + 'weapp' => [ + + ] + ] +]; diff --git a/niucloud/config/pay.php b/niucloud/config/pay.php new file mode 100644 index 00000000..4a8eb2fb --- /dev/null +++ b/niucloud/config/pay.php @@ -0,0 +1,33 @@ + 'wechatpay', + //驱动 + 'drivers' => [ + //微信 + 'wechatpay' => [], + //支付宝 + 'alipay' => [], + //余额 + 'balancepay' => [ + 'driver' => 'app\service\core\paytype\CoreBalanceService', //反射类的名字 + ], + 'offlinepay' => [ + 'driver' => 'app\service\core\paytype\CoreOfflineService' + ] + ] +]; + +return (new DictLoader("Config"))->load(['data' => $system, 'name' => 'pay']); diff --git a/niucloud/config/poster.php b/niucloud/config/poster.php new file mode 100644 index 00000000..ffed52e2 --- /dev/null +++ b/niucloud/config/poster.php @@ -0,0 +1,22 @@ + 'poster', + //驱动厂商列表及参数-海报 + 'drivers' => [ + //牛云默认海报 + 'poster' => [ + + ] + ] +]; diff --git a/niucloud/config/route.php b/niucloud/config/route.php new file mode 100644 index 00000000..2f4cd129 --- /dev/null +++ b/niucloud/config/route.php @@ -0,0 +1,45 @@ + '/', + // URL伪静态后缀 + 'url_html_suffix' => 'html', + // URL普通方式参数 用于自动生成 + 'url_common_param' => true, + // 是否开启路由延迟解析 + 'url_lazy_route' => false, + // 是否强制使用路由 + 'url_route_must' => false, + // 合并路由规则 + 'route_rule_merge' => false, + // 路由是否完全匹配 + 'route_complete_match' => false, + // 访问控制器层名称 + 'controller_layer' => 'controller', + // 空控制器名 + 'empty_controller' => 'Error', + // 是否使用控制器后缀 + 'controller_suffix' => false, + // 默认的路由变量规则 + 'default_route_pattern' => '[\w\.]+', + // 是否开启请求缓存 true自动缓存 支持设置请求缓存规则 + 'request_cache_key' => false, + // 请求缓存有效期 + 'request_cache_expire' => null, + // 全局请求缓存排除规则 + 'request_cache_except' => [], + // 默认控制器名 + 'default_controller' => 'Index', + // 默认操作名 + 'default_action' => 'index', + // 操作方法后缀 + 'action_suffix' => '', + // 默认JSONP格式返回的处理方法 + 'default_jsonp_handler' => 'jsonpReturn', + // 默认JSONP处理方法 + 'var_jsonp_handler' => 'callback', +]; diff --git a/niucloud/config/session.php b/niucloud/config/session.php new file mode 100644 index 00000000..c1ef6e16 --- /dev/null +++ b/niucloud/config/session.php @@ -0,0 +1,19 @@ + 'PHPSESSID', + // SESSION_ID的提交变量,解决flash上传跨域 + 'var_session_id' => '', + // 驱动方式 支持file cache + 'type' => 'file', + // 存储连接标识 当type使用cache的时候有效 + 'store' => null, + // 过期时间 + 'expire' => 1440, + // 前缀 + 'prefix' => '', +]; diff --git a/niucloud/config/sms.php b/niucloud/config/sms.php new file mode 100644 index 00000000..114fb4d2 --- /dev/null +++ b/niucloud/config/sms.php @@ -0,0 +1,36 @@ + 'aliyun', + //驱动厂商列表及参数-短信 + 'drivers' => [ + //阿里云 + 'aliyun' => [ + 'driver' => 'core\sms\Aliyun', //反射类的名字 + 'app_key' => '', + 'secret_key' => '', + 'sign' => '', + ], + //腾讯云 + 'tencent' => [ + 'secret_id' => '', + 'secret_key' => '', + 'sign' => '', + 'app_id' => '', + ] + ] +]; + +return (new DictLoader("Config"))->load(['data' => $system, 'name' => 'sms']); diff --git a/niucloud/config/terminal.php b/niucloud/config/terminal.php new file mode 100644 index 00000000..77b6fdb5 --- /dev/null +++ b/niucloud/config/terminal.php @@ -0,0 +1,44 @@ + [ + + // 查看版本的命令 + 'version' => [ + 'npm' => 'npm -v', + 'node' => 'node -v', + ], + 'npm-admin' => [ + 'cwd' => 'admin', + 'command' => 'npm install', + ], + + 'npm-web' => [ + 'cwd' => 'web', + 'command' => 'npm install', + ], + + 'npm-uni-app' => [ + 'cwd' => 'uni-app', + 'command' => 'npm install', + ], + + 'composer-install' => [ + 'cwd' => 'niucloud', + 'command' => 'composer update', + ], + // 切换到国内镜像 + 'set-mirror' => [ + //切换到淘宝镜像 + 'npm' => 'npm config set registry https://registry.npmjs.org', + //切换到阿里云镜像 + 'composer' => 'composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/', + ], + ], +]; + diff --git a/niucloud/config/trace.php b/niucloud/config/trace.php new file mode 100644 index 00000000..0b2ee6d1 --- /dev/null +++ b/niucloud/config/trace.php @@ -0,0 +1,10 @@ + env('app_trace_type', 'Html'), + // 读取的日志通道名 + 'channel' => '', +]; diff --git a/niucloud/config/upload.php b/niucloud/config/upload.php new file mode 100644 index 00000000..a2603480 --- /dev/null +++ b/niucloud/config/upload.php @@ -0,0 +1,98 @@ + 'local',//默认驱动 + 'drivers' => [ + //本地上传 + 'local' => [], + //七牛云 + 'qiniu' => [ + 'access_key' => '', + 'secret_key' => '', + 'bucket' => '' + ], + //阿里云 + 'aliyun' => [ + 'access_key' => '', + 'secret_key' => '', + 'endpoint' => '', + 'bucket' => '' + ], + //腾讯云 + 'tencent' => [ + 'access_key' => '', + 'secret_key' => '', + 'region' => '', + 'bucket' => '' + ], + ], + // 默认规则 + 'rules' => [ + 'image' => [ + 'ext' => ['jpg', 'jpeg', 'png', 'gif'], + 'mime' => ['image/jpeg', 'image/gif', 'image/png'], + 'size' => 10485760 + ], + 'video' => [ + 'ext' => ['mp4'], + 'mime' => ['video/mp4'], + 'size' => 104857600 + ], + 'wechat' => [ + 'ext' => ['pem', 'key'], + 'mime' => [ + 'application/x-x509-ca-cert', + 'application/octet-stream', + 'application/x-iwork-keynote-sffkey' + ], + 'size' => 2097152 + ], + 'aliyun' => [ + 'ext' => ['crt'], + 'mime' => [ + 'application/x-x509-ca-cert', + 'application/octet-stream' + ], + 'size' => 2097152 + ], + 'applet' => [ + 'ext' => ['zip', 'rar'], + 'mime' => [ + 'application/zip', + 'application/vnd.rar', + 'application/x-zip-compressed' + ], + 'size' => 2097152 + ], + 'excel' => [ + 'ext' => ['xls', 'xlsx'], + 'mime' => [ + 'application/vnd.ms-excel', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ], + 'size' => 10485760 + ] + ], + 'thumb' => [ + 'thumb_type' => [ + 'big' => [ + 'width' => 1200, + 'height' => 1200, + ], + 'mid' => [ + 'width' => 800, + 'height' => 800, + ], + 'small' => [ + 'width' => 200, + 'height' => 200, + ], + ] + + + ] +]; + +return (new DictLoader("Config"))->load(['data' => $system, 'name' => 'upload']); diff --git a/niucloud/config/version.php b/niucloud/config/version.php new file mode 100644 index 00000000..67c29f73 --- /dev/null +++ b/niucloud/config/version.php @@ -0,0 +1,6 @@ + '1.5.1', + 'code' => '2025022201' +]; diff --git a/niucloud/config/view.php b/niucloud/config/view.php new file mode 100644 index 00000000..5f39a1d6 --- /dev/null +++ b/niucloud/config/view.php @@ -0,0 +1,31 @@ + 'Think', + // 默认模板渲染规则 1 解析为小写+下划线 2 全部转换小写 3 保持操作方法 + 'auto_rule' => 1, + // 模板目录名 + 'view_dir_name' => 'view', + // 模板后缀 + 'view_suffix' => 'html', + // 模板文件名分隔符 + 'view_depr' => DIRECTORY_SEPARATOR, + // 模板引擎普通标签开始标记 + 'tpl_begin' => '{', + // 模板引擎普通标签结束标记 + 'tpl_end' => '}', + // 标签库标签开始标记 + 'taglib_begin' => '{', + // 标签库标签结束标记 + 'taglib_end' => '}', + 'tpl_cache' => false, //模板缓存,部署模式后改为true + 'tpl_replace_string' => [ + 'INSTALL_IMG' => '/install/img', + 'INSTALL_CSS' => '/install/css', + 'INSTALL_JS' => '/install/js', + ] +]; diff --git a/niucloud/core/core/base/BaseAdminController.php b/niucloud/core/core/base/BaseAdminController.php new file mode 100644 index 00000000..e9ec2b7c --- /dev/null +++ b/niucloud/core/core/base/BaseAdminController.php @@ -0,0 +1,29 @@ +username = $this->request->username(); + $this->uid = $this->request->uid(); + } +} diff --git a/niucloud/core/core/base/BaseApiController.php b/niucloud/core/core/base/BaseApiController.php new file mode 100644 index 00000000..6fac93f0 --- /dev/null +++ b/niucloud/core/core/base/BaseApiController.php @@ -0,0 +1,29 @@ +member_id = $this->request->memberId(); + $this->channel = $this->request->getChannel(); + } +} \ No newline at end of file diff --git a/niucloud/core/core/base/BaseController.php b/niucloud/core/core/base/BaseController.php new file mode 100644 index 00000000..793b992b --- /dev/null +++ b/niucloud/core/core/base/BaseController.php @@ -0,0 +1,96 @@ +app = $app; + $this->request = $this->app->request; + // 控制器初始化 + $this->initialize(); + } + + // 初始化 + protected function initialize() + { + } + + /** + * 验证数据 + * @access protected + * @param array $data 数据 + * @param string|array $validate 验证器名或者验证规则数组 + * @param array $message 提示信息 + * @param bool $batch 是否批量验证 + * @return array|string|true + * @throws ValidateException + */ + protected function validate(array $data, $validate, array $message = [], bool $batch = false) + { + if (is_array($validate)) { + $v = new Validate(); + $v->rule($validate); + } else { + if (strpos($validate, '.')) { + // 支持场景 + [$validate, $scene] = explode('.', $validate); + } + $class = str_contains($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate); + $v = new $class(); + if (!empty($scene)) { + $v->scene($scene); + } + } + + $v->message($message); + + // 是否批量验证 + if ($batch || $this->batchValidate) { + $v->batch(); + } + + return $v->failException()->check($data); + } + + +} diff --git a/niucloud/core/core/base/BaseCoreService.php b/niucloud/core/core/base/BaseCoreService.php new file mode 100644 index 00000000..8f152c27 --- /dev/null +++ b/niucloud/core/core/base/BaseCoreService.php @@ -0,0 +1,27 @@ +runJob($method, $data); + } + + + /** + * 执行任务 + * @param string $method + * @param array $data + * @param int $error_count + */ + protected function runJob(string $method, array $data) + { + try { + $method = method_exists($this, $method) ? $method : 'handle'; + if (!method_exists($this, $method)) { + throw new CommonException('Job "'.static::class.'" not found!'); + } + $this->{$method}(...$data); + return true; + } catch (\Throwable $e) { + Log::write('队列错误:'.static::class.$method.'_'.'_'.$e->getMessage().'_'.$e->getFile().'_'.$e->getLine()); + throw new CommonException('Job "'.static::class.'" has error!'); + } + + } + +} diff --git a/niucloud/core/core/base/BaseModel.php b/niucloud/core/core/base/BaseModel.php new file mode 100644 index 00000000..dbf71c86 --- /dev/null +++ b/niucloud/core/core/base/BaseModel.php @@ -0,0 +1,48 @@ +getTable(); + $sql = 'SHOW TABLE STATUS WHERE 1=1 '; + $tablePrefix = config('database.connections.mysql.prefix'); + if (!empty($table_name)) { + $sql .= "AND name='" .$table_name."'"; + } + $tables = Db::query($sql); + $table_info = $tables[0] ?? []; + $table_name = preg_replace("/^{$tablePrefix}/", '', $table_info['Name'], 1); + return Db::name($table_name)->getFields(); + } + + /** + * 处理搜索条件特殊字符(%、_) + * @param $value + */ + public function handelSpecialCharacter($value) + { + $value = str_replace('%', '\%', str_replace('_', '\_', $value)); + return $value; + } +} diff --git a/niucloud/core/core/base/BaseService.php b/niucloud/core/core/base/BaseService.php new file mode 100644 index 00000000..d3f1ecb7 --- /dev/null +++ b/niucloud/core/core/base/BaseService.php @@ -0,0 +1,135 @@ +request = request(); + } + + /** + * 分页列表参数(页码和每页多少条) + * @return mixed + */ + public function getPageParam() + { + + $page = request()->params([ + ['page', 1], + ['limit', 15] + ]); + validate(Page::class) + ->check($page); + return $page; + } + + /** + * 分页列表 + * @param Model $model + * @param array $where + * @param string $field + * @param string $order + * @param array $append + * @return array + * @throws DbException + */ + public function getPageList(Model $model, array $where, string $field = '*', string $order = '', array $append = [], $with = null, $each = null) + { + $page_params = $this->getPageParam(); + $page = $page_params['page']; + $limit = $page_params['limit']; + + $list = $model->where($where)->when($append, function ($query) use ($append) { + $query->append($append); + })->when($with, function ($query) use ($with) { + $query->with($with); + })->field($field)->order($order)->paginate([ + 'list_rows' => $limit, + 'page' => $page, + ]); + if (!empty($each)) { + $list = $list->each($each); + } + return $list->toArray(); + } + + /** + * 分页数据查询,传入model(查询后结果) + * @param $model BaseModel + * @return array + * @throws DbException + */ + public function pageQuery($model, $each = null) + { + $page_params = $this->getPageParam(); + $page = $page_params['page']; + $limit = $page_params['limit']; + $list = $model->paginate([ + 'list_rows' => $limit, + 'page' => $page, + ]); + if (!empty($each)) { + $list = $list->each($each); + } + return $list->toArray(); + } + + /** + * 分页视图列表查询 + * @param Model $model + * @param array $where + * @param string $field + * @param string $order + * @param array $append + * @return array + * @throws DbException + */ + public function getPageViewList(Model $model, array $where, string $field = '*', string $order = '', array $append = [], $with = null, $each = null) + { + $page_params = $this->getPageParam(); + $page = $page_params['page']; + $limit = $page_params['limit']; + + $list = $model->where($where)->when($append, function ($query) use ($append) { + $query->append($append); + })->when($with, function ($query) use ($with) { + $query->withJoin($with); + })->field($field)->order($order)->paginate([ + 'list_rows' => $limit, + 'page' => $page, + ]); + if (!empty($each)) { + $list = $list->each($each); + } + return $list->toArray(); + } + +} \ No newline at end of file diff --git a/niucloud/core/core/base/BaseValidate.php b/niucloud/core/core/base/BaseValidate.php new file mode 100644 index 00000000..34a2b0a5 --- /dev/null +++ b/niucloud/core/core/base/BaseValidate.php @@ -0,0 +1,46 @@ +parseMsg(); + } + + public function parseMsg(){ + if(!empty($this->message)) + { + foreach ($this->message as $key => $value) + { + if(is_array($value)) + { + $this->message[$key] = get_lang($value[0], $value[1]); + } + } + } + + } + +} diff --git a/niucloud/core/core/dict/AdvPosition.php b/niucloud/core/core/dict/AdvPosition.php new file mode 100644 index 00000000..188726bb --- /dev/null +++ b/niucloud/core/core/dict/AdvPosition.php @@ -0,0 +1,38 @@ +getLocalAddons(); + $adv_position_files = []; + foreach ($addons as $v) { + $adv_position_path = $this->getAddonDictPath($v) . "web" . DIRECTORY_SEPARATOR . "adv_position.php"; + if (is_file($adv_position_path)) { + $adv_position_files[] = $adv_position_path; + } + } + $adv_position_file_data = $this->loadFiles($adv_position_files); + $adv_position = $data; + foreach ($adv_position_file_data as $file_data) { + $adv_position = empty($adv_position) ? $file_data : array_merge($adv_position, $file_data); + } + return $adv_position; + } +} diff --git a/niucloud/core/core/dict/BaseDict.php b/niucloud/core/core/dict/BaseDict.php new file mode 100644 index 00000000..75cdc603 --- /dev/null +++ b/niucloud/core/core/dict/BaseDict.php @@ -0,0 +1,162 @@ +column("key"); + Cache::tag(CoreAddonBaseService::$cache_tag_name)->set("local_install_addons", $addons); + + return $addons; + } + + /** + * 获取所有本地插件(包括未安装,用于系统指令执行) + * @return array|false + */ + public function getAllLocalAddons() + { + $addon_dir = root_path() . 'addon'; + $addons = array_diff(scandir($addon_dir), ['.', '..']); + return $addons; + } + + /** + * 获取插件目录 + * @param string $addon + * @return string + */ + protected function getAddonPath(string $addon) + { + return root_path() . 'addon' . DIRECTORY_SEPARATOR . $addon . DIRECTORY_SEPARATOR; + + } + + /** + * 获取系统整体app目录 + * @return string + */ + protected function getAppPath() + { + return root_path() . "app" . DIRECTORY_SEPARATOR; + } + + /** + * 获取插件对应app目录 + * @param string $addon + * @return string + */ + protected function getAddonAppPath(string $addon) + { + return $this->getAddonPath($addon) . "app" . DIRECTORY_SEPARATOR; + } + + /** + *获取系统dict path + */ + protected function getDictPath() + { + return root_path() . 'app' . DIRECTORY_SEPARATOR . 'dict' . DIRECTORY_SEPARATOR; + } + + /** + *获取插件对应的dict目录 + * @param string $addon + * @return string + */ + protected function getAddonDictPath(string $addon) + { + return $this->getAddonPath($addon) . 'app' . DIRECTORY_SEPARATOR . 'dict' . DIRECTORY_SEPARATOR; + } + + /** + *获取插件对应的config目录 + * @param string $addon + * @return string + */ + protected function getAddonConfigPath(string $addon) + { + return $this->getAddonPath($addon) . 'config' . DIRECTORY_SEPARATOR; + } + + /** + * 加载文件数据 + * @param $files + * @return array + */ + protected function loadFiles($files) + { + $default_sort = 100000; + $files_data = []; + if (!empty($files)) { + foreach ($files as $file) { + $config = include $file; + if (!empty($config)) { + if (isset($config['file_sort'])) { + $sort = $config['file_sort']; + unset($config['file_sort']); + $sort = $sort * 10; + while (array_key_exists($sort, $files_data)) { + $sort++; + } + $files_data[$sort] = $config; + } else { + $files_data[$default_sort] = $config; + $default_sort++; + } + } + } + } + ksort($files_data); + return $files_data; + } + + /** + * 加载 + * @return mixed + */ + abstract public function load(array $data); +} diff --git a/niucloud/core/core/dict/Config.php b/niucloud/core/core/dict/Config.php new file mode 100644 index 00000000..d7f404fd --- /dev/null +++ b/niucloud/core/core/dict/Config.php @@ -0,0 +1,41 @@ +getAllLocalAddons(); + $config_files = []; + + foreach ($addons as $v) { + $config_path = $this->getAddonAppPath($v) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . $config . '.php'; + if (is_file($config_path)) { + $config_files[] = $config_path; + } + } + $files_data = $this->loadFiles($config_files); + + foreach ($files_data as $file_data) { + if(!empty($file_data)) + { + $system_config = empty($system_config) ? $file_data : array_merge2($system_config, $file_data); + } + + } + return $system_config; + } +} diff --git a/niucloud/core/core/dict/Console.php b/niucloud/core/core/dict/Console.php new file mode 100644 index 00000000..3fed813d --- /dev/null +++ b/niucloud/core/core/dict/Console.php @@ -0,0 +1,45 @@ +getAllLocalAddons(); + $console_files = []; + + foreach ($addons as $v) { + $console_path = $this->getAddonAppPath($v) . "/config/console.php"; + if (is_file($console_path)) { + $console_files[] = $console_path; + } + } + $files_data = $this->loadFiles($console_files); + + + $console = $data; + foreach ($files_data as $file_data) { + if(!empty($file_data)) + { + $console = empty($console) ? $file_data : array_merge2($console, $file_data); + } + + } + return $console; + } +} diff --git a/niucloud/core/core/dict/DictLoader.php b/niucloud/core/core/dict/DictLoader.php new file mode 100644 index 00000000..8e3e5232 --- /dev/null +++ b/niucloud/core/core/dict/DictLoader.php @@ -0,0 +1,41 @@ +getLocalAddons(); + $components_files = []; + + foreach ($addons as $v) { + $components_path = $this->getAddonDictPath($v) . "diy_form" . DIRECTORY_SEPARATOR . "components.php"; + if (is_file($components_path)) { + $components_files[] = $components_path; + } + } + $components_files_data = $this->loadFiles($components_files); + $components = $data; + foreach ($components_files_data as $file_data) { + $components = empty($components) ? $file_data : array_merge2($components, $file_data); + } + return $components; + } +} diff --git a/niucloud/core/core/dict/DiyFormTemplate.php b/niucloud/core/core/dict/DiyFormTemplate.php new file mode 100644 index 00000000..5ac2e130 --- /dev/null +++ b/niucloud/core/core/dict/DiyFormTemplate.php @@ -0,0 +1,38 @@ +getLocalAddons(); + $components_files = []; + + foreach ($addons as $v) { + $components_path = $this->getAddonDictPath($v) . "diy_form" . DIRECTORY_SEPARATOR . "template.php"; + if (is_file($components_path)) { + $components_files[] = $components_path; + } + } + $components_files_data = $this->loadFiles($components_files); + $components = $data; + foreach ($components_files_data as $file_data) { + $components = empty($components) ? $file_data : array_merge2($components, $file_data); + } + return $components; + } +} diff --git a/niucloud/core/core/dict/DiyFormType.php b/niucloud/core/core/dict/DiyFormType.php new file mode 100644 index 00000000..7b0caab5 --- /dev/null +++ b/niucloud/core/core/dict/DiyFormType.php @@ -0,0 +1,38 @@ +getLocalAddons(); + $components_files = []; + + foreach ($addons as $v) { + $components_path = $this->getAddonDictPath($v) . "diy_form" . DIRECTORY_SEPARATOR . "type.php"; + if (is_file($components_path)) { + $components_files[] = $components_path; + } + } + $components_files_data = $this->loadFiles($components_files); + $components = $data; + foreach ($components_files_data as $file_data) { + $components = empty($components) ? $file_data : array_merge2($components, $file_data); + } + return $components; + } +} diff --git a/niucloud/core/core/dict/Event.php b/niucloud/core/core/dict/Event.php new file mode 100644 index 00000000..e9eb7d07 --- /dev/null +++ b/niucloud/core/core/dict/Event.php @@ -0,0 +1,42 @@ +getLocalAddons(); + $event_files = []; + + foreach ($addons as $v) { + $event_path = $this->getAddonAppPath($v) . "event.php"; + if (is_file($event_path)) { + $event_files[] = $event_path; + } + } + $files_data = $this->loadFiles($event_files); + + $files_data[1] = $data; + + $events = []; + foreach ($files_data as $file_data) { + $events = empty($events) ? $file_data : array_merge2($events, $file_data); + } + return $events; + } +} diff --git a/niucloud/core/core/dict/GrowthRule.php b/niucloud/core/core/dict/GrowthRule.php new file mode 100644 index 00000000..44faa3b3 --- /dev/null +++ b/niucloud/core/core/dict/GrowthRule.php @@ -0,0 +1,45 @@ +getLocalAddons(); + $account_change_type_files = []; + $system_change_type_file = $this->getDictPath() . "member" . DIRECTORY_SEPARATOR . "growth_rule.php"; + + + if (is_file($system_change_type_file)) { + $account_change_type_files[] = $system_change_type_file; + } + foreach ($addons as $v) { + $addon_change_type_file = $this->getAddonDictPath($v) . "member" . DIRECTORY_SEPARATOR . "growth_rule.php"; + if (is_file($addon_change_type_file)) { + $account_change_type_files[] = $addon_change_type_file; + } + } + + $account_change_type_datas = $this->loadFiles($account_change_type_files); + + $account_change_type_array = []; + foreach ($account_change_type_datas as $account_change_type_data) { + $account_change_type_array = empty($account_change_type_array) ? $account_change_type_data : array_merge2($account_change_type_array, $account_change_type_data); + } + return $account_change_type_array; + } +} diff --git a/niucloud/core/core/dict/Icon.php b/niucloud/core/core/dict/Icon.php new file mode 100644 index 00000000..499d14f2 --- /dev/null +++ b/niucloud/core/core/dict/Icon.php @@ -0,0 +1,50 @@ +getRootPath()) . str_replace('/', DIRECTORY_SEPARATOR, '/admin/src/styles/icon'); + $file_arr = getFileMap($sys_path); + $icon_arr = []; + if (!empty($file_arr)) { + foreach ($file_arr as $ck => $cv) { + if (str_contains($cv, '.json')) { + $json_string = file_get_contents($ck); + $icon = json_decode($json_string, true, 512, JSON_THROW_ON_ERROR); + $icon_arr[] = $icon; + } + } + } + + if (count($icon_arr) > 1) { + $last_icon = array_pop($icon_arr); // 最后一个 + $first_icon = array_shift($icon_arr); // 第一个 + + array_unshift($icon_arr, $last_icon); // 将系统图标放到第一位置 + $icon_arr[] = $first_icon; // 交换位置 + } + + return $icon_arr; + } +} diff --git a/niucloud/core/core/dict/Lang.php b/niucloud/core/core/dict/Lang.php new file mode 100644 index 00000000..40a4a0fc --- /dev/null +++ b/niucloud/core/core/dict/Lang.php @@ -0,0 +1,56 @@ +getLocalAddons(); + $system_lang_path = $this->getAppPath() . "lang" . DIRECTORY_SEPARATOR . $data['lang_type'] . DIRECTORY_SEPARATOR; + $lang_files = [ + $system_lang_path . "api.php", + $system_lang_path . "dict.php", + $system_lang_path . "validate.php", + ]; + + + foreach ($addons as $v) { + $lang_path = $this->getAddonAppPath($v) . "lang" . DIRECTORY_SEPARATOR . $data['lang_type'] . DIRECTORY_SEPARATOR; + + $api_path = $lang_path . "api.php"; + $dict_path = $lang_path . "dict.php"; + $validate_path = $lang_path . "validate.php"; + if (is_file($api_path)) { + $lang_files[] = $api_path; + + } + if (is_file($dict_path)) { + $lang_files[] = $dict_path; + } + if (is_file($validate_path)) { + $lang_files[] = $validate_path; + } + } + $files_data = $this->loadFiles($lang_files); + $lang = []; + foreach ($files_data as $file_data) { + $lang = empty($lang) ? $file_data : array_merge2($lang, $file_data); + } + return $lang; + } +} diff --git a/niucloud/core/core/dict/MemberAccountChangeType.php b/niucloud/core/core/dict/MemberAccountChangeType.php new file mode 100644 index 00000000..c7cf0ce8 --- /dev/null +++ b/niucloud/core/core/dict/MemberAccountChangeType.php @@ -0,0 +1,46 @@ +getLocalAddons(); + $account_change_type_files = []; + $system_change_type_file = $this->getDictPath() . "member" . DIRECTORY_SEPARATOR . "account_change_type.php"; + + + if (is_file($system_change_type_file)) { + $account_change_type_files[] = $system_change_type_file; + } + foreach ($addons as $v) { + $addon_change_type_file = $this->getAddonDictPath($v) . "member" . DIRECTORY_SEPARATOR . "account_change_type.php"; + if (is_file($addon_change_type_file)) { + $account_change_type_files[] = $addon_change_type_file; + } + } + + $account_change_type_datas = $this->loadFiles($account_change_type_files); + + $account_change_type_array = []; + foreach ($account_change_type_datas as $account_change_type_data) { + $account_change_type_array = empty($account_change_type_array) ? $account_change_type_data : array_merge2($account_change_type_array, $account_change_type_data); + } + return $account_change_type_array; + } +} diff --git a/niucloud/core/core/dict/MemberBenefits.php b/niucloud/core/core/dict/MemberBenefits.php new file mode 100644 index 00000000..c22581fc --- /dev/null +++ b/niucloud/core/core/dict/MemberBenefits.php @@ -0,0 +1,45 @@ +getLocalAddons(); + $account_change_type_files = []; + $system_change_type_file = $this->getDictPath() . "member" . DIRECTORY_SEPARATOR . "benefits.php"; + + + if (is_file($system_change_type_file)) { + $account_change_type_files[] = $system_change_type_file; + } + foreach ($addons as $v) { + $addon_change_type_file = $this->getAddonDictPath($v) . "member" . DIRECTORY_SEPARATOR . "benefits.php"; + if (is_file($addon_change_type_file)) { + $account_change_type_files[] = $addon_change_type_file; + } + } + + $account_change_type_datas = $this->loadFiles($account_change_type_files); + + $account_change_type_array = []; + foreach ($account_change_type_datas as $account_change_type_data) { + $account_change_type_array = empty($account_change_type_array) ? $account_change_type_data : array_merge2($account_change_type_array, $account_change_type_data); + } + return $account_change_type_array; + } +} diff --git a/niucloud/core/core/dict/MemberGift.php b/niucloud/core/core/dict/MemberGift.php new file mode 100644 index 00000000..1c8284fe --- /dev/null +++ b/niucloud/core/core/dict/MemberGift.php @@ -0,0 +1,45 @@ +getLocalAddons(); + $account_change_type_files = []; + $system_change_type_file = $this->getDictPath() . "member" . DIRECTORY_SEPARATOR . "gift.php"; + + + if (is_file($system_change_type_file)) { + $account_change_type_files[] = $system_change_type_file; + } + foreach ($addons as $v) { + $addon_change_type_file = $this->getAddonDictPath($v) . "member" . DIRECTORY_SEPARATOR . "gift.php"; + if (is_file($addon_change_type_file)) { + $account_change_type_files[] = $addon_change_type_file; + } + } + + $account_change_type_datas = $this->loadFiles($account_change_type_files); + + $account_change_type_array = []; + foreach ($account_change_type_datas as $account_change_type_data) { + $account_change_type_array = empty($account_change_type_array) ? $account_change_type_data : array_merge2($account_change_type_array, $account_change_type_data); + } + return $account_change_type_array; + } +} diff --git a/niucloud/core/core/dict/Menu.php b/niucloud/core/core/dict/Menu.php new file mode 100644 index 00000000..519ccf2b --- /dev/null +++ b/niucloud/core/core/dict/Menu.php @@ -0,0 +1,29 @@ +getAddonDictPath($data['addon']) . "menu" . DIRECTORY_SEPARATOR . $data['app_type'] . ".php"; + if (is_file($menu_path)) { + return include $menu_path; + } + return []; + } +} diff --git a/niucloud/core/core/dict/Notice.php b/niucloud/core/core/dict/Notice.php new file mode 100644 index 00000000..64f5a14e --- /dev/null +++ b/niucloud/core/core/dict/Notice.php @@ -0,0 +1,43 @@ +getDictPath() . "notice" . DIRECTORY_SEPARATOR . $data[ 'type' ] . ".php"; + if (is_file($system_path)) { + $template_files[] = $system_path; + } + $addons = $this->getLocalAddons(); + foreach ($addons as $v) { + $template_path = $this->getAddonDictPath($v) . "notice" . DIRECTORY_SEPARATOR . $data[ 'type' ] . ".php"; + if (is_file($template_path)) { + $template_files[] = $template_path; + } + } + $template_files_data = $this->loadFiles($template_files); + + $template_data_array = []; + foreach ($template_files_data as $file_data) { + $template_data_array = empty($template_data_array) ? $file_data : array_merge($template_data_array, $file_data); + } + return $template_data_array; + } +} diff --git a/niucloud/core/core/dict/PackageGift.php b/niucloud/core/core/dict/PackageGift.php new file mode 100644 index 00000000..f790da46 --- /dev/null +++ b/niucloud/core/core/dict/PackageGift.php @@ -0,0 +1 @@ +// | 官方网址:https://www.niucloud.com diff --git a/niucloud/core/core/dict/PointRule.php b/niucloud/core/core/dict/PointRule.php new file mode 100644 index 00000000..cdfad3ef --- /dev/null +++ b/niucloud/core/core/dict/PointRule.php @@ -0,0 +1,45 @@ +getLocalAddons(); + $account_change_type_files = []; + $system_change_type_file = $this->getDictPath() . "member" . DIRECTORY_SEPARATOR . "point_rule.php"; + + + if (is_file($system_change_type_file)) { + $account_change_type_files[] = $system_change_type_file; + } + foreach ($addons as $v) { + $addon_change_type_file = $this->getAddonDictPath($v) . "member" . DIRECTORY_SEPARATOR . "point_rule.php"; + if (is_file($addon_change_type_file)) { + $account_change_type_files[] = $addon_change_type_file; + } + } + + $account_change_type_datas = $this->loadFiles($account_change_type_files); + + $account_change_type_array = []; + foreach ($account_change_type_datas as $account_change_type_data) { + $account_change_type_array = empty($account_change_type_array) ? $account_change_type_data : array_merge2($account_change_type_array, $account_change_type_data); + } + return $account_change_type_array; + } +} diff --git a/niucloud/core/core/dict/Poster.php b/niucloud/core/core/dict/Poster.php new file mode 100644 index 00000000..1e6177af --- /dev/null +++ b/niucloud/core/core/dict/Poster.php @@ -0,0 +1,95 @@ +getDictPath() . 'poster' . DIRECTORY_SEPARATOR . 'template.php'; + if (is_file($system_path)) { + $schedule_files[] = $system_path; + } + $addons = $this->getLocalAddons(); + foreach ($addons as $v) { + $addon_path = $this->getAddonDictPath($v) . 'poster' . DIRECTORY_SEPARATOR . 'template.php'; + if (is_file($addon_path)) { + $schedule_files[] = $addon_path; + } + } + } else { + $schedule_files = []; + if ($addon == 'system') { + $system_path = $this->getDictPath() . 'poster' . DIRECTORY_SEPARATOR . 'template.php'; + if (is_file($system_path)) { + $schedule_files[] = $system_path; + } + } else { + $addon_path = $this->getAddonDictPath($addon) . 'poster' . DIRECTORY_SEPARATOR . 'template.php'; + if (is_file($addon_path)) { + $schedule_files[] = $addon_path; + } + } + + } + + $schedule_files_data = $this->loadFiles($schedule_files); + $schedule_data_array = []; + foreach ($schedule_files_data as $file_data) { + $schedule_data_array = empty($schedule_data_array) ? $file_data : array_merge($schedule_data_array, $file_data); + } + + if (!empty($type)) { + foreach ($schedule_data_array as $k => $v) { + if ($v[ 'type' ] != $type) { + unset($schedule_data_array[ $k ]); + } + } + $schedule_data_array = array_values($schedule_data_array); + } + return $schedule_data_array; + + } + + /** + * 获取海报组件 + * @param array $data + * @return array|mixed + */ + public function loadComponents(array $data = []) + { + $addons = $this->getLocalAddons(); + $components_files = []; + foreach ($addons as $v) { + $components_path = $this->getAddonDictPath($v) . "poster" . DIRECTORY_SEPARATOR . "components.php"; + if (is_file($components_path)) { + $components_files[] = $components_path; + } + } + $components_files_data = $this->loadFiles($components_files); + $components = $data; + foreach ($components_files_data as $file_data) { + $components = empty($components) ? $file_data : array_merge2($components, $file_data); + } + return $components; + + } +} diff --git a/niucloud/core/core/dict/Printer.php b/niucloud/core/core/dict/Printer.php new file mode 100644 index 00000000..6e209edc --- /dev/null +++ b/niucloud/core/core/dict/Printer.php @@ -0,0 +1,40 @@ +getLocalAddons(); + $types_files = []; + + foreach ($addons as $v) { + $types_path = $this->getAddonDictPath($v) . "printer" . DIRECTORY_SEPARATOR . "type.php"; + if (is_file($types_path)) { + $types_files[] = $types_path; + } + } + $types_files_data = $this->loadFiles($types_files); + $types = $data; + foreach ($types_files_data as $file_data) { + $types = empty($types) ? $file_data : array_merge2($types, $file_data); + } + return $types; + } +} diff --git a/niucloud/core/core/dict/RechargeGift.php b/niucloud/core/core/dict/RechargeGift.php new file mode 100644 index 00000000..f3f1a78b --- /dev/null +++ b/niucloud/core/core/dict/RechargeGift.php @@ -0,0 +1,43 @@ +getLocalAddons(); + foreach ($addons as $v) { + $addon_change_type_file = $this->getAddonDictPath($v) . "recharge" . DIRECTORY_SEPARATOR . "package_gift.php"; + if (is_file($addon_change_type_file)) { + $account_change_type_files[] = $addon_change_type_file; + } + } + $account_change_type_datas = $this->loadFiles($account_change_type_files); + $account_change_type_array = []; + foreach ($account_change_type_datas as $account_change_type_data) { + $account_change_type_array = empty($account_change_type_array) ? $account_change_type_data : array_merge2($account_change_type_array, $account_change_type_data); + } + foreach ($account_change_type_array as $key => &$value) { + $value[ 'key' ] = $key; + } + usort($account_change_type_array, function($list_one, $list_two) { + return $list_one[ 'sort' ] <=> $list_two[ 'sort' ]; + }); + return $account_change_type_array; + + } +} diff --git a/niucloud/core/core/dict/Route.php b/niucloud/core/core/dict/Route.php new file mode 100644 index 00000000..b74d8941 --- /dev/null +++ b/niucloud/core/core/dict/Route.php @@ -0,0 +1,33 @@ +getLocalAddons(); + + foreach ($addons as $k => $v) { + $route_path = $this->getAddonAppPath($v) . DIRECTORY_SEPARATOR . $data['app_type'] . DIRECTORY_SEPARATOR . "route" . DIRECTORY_SEPARATOR . "route.php"; + if (is_file($route_path)) { + include $route_path; + } + } + return true; + } +} diff --git a/niucloud/core/core/dict/Schedule.php b/niucloud/core/core/dict/Schedule.php new file mode 100644 index 00000000..eb824c58 --- /dev/null +++ b/niucloud/core/core/dict/Schedule.php @@ -0,0 +1,60 @@ +getDictPath() . 'schedule' . DIRECTORY_SEPARATOR . 'schedule.php'; + if (is_file($system_path)) { + $schedule_files[] = $system_path; + } + $addons = $this->getLocalAddons(); + foreach ($addons as $v) { + $addon_path = $this->getAddonDictPath($v) . 'schedule' . DIRECTORY_SEPARATOR . 'schedule.php'; + if (is_file($addon_path)) { + $schedule_files[] = $addon_path; + } + } + } else { + $schedule_files = []; + if ($addon == 'system') { + $system_path = $this->getDictPath() . 'schedule' . DIRECTORY_SEPARATOR . 'schedule.php'; + if (is_file($system_path)) { + $schedule_files[] = $system_path; + } + } else { + $addon_path = $this->getAddonDictPath($addon) . 'schedule' . DIRECTORY_SEPARATOR . 'schedule.php'; + if (is_file($addon_path)) { + $schedule_files[] = $addon_path; + } + } + + } + $schedule_files_data = $this->loadFiles($schedule_files); + $schedule_data_array = []; + foreach ($schedule_files_data as $file_data) { + $schedule_data_array = empty($schedule_data_array) ? $file_data : array_merge($schedule_data_array, $file_data); + } + return $schedule_data_array; + + } +} diff --git a/niucloud/core/core/dict/UniappComponent.php b/niucloud/core/core/dict/UniappComponent.php new file mode 100644 index 00000000..669b6c91 --- /dev/null +++ b/niucloud/core/core/dict/UniappComponent.php @@ -0,0 +1,38 @@ +getLocalAddons(); + $components_files = []; + foreach ($addons as $v) { + $components_path = $this->getAddonDictPath($v) . "diy" . DIRECTORY_SEPARATOR . "components.php"; + if (is_file($components_path)) { + $components_files[] = $components_path; + } + } + $components_files_data = $this->loadFiles($components_files); + $components = $data; + foreach ($components_files_data as $file_data) { + $components = empty($components) ? $file_data : array_merge2($components, $file_data); + } + return $components; + } +} diff --git a/niucloud/core/core/dict/UniappLink.php b/niucloud/core/core/dict/UniappLink.php new file mode 100644 index 00000000..e2aca6a7 --- /dev/null +++ b/niucloud/core/core/dict/UniappLink.php @@ -0,0 +1,75 @@ +getLocalAddons(); + } + + $link_files = []; + + foreach ($addons as $v) { + $link_path = $this->getAddonDictPath($v) . "diy" . DIRECTORY_SEPARATOR . "links.php"; + if (is_file($link_path)) { + $link_files[ $v ] = $link_path; + } + } + + $addon_service = new AddonService(); + $addon_info_list = $addon_service->getAddonListByKeys(array_keys($link_files)); + + if (!empty($params[ 'params' ][ 'query' ]) && $params[ 'params' ][ 'query' ] == 'addon') { + $list_key = array_column($addon_info_list, 'key'); + $addon_info_list = array_combine($list_key, $addon_info_list); + return $addon_info_list; + } else { + + $links = $params[ 'data' ]; + + foreach ($link_files as $k => $v) { + $addon_link = include $v; + if (!empty($addon_link)) { + $addon_info = []; + foreach ($addon_info_list as $ck => $cv) { + if ($cv[ 'key' ] == $k) { + $addon_info = $cv; + break; + } + } + + foreach ($addon_link as $ck => $cv) { + $addon_link[ $ck ][ 'addon_info' ] = $addon_info; + } + $links = array_merge($links, $addon_link); + } + } + + return $links; + } + } +} diff --git a/niucloud/core/core/dict/UniappPages.php b/niucloud/core/core/dict/UniappPages.php new file mode 100644 index 00000000..bb154cb3 --- /dev/null +++ b/niucloud/core/core/dict/UniappPages.php @@ -0,0 +1,52 @@ +getLocalAddons(); + } + + $page_files = []; + foreach ($addons as $v) { + $page_path = $this->getAddonDictPath($v) . "diy" . DIRECTORY_SEPARATOR . "pages.php"; + if (is_file($page_path)) { + $page_files[] = $page_path; + } + } + $page_files_data = $this->loadFiles($page_files); + if (!empty($data[ 'addon' ])) { + $pages = []; + } else { + $pages = $data; + } + foreach ($page_files_data as $file_data) { + if (empty($pages)) { + $pages = $file_data; + } else { + $pages = array_merge2($pages, $file_data); + } + } + return $pages; + } +} diff --git a/niucloud/core/core/dict/UniappTemplate.php b/niucloud/core/core/dict/UniappTemplate.php new file mode 100644 index 00000000..6dab6e05 --- /dev/null +++ b/niucloud/core/core/dict/UniappTemplate.php @@ -0,0 +1,95 @@ +getLocalAddons(); + } + + $app_keys = []; // 应用插件key集合 + $apps = []; // 应用插件集合 + $page_files = []; // 模板页面文件集合 + + // 筛选插件 + if (!empty($params[ 'params' ]) && !empty($params[ 'params' ][ 'addon' ])) { + $is_pass = true; + foreach ($addons as $k => $v) { + if ($params[ 'params' ][ 'addon' ] == $v) { + $addons = [ $v ]; + $is_pass = false; + break; + } + } + + // 如果没有匹配到,则返回系统的 + if ($is_pass) { + return $params[ 'data' ]; + } + } + + foreach ($addons as $v) { + $page_path = $this->getAddonDictPath($v) . "diy" . DIRECTORY_SEPARATOR . "template.php"; + if (is_file($page_path)) { + if (!empty($params[ 'params' ][ 'query' ]) && $params[ 'params' ][ 'query' ] == 'addon') { + $file = include $page_path; + if (!empty($file)) { + $app_keys[] = $v; + $apps[ $v ] = $file; + } + } else { + $page_files[] = $page_path; + } + } + } + + // 查询存在模板页面的应用插件列表 + if (!empty($params[ 'params' ][ 'query' ]) && $params[ 'params' ][ 'query' ] == 'addon') { + $addon_service = new AddonService(); + $list = $addon_service->getAddonListByKeys($app_keys); + $list_key = array_column($list, 'key'); + $list = array_combine($list_key, $list); + foreach ($list as $k => $v) { + $list[ $k ][ 'list' ] = $apps[ $k ]; + } + return $list; + } else { + // 查询应用插件下的模板页面数据 + $page_files_data = $this->loadFiles($page_files); + if (!empty($params[ 'params' ]) && !empty($params[ 'params' ][ 'addon' ])) { + $pages = []; + } else { + $pages = $params[ 'data' ]; + } + foreach ($page_files_data as $file_data) { + if (empty($pages)) { + $pages = $file_data; + } else { + $pages = array_merge($pages, $file_data); + } + } + return $pages; + } + } +} diff --git a/niucloud/core/core/dict/WebLink.php b/niucloud/core/core/dict/WebLink.php new file mode 100644 index 00000000..da09ff00 --- /dev/null +++ b/niucloud/core/core/dict/WebLink.php @@ -0,0 +1,75 @@ +getLocalAddons(); + } + + $link_files = []; + + foreach ($addons as $v) { + $link_path = $this->getAddonDictPath($v) . "web" . DIRECTORY_SEPARATOR . "web_links.php"; + if (is_file($link_path)) { + $link_files[ $v ] = $link_path; + } + } + + $addon_service = new AddonService(); + $addon_info_list = $addon_service->getAddonListByKeys(array_keys($link_files)); + + if (!empty($params[ 'params' ][ 'query' ]) && $params[ 'params' ][ 'query' ] == 'addon') { + $list_key = array_column($addon_info_list, 'key'); + $addon_info_list = array_combine($list_key, $addon_info_list); + return $addon_info_list; + } else { + + $links = $params[ 'data' ]; + + foreach ($link_files as $k => $v) { + $addon_link = include $v; + if (!empty($addon_link)) { + $addon_info = []; + foreach ($addon_info_list as $ck => $cv) { + if ($cv[ 'key' ] == $k) { + $addon_info = $cv; + break; + } + } + + foreach ($addon_link as $ck => $cv) { + $addon_link[ $ck ][ 'addon_info' ] = $addon_info; + } + $links = array_merge($links, $addon_link); + } + } + + return $links; + } + } +} diff --git a/niucloud/core/core/exception/AddonException.php b/niucloud/core/core/exception/AddonException.php new file mode 100644 index 00000000..34a08521 --- /dev/null +++ b/niucloud/core/core/exception/AddonException.php @@ -0,0 +1,17 @@ +job($class)->secs($secs); + if (is_array($action)) { + $queue->data(...$action); + } else if (is_string($action)) { + $queue->method($action)->data(...$data); + } + if ($queue_name) { + $queue->setQueueName($queue_name); + } + return $queue->push(); + } else { + if($secs == 0){ + $class_name = '\\' . $class; + $res = new $class_name(); + if (is_array($action)) { + return $res->doJob(...$action); + } else { + return $res->$action(...$data); + } + } + } + } +} diff --git a/niucloud/core/core/loader/Loader.php b/niucloud/core/core/loader/Loader.php new file mode 100644 index 00000000..e3403f6b --- /dev/null +++ b/niucloud/core/core/loader/Loader.php @@ -0,0 +1,118 @@ +name = $name; + } + $this->config = $config; + } + + /** + * 获取默认驱动 + * @return mixed + */ + abstract protected function getDefault(); + + /** + * 创建实例对象 + * @param string $type + * @return object|DbManager + * @throws Exception + */ + public function create(string $type) + { + $class = $this->getClass($type); + return self::createFacade($class, [ + $this->name, + $this->config, + $this->config_file + ], true); + } + + /** + * 获取类 + * @param string $type + * @return mixed|string + * @throws Exception + */ + public function getClass(string $type) + { + $class = config($this->config_name . '.drivers.' . $type . '.driver'); + if (!empty($class) && class_exists($class)) { + return $class; + } else { + if ($this->namespace || str_contains($type, '\\')) { + $class = str_contains($type, '\\') ? $type : $this->namespace . $type; + if (class_exists($class)) { + return $class; + } else { + $class = str_contains($type, '\\') ? $type : $this->namespace . Str::studly($type); + if (class_exists($class)) { + return $class; + } + } + } + } + throw new Exception("Driver [$type] not supported."); + } + + /** + * 通过装载器获取实例 + * @return object|DbManager + * @throws Exception + */ + public function getLoader() + { + + if (empty($this->class)) { + $this->name = $this->name ?: $this->getDefault(); + if (!$this->name) { + throw new Exception(sprintf( + 'could not find driver [%s].', static::class + )); + } + $this->class = $this->create($this->name); + } + return $this->class; + } + + /** + * 动态调用 + * @param $method + * @param $arguments + * @return mixed + * @throws Exception + */ + public function __call($method, $arguments) + { + return $this->getLoader()->{$method}(...$arguments); + } + +} \ No newline at end of file diff --git a/niucloud/core/core/loader/Storage.php b/niucloud/core/core/loader/Storage.php new file mode 100644 index 00000000..50aea02b --- /dev/null +++ b/niucloud/core/core/loader/Storage.php @@ -0,0 +1,69 @@ +name = $name; + $this->config_file = $config_file; + $this->initialize($config); + } + + /** + * 设置错误信息 + * @param string|null $error + * @return bool + */ + protected function setError(?string $error = null) + { + $this->error = $error; + return false; + } + + /** + * 获取错误信息 + * @return string + */ + public function getError() + { + $error = $this->error; + $this->error = null; + return $error; + } + + /** + * 初始化 + * @param array $config + * @return mixed + */ + abstract protected function initialize(array $config); + +} diff --git a/niucloud/core/core/oauth/BaseOauth.php b/niucloud/core/core/oauth/BaseOauth.php new file mode 100644 index 00000000..8c536023 --- /dev/null +++ b/niucloud/core/core/oauth/BaseOauth.php @@ -0,0 +1,42 @@ +oauth; + } + + public function oauth(string $code = null, array $options = []) + { +// $this->instance()-> + // TODO: Implement oauth() method. + } +} diff --git a/niucloud/core/core/pay/Alipay.php b/niucloud/core/core/pay/Alipay.php new file mode 100644 index 00000000..0368a330 --- /dev/null +++ b/niucloud/core/core/pay/Alipay.php @@ -0,0 +1,389 @@ +config = $this->payConfig($config, 'alipay'); + Pay::config($this->config); + } + + public function mp(array $params) + { + + } + + /** + * 网页支付 + * @param array $params + * @return array + */ + public function web(array $params) + { + return $this->returnFormat(Pay::alipay()->web([ + 'out_trade_no' => $params['out_trade_no'], + 'total_amount' => $params['money'], + 'subject' => $params['body'], + '_method' => 'get', + ])); + } + + /** + * 手机网页支付 + * @param array $params + * @return array + */ + public function wap(array $params) + { + $response = Pay::alipay()->h5([ + 'out_trade_no' => $params['out_trade_no'], + 'total_amount' => $params['money'], + 'subject' => $params['body'], + 'quit_url' => $params['quit_url'] ?? '',//用户付款中途退出返回商户网站的地址, 一般是商品详情页或购物车页 + '_method' => 'get', + ]); + + $redirects = $response->getHeader('Location'); + $effective_url = end($redirects); + return ['url' => $effective_url]; + } + + /** + * app支付 + * @param array $params + * @return array + */ + public function app(array $params) + + { + return $this->returnFormat(Pay::alipay()->app([ + 'out_trade_no' => $params['out_trade_no'], + 'total_amount' => $params['money'], + 'subject' => $params['body'],//用户付款中途退出返回商户网站的地址, 一般是商品详情页或购物车页 + ])); + } + + /** + * 小程序支付 + * @param array $params + * @return Collection + */ + public function mini(array $params) + { + return Pay::alipay()->mini([ + 'out_trade_no' => $params['out_trade_no'], + 'total_amount' => $params['money'], + 'subject' => $params['body'], + 'buyer_id' => $params['buyer_id'],//买家支付宝用户ID 注:交易的买家与卖家不能相同。 + ]); + } + + /** + * 付款码支付 + * @param array $params + * @return Collection + */ + public function pos(array $params) + { + return Pay::alipay()->pos([ + 'out_trade_no' => $params['out_trade_no'], + 'auth_code' => $params['auth_code'],//付授权码。 当面付场景传买家的付款码(25~30开头的长度为16~24位的数字,实际字符串长度以开发者获取的付款码长度为准)或者刷脸标识串(fp开头的35位字符串)。 + 'total_amount' => $params['money'], + 'subject' => $params['body'], + ]); + } + + /** + * 扫码支付 + * @param array $params + * @return Collection + */ + public function scan(array $params) + { + return Pay::alipay()->scan([ + 'out_trade_no' => $params['out_trade_no'], + 'total_amount' => $params['money'], + 'subject' => $params['body'], + ]); + } + + /** + * 转账 + * @param array $params + * @return array + */ + public function transfer(array $params) + { + + $result = $this->returnFormat(Pay::alipay()->transfer([ + 'out_biz_no' => $params['transfer_no'], + 'trans_amount' => $params['money'], + 'product_code' => $params['product_code'] ?: 'TRANS_ACCOUNT_NO_PWD',//业务产品码,单笔无密转账到支付宝账户固定为 : TRANS_ACCOUNT_NO_PWD; 收发现金红包固定为 : STD_RED_PACKET; + 'biz_scene' => $params['scene'] ?: 'DIRECT_TRANSFER',//描述特定的业务场景,可传的参数如下:DIRECT_TRANSFER:单笔无密转账到支付宝,B2C现金红包;PERSONAL_COLLECTION:C2C现金红包-领红包 + 'payee_info' => [//收款方信息 + 'identity' => $params['to_no'],//参与方的唯一标识 + 'identity_type' => $params['to_type'] ?: 'ALIPAY_LOGON_ID',//参与方的标识类型,目前支持如下类型:1、ALIPAY_USER_ID 支付宝的会员ID2、ALIPAY_LOGON_ID:支付宝登录号,支持邮箱和手机号格式3、ALIPAY_OPEN_ID:支付宝openid + 'name' => $params['to_name'],//参与方真实姓名,如果非空,将校验收款支付宝账号姓名一致性。当identity_type=ALIPAY_LOGON_ID时,本字段必填。 + ], + ])); + if (!empty($result['msg']) && $result['msg'] != 'Success') { + throw new PayException($result['sub_msg']); + } else { + $status = $result['status']; + $status_array = [ + 'SUCCESS' => TransferDict::SUCCESS, + 'WAIT_PAY' => TransferDict::WAIT, + 'CLOSED' => TransferDict::FAIL, + 'FAIL' => TransferDict::FAIL + ]; + $res = [ + 'status' => $status_array[$status], + ]; + if ($status == 'FAIL') { + $res['fail_reason'] = $result['fail_reason']; + } + } + return $res; + } + + /** + * 支付关闭 + * @param string $out_trade_no + * @return bool + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException + */ + public function close(string $out_trade_no) + { + $result = $this->returnFormat(Pay::alipay()->close([ + 'out_trade_no' => $out_trade_no, + ])); + //todo 支付宝关闭异步回调 + if (isset($result['sub_code']) && in_array($result['sub_code'], ['ACQ.REASON_ILLEGAL_STATUS', 'ACQ.REASON_TRADE_STATUS_INVALID', 'ACQ.TRADE_NOT_EXIST', 'ACQ.TRADE_STATUS_ERROR'])) { + return true; + } + if (!empty($result['msg']) && $result['msg'] == 'Success') { + return true; + } else { + return false; + } + } + + /** + * 退款 + * @param array $params + * @return array|false + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException + */ + public function refund(array $params) + { + $out_trade_no = $params['out_trade_no']; + $money = $params['money']; +// $total = $params['total']; + $refund_no = $params['refund_no']; + $result = $this->returnFormat(Pay::alipay()->refund([ + 'out_trade_no' => $out_trade_no, + 'refund_amount' => $money, + 'out_request_no' => $refund_no + ])); + if (!empty($result['msg']) && $result['msg'] == 'Success') { + $fund_change = $result['fund_change'];//退款是否成功可以根据同步响应的 fund_change 参数来判断,fund_change 表示本次退款是否发生了资金变化,返回 Y 表示退款成功,返回 N 则表示本次退款未发生资金变动 。 + if ($fund_change == 'Y') { + $status = RefundDict::SUCCESS; + } else { + $status = RefundDict::DEALING; + } + return [ + 'status' => $status, + 'refund_no' => $refund_no, + 'out_trade_no' => $out_trade_no + ]; + } else { + //todo 这儿可以抛出错误 + return false; + } + } + + + /** + * 支部异步回调 + * @param string $action + * @param callable $callback + * @return ResponseInterface|string + */ + public function notify(string $action, callable $callback) + { + try { + $result = Pay::alipay()->callback(); + //通过返回的值 + if (!empty($result)) {//成功 + if ($action == 'pay') { + //todo 这儿需要具体设计 + $temp_data = array( + 'mchid' => $result['seller_id'], + 'trade_no' => $result['trade_no'], + 'result' => $result, + 'status' => OnlinePayDict::getAliPayStatus($result['trade_status']) + ); + $callback_result = $callback($result['out_trade_no'], $temp_data); + if (is_bool($callback_result) && $callback_result) { + return Pay::alipay()->success(); + } + } + + } + return $this->fail(); + } catch ( Throwable $e ) { + return $this->fail(); + } + + + } + + /** + * 查询普通支付订单 + * @param array $params + * @return array + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException + */ + public function getOrder(array $params = []) + { + $out_trade_no = $params['out_trade_no']; + $order = [ + 'out_trade_no' => $out_trade_no, + ]; + $result = $this->returnFormat(Pay::alipay()->query($order)); + if (!empty($result['msg']) && $result['msg'] == 'Success') { + return [ + 'status' => OnlinePayDict::getAliPayStatus($result['trade_status']) + ]; + } else { + if (!empty($result['sub_code']) && $result['sub_code'] == 'ACQ.ACQ.SYSTEM_ERROR') { + throw new PayException($result['msg']); + } else { + return []; + } + } + } + + /** + * 查询退款单据 + * @param string $out_trade_no + * @param string|null $refund_no + * @return array + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException + */ + public function getRefund(string $out_trade_no, ?string $refund_no) + { + $order = [ + 'out_trade_no' => $out_trade_no, + 'out_request_no' => $refund_no, + '_action' => 'refund', // 默认值,查询退款网页订单 + ]; + + $result = $this->returnFormat(Pay::alipay()->query($order)); + if (!empty($result['msg']) && $result['msg'] == 'Success') { + $refund_status = $result['refund_status'] ?? ''; + if ($refund_status == 'REFUND_SUCCESS') { + $status = RefundDict::SUCCESS; + } else { + $status = RefundDict::DEALING; + } + return [ + 'status' => $status, + 'refund_no' => $refund_no, + 'out_trade_no' => $out_trade_no + ]; + } else { + if (!empty($result['sub_code']) && $result['sub_code'] == 'ACQ.ACQ.SYSTEM_ERROR') { + throw new PayException($result['msg']); + } else { + return []; + } + } + } + + /** + * 获取转账订单 + * @param string $transfer_no + * @return array + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException + */ + public function getTransfer(string $transfer_no, $out_transfer_no = '') + { + $order = [ + 'out_biz_no' => $transfer_no, + '_action' => 'transfer' + ]; + $result = $this->returnFormat(Pay::alipay()->query($order)); + if (!empty($result['msg']) && $result['msg'] == 'Success') { + $status = $result['SUCCESS'] ?? ''; + $status_array = array( + 'SUCCESS' => TransferDict::SUCCESS, + 'WAIT_PAY' => TransferDict::WAIT, + 'CLOSED' => TransferDict::FAIL, + 'FAIL' => TransferDict::FAIL + ); + return [ + 'status' => $status_array[$status], + 'transfer_no' => $transfer_no + ]; + } else { + if (!empty($result['sub_code']) && $result['sub_code'] == 'ACQ.ACQ.SYSTEM_ERROR') { + throw new PayException($result['msg']); + } else { + return []; + } + } + } + + public function fail() + { + return 'fail'; + } + + public function returnUrl($params) + { + return ['url' => $params->getHeader('Location')[0] ?? '']; + } +} diff --git a/niucloud/core/core/pay/BasePay.php b/niucloud/core/core/pay/BasePay.php new file mode 100644 index 00000000..439d083f --- /dev/null +++ b/niucloud/core/core/pay/BasePay.php @@ -0,0 +1,203 @@ + [ + 'enable' => true, + 'file' => root_path('runtime') . 'paylog' . DIRECTORY_SEPARATOR . date('Ym') . DIRECTORY_SEPARATOR . date('d') . '.log', + 'level' => env('app_debug') ? 'debug' : 'info', // 建议生产环境等级调整为 info,开发环境为 debug + 'type' => 'single', // optional, 可选 daily. + 'max_file' => 30, // optional, 当 type 为 daily 时有效,默认 30 天 + ], + 'http' => [ // optional + 'timeout' => 5.0, + ] + ], + [ + $type => [ + 'default' => $config + ] + ], + ['_force' => true] + ); + } + + public function returnFormat($param) + { + if ($param instanceof MessageInterface || $param instanceof Response) { + $return_value = $param->getBody()->getContents(); + } else if ($param instanceof Collection) { + $return_value = $param->toArray(); + } else { + $return_value = $param; + } + return $return_value; + } + + /** + * 解析退款返回数据并解析 + * @param $our_trade_no + * @param $refund_no + * @param $status + * @param int $success_time + * @param string $reason + * @return array + */ + public function getRefundData($our_trade_no, $refund_no, $status, $success_time = 0, $reason = '') + { + return [ + 'our_trade_no' => $our_trade_no, + 'refund_no' => $refund_no, + 'status' => $status, + 'success_time' => $success_time, + 'reason' => $reason + ]; + } + + /** + * 获取转账数据并解析 + * @param $transfer_no + * @param $status + * @param $reason + * @return void + */ + public function getTransferData($transfer_no, $status, $reason) + { + + } + + +} diff --git a/niucloud/core/core/pay/PayLoader.php b/niucloud/core/core/pay/PayLoader.php new file mode 100644 index 00000000..b0c34ab6 --- /dev/null +++ b/niucloud/core/core/pay/PayLoader.php @@ -0,0 +1,42 @@ +config = $config; + $config['mch_secret_cert'] = url_to_path($config['mch_secret_cert'] ?? ''); + $config['mch_public_cert_path'] = url_to_path($config['mch_public_cert_path'] ?? ''); + // 选填-默认为正常模式。可选为: MODE_NORMAL, MODE_SERVICE + $config['mode'] = Pay::MODE_NORMAL; + if (!empty($config['wechat_public_cert_path']) && !empty($config['wechat_public_cert_id'])) { + $config['wechat_public_cert_path'] = [ + $config['wechat_public_cert_id'] => url_to_path($config['wechat_public_cert_path']) + ]; + } else { + unset($config['wechat_public_cert_path']); + unset($config['wechat_public_cert_id']); + } + Pay::config($this->payConfig($config, 'wechat')); + } + + + /** + * 公众号支付 + * @param array $params + * @return mixed|Collection + */ + public function mp(array $params) + { + try { + $result = $this->returnFormat(Pay::wechat()->mp([ + 'out_trade_no' => $params['out_trade_no'], + 'description' => $params['body'], + 'amount' => [ + 'total' => $params['money'], + ], + 'payer' => [ + 'openid' => $params['openid'], + ], + ])); + $code = $result['code'] ?? 0; + if ($code == 0) return $result; + //支付错误抛出 + throw new PayException($result['message']); + } catch (\Exception $e) { + if ($e instanceof InvalidResponseException) { + throw new PayException($e->response->all()['message'] ?? ''); + } + throw new PayException($e->getMessage()); + } + } + + /** + * 手机网页支付 + * @param array $params + * @return mixed + */ + public function wap(array $params) + { + try { + $order = [ + 'out_trade_no' => $params['out_trade_no'], + 'description' => $params['body'], + 'amount' => [ + 'total' => $params['money'], + ], + 'scene_info' => [ + 'payer_client_ip' => request()->ip(), + 'h5_info' => [ + 'type' => 'Wap', + ] + ], + ]; + //这儿有些特殊, 默认情况下,H5 支付所使用的 appid 是微信公众号的 appid,即配置文件中的 mp_app_id 参数,如果想使用关联的小程序的 appid,则只需要在调用参数中增加 ['_type' => 'mini'] 即可 + if (!empty($order['type'])) { + $order['_type'] = 'mini'; // 注意这一行 + } + return $this->returnFormat(Pay::wechat()->h5($order)); + } catch (\Exception $e) { + if ($e instanceof InvalidResponseException) { + throw new PayException($e->response->all()['message'] ?? ''); + } + throw new PayException($e->getMessage()); + } + } + + public function web(array $params) + { + + } + + /** + * app支付 + * @param array $params + * @return mixed|ResponseInterface + */ + public function app(array $params) + { + try { + return $this->returnFormat(Pay::wechat()->app([ + 'out_trade_no' => $params['out_trade_no'], + 'description' => $params['body'], + 'amount' => [ + 'total' => $params['money'], + ], + ])); + } catch (\Exception $e) { + if ($e instanceof InvalidResponseException) { + throw new PayException($e->response->all()['message'] ?? ''); + } + throw new PayException($e->getMessage()); + } + } + + /** + * 小程序支付 + * @param array $params + * @return mixed|ResponseInterface + */ + public function mini(array $params) + { + try { + return $this->returnFormat(Pay::wechat()->mini([ + 'out_trade_no' => $params['out_trade_no'], + 'description' => $params['body'], + 'amount' => [ + 'total' => $params['money'], + 'currency' => 'CNY',//一般是人民币 + ], + 'payer' => [ + 'openid' => $params['openid'], + ] + ])); + } catch (\Exception $e) { + if ($e instanceof InvalidResponseException) { + throw new PayException($e->response->all()['message'] ?? ''); + } + throw new PayException($e->getMessage()); + } + } + + /** + * 付款码支付 + * @param array $params + * @return mixed|Collection + */ + public function pos(array $params) + { + try { + $order = [ + 'out_trade_no' => $params['out_trade_no'], + 'body' => $params['body'], + 'total_fee' => $params['money'], + 'spbill_create_ip' => request()->ip(), + 'auth_code' => $params["auth_code"], + ]; + $result = Pay::wechat()->pos($order); + return $this->returnFormat($result); + } catch (\Exception $e) { + if ($e instanceof InvalidResponseException) { + throw new PayException($e->response->all()['message'] ?? ''); + } + throw new PayException($e->getMessage()); + } + } + + /** + * 扫码支付 + * @param array $params + * @return mixed|Collection + */ + public function scan(array $params) + { + try { + return $this->returnFormat(Pay::wechat()->scan([ + 'out_trade_no' => $params['out_trade_no'], + 'description' => $params['body'], + 'amount' => [ + 'total' => $params['money'], + ], + ])); + } catch (\Exception $e) { + if ($e instanceof InvalidResponseException) { + throw new PayException($e->response->all()['message'] ?? ''); + } + throw new PayException($e->getMessage()); + } + } + + /** + * 转账(微信的转账是很多笔的) + * @param array $params + * @return array + */ + public function transfer(array $params) + { + + $to_data = $params['to_no'];//收款人数据 + $channel = $to_data['channel'] ?? '';//渠道 + $open_id = $to_data['open_id'] ?? '';//openid + + if(empty($this->config['mch_id']) || empty($this->config['mch_secret_key']) || empty($this->config['mch_secret_cert']) || empty($this->config['mch_public_cert_path'])){ + throw new PayException('WECHAT_TRANSFER_CONFIG_NOT_EXIST'); + } + //这儿的批次信息可能是这儿生成的,但依然需要记录 + $order = [ + 'out_batch_no' => ($to_data['out_batch_no'] ?? '') . '',// + 'batch_name' => $params['remark'] ?? '', + 'batch_remark' => $params['remark'] ?? '', + ]; + if($channel == ChannelDict::WEAPP){ + $order['_type'] = 'mini'; + } + $transfer_list = $params['transfer_list']; + //单笔转账 + if (empty($transfer_list)) { + $transfer_list = [ + [ + 'transfer_no' => $params['transfer_no'], + 'money' => (int)$params['money'], + 'remark' => $params['remark'], + 'openid' => $open_id + ] + ]; + } + $total_amount = 0; + $total_num = 0; + + foreach ($transfer_list as $k => $v) { + $item_transfer = [ + 'out_detail_no' => $params['transfer_no'], + 'transfer_amount' => (int)$v['money'], + 'transfer_remark' => $v['remark'], + 'openid' => $v['openid'], + ]; + $total_amount += (int)$v['money']; + $total_num++; + if (!empty($v['user_name'])) { + $item_transfer['user_name'] = $v['user_name'];// 明文传参即可,sdk 会自动加密 + } + $order['transfer_detail_list'][] = $item_transfer; + } + $order['total_amount'] = $total_amount; + $order['total_num'] = $total_num; + $tran_status_list = [ + 'PROCESSING' => TransferDict::DEALING, + 'ACCEPTED' => TransferDict::DEALING, + 'CLOSED' => TransferDict::FAIL, + 'FINISHED' => TransferDict::SUCCESS, + ]; + try { + $result = $this->returnFormat(Pay::wechat()->transfer($order)); + if (!empty($result['code'])) { +// if($result['code'] == 'PARAM_ERROR'){ +// throw new PayException(); +// }else if($result['code'] == 'INVALID_REQUEST'){ +// throw new PayException(); +// } + if ($result['code'] == 'INVALID_REQUEST') { + throw new PayException(700010); + } + throw new PayException($result['message']); + } + + + return ['batch_id' => $result['batch_id'], 'out_batch_no' => $result['out_batch_no'], 'status' => $tran_status_list[$result['batch_status']]]; + } catch (\Exception $e) { + if($e->getCode() == 9402){ + return ['batch_id' => '', 'out_batch_no' => $order['out_batch_no'], 'status' => TransferDict::DEALING]; + } + if ($e instanceof InvalidResponseException) { + throw new PayException($e->response->all()['message'] ?? ''); + } + throw new PayException($e->getMessage()); + } + + } + + /** + * 支付关闭 + * @param string $out_trade_no + * @return void + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException + */ + public function close(string $out_trade_no) + { + try { + $result = Pay::wechat()->close([ + 'out_trade_no' => $out_trade_no, + ]); + return $this->returnFormat($result); + }catch(Throwable $e){ + return false; + } + return true; + } + + /** + * 退款 + * @param array $params + * @return array + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException + */ + public function refund(array $params) + { + $out_trade_no = $params['out_trade_no']; + $money = $params['money']; + $total = $params['total']; + $refund_no = $params['refund_no']; + $result = Pay::wechat()->refund([ + 'out_trade_no' => $out_trade_no, + 'out_refund_no' => $refund_no, + 'amount' => [ + 'refund' => $money, + 'total' => $total, + 'currency' => 'CNY', + ], + ]); + $result = $this->returnFormat($result); + + $refund_status_array = [ + 'SUCCESS' => RefundDict::SUCCESS, + 'CLOSED' => RefundDict::FAIL, + 'PROCESSING' => RefundDict::DEALING, + 'ABNORMAL' => RefundDict::FAIL, + ]; + return [ + 'status' => $refund_status_array[$result['status']], + 'refund_no' => $refund_no, + 'out_trade_no' => $out_trade_no, + 'pay_refund_no' => $result['refund_id'] + ]; + } + + + /** + * 异步回调 + * @param string $action + * @param callable $callback + * @return ResponseInterface|Response + */ + public function notify(string $action, callable $callback) + { + try { + $result = $this->returnFormat(Pay::wechat()->callback()); + if ($action == 'pay') {//支付 + if ($result['event_type'] == 'TRANSACTION.SUCCESS') { + $pay_trade_data = $result['resource']['ciphertext']; + + $temp_params = [ + 'trade_no' => $pay_trade_data['transaction_id'], + 'mch_id' => $pay_trade_data['mchid'], + 'status' => OnlinePayDict::getWechatPayStatus($pay_trade_data['trade_state']) + ]; + + $callback_result = $callback($pay_trade_data['out_trade_no'], $temp_params); + if (is_bool($callback_result) && $callback_result) { + return Pay::wechat()->success(); + } + } + } else if ($action == 'refund') {//退款 + if ($result['event_type'] == 'REFUND.SUCCESS') { + $refund_trade_data = $result['resource']['ciphertext']; + $refund_status_array = [ + 'SUCCESS' => RefundDict::SUCCESS, + 'CLOSED' => RefundDict::FAIL, + 'PROCESSING' => RefundDict::DEALING, + 'ABNORMAL' => RefundDict::FAIL, + ]; + $temp_params = [ + 'trade_no' => $refund_trade_data['transaction_id'], + 'mch_id' => $refund_trade_data['mchid'], + 'refund_no' => $refund_trade_data['out_refund_no'], + 'status' => $refund_status_array[$refund_trade_data['refund_status']], + ]; + + $callback_result = $callback($refund_trade_data['out_trade_no'], $temp_params); + if (is_bool($callback_result) && $callback_result) { + return Pay::wechat()->success(); + } + } + } + return $this->fail(); + + } catch ( Throwable $e ) { +// throw new PayException($e->getMessage()); + return $this->fail($e->getMessage()); + } + } + + /** + * 查询普通支付订单 + * @param array $params + * @return array|MessageInterface|Collection|null + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException + */ + public function getOrder(array $params = []) + { + + $out_trade_no = $params['out_trade_no']; + $transaction_id = $params['transaction_id'] ?? ''; + $order = [ + + ]; + if (!empty($out_trade_no)) { + $order['out_trade_no'] = $out_trade_no; + } + if (!empty($transaction_id)) { + $order['transaction_id'] = $transaction_id; + } + $result = Pay::wechat()->query($order); + if (empty($result)) + return $result; + $result = $this->returnFormat($result); + return [ + 'status' => OnlinePayDict::getWechatPayStatus($result['trade_state']), + ]; + } + + /** + * 查询退款单据 + * @param string|null $out_trade_no + * @param string|null $refund_no + * @return array|Collection|MessageInterface|null + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException + */ + public function getRefund(?string $out_trade_no, ?string $refund_no = '') + { + $order = [ + '_action' => 'refund', + 'transaction_id' => $out_trade_no, + 'out_refund_no' => $refund_no, + '' + ]; + $result = Pay::wechat()->query($order); + if (empty($result)) + return $result; + $result = $this->returnFormat($result); + $refund_status_array = [ + 'SUCCESS' => RefundDict::SUCCESS, + 'CLOSED' => RefundDict::FAIL, + 'PROCESSING' => RefundDict::DEALING, + 'ABNORMAL' => RefundDict::FAIL, + ]; + return [ + 'status' => $refund_status_array[$result['status']], + 'refund_no' => $refund_no, + 'out_trade_no' => $out_trade_no + ]; + } + + /** + * 获取转账订单(todo 切勿调用) + * @param string $transfer_no + * @return array + * @throws ContainerException + * @throws InvalidParamsException + */ + public function getTransfer(string $transfer_no, $out_batch_no = '') + { + $order = [ + 'out_batch_no' => $out_batch_no, + 'out_detail_no' => $transfer_no, + '_action' => 'transfer', + ]; + + try { + $result = Pay::wechat()->query($order); + $result = $this->returnFormat($result); + //微信转账状态 + $transfer_status_array = [ + 'INIT' => TransferDict::DEALING,//初始态。 系统转账校验中 + 'WAIT_PAY' => TransferDict::DEALING, + 'PROCESSING' => TransferDict::DEALING, + 'FAIL' => TransferDict::FAIL, + 'SUCCESS' => TransferDict::SUCCESS, + ]; + return [ + 'status' => $transfer_status_array[$result['detail_status']], + 'transfer_no' => $transfer_no + ]; + }catch(Throwable $e){ + return [ + 'status' => TransferDict::DEALING, + 'transfer_no' => $transfer_no + ]; + } + } + + + public function fail($message = '') + { + $response = [ + 'code' => 'FAIL', + 'message' => $message ?: '失败', + ]; + return response($response, 400, [], 'json'); + } +} diff --git a/niucloud/core/core/poster/BasePoster.php b/niucloud/core/core/poster/BasePoster.php new file mode 100644 index 00000000..2822d065 --- /dev/null +++ b/niucloud/core/core/poster/BasePoster.php @@ -0,0 +1,41 @@ +config([ 'path' => realpath($dir) . DIRECTORY_SEPARATOR . $file_path ]); + $bg_width = $poster_data[ 'global' ][ 'width' ]; + $bg_height = $poster_data[ 'global' ][ 'height' ]; + if ($bg_type == 'url' && !empty($poster_data[ 'global' ][ 'bgUrl' ]) && is_file($poster_data[ 'global' ][ 'bgUrl' ])) { + $im = $instance->buildIm($bg_width, $bg_height)->buildImage([ + 'src' => $poster_data[ 'global' ][ 'bgUrl' ], +// 'angle' => 80 + ], 0, 0, 0, 0, $bg_width, $bg_height); + } else { + $im = $instance->buildIm($bg_width, $bg_height, $this->getRgbColor($poster_data[ 'global' ][ 'bgColor' ])); + } + $align_array = [ + 'center', 'left', 'right', 'top', 'bottom' + ]; + foreach ($poster_data[ 'value' ] as $k => $v) { + $type = $v[ 'type' ]; + switch ($type) { + case 'text': + $font_size = ceil($v[ 'fontSize' ]); + $default_font = 'static' . DIRECTORY_SEPARATOR . 'font' . DIRECTORY_SEPARATOR . 'SourceHanSansCN-Regular.ttf'; + $font = $v[ 'fontFamily' ] ? : $default_font; + $content_list = $this->getText($v[ 'value' ], $font_size, $font, $v[ 'space' ] ?? 0, $v[ 'width' ], $v[ 'height' ], $v[ 'lineHeight' ] + $font_size); + $base_y = $this->getX($v[ 'y' ]); + if (is_array($base_y)) { + $diff_height = count($content_list) * ( $v[ 'lineHeight' ] + $font_size ); + $again_y = $base_y[ 0 ]; + if ($again_y == 'center') { + $base_y_num = ( $bg_height - $diff_height ) > 0 ? ( $bg_height - $diff_height ) / 2 : 0; + } else if ($again_y == 'top') { + $base_y_num = 0; + } else { + $base_y_num = $bg_height - $v[ 'height' ]; + } + + } else { + $base_y_num = $base_y; + } +// if(in_array($base_y, $align_array)){ +// $diff_height = count($content_list)*($v[ 'lineHeight' ]+$font_size); +// $base_y_num = ($bg_height-$diff_height) > 0 ? ($bg_height-$diff_height)/2 : 0; +// }else{ +// $base_y_num = $base_y[0]; +// } + foreach ($content_list as $ck => $content) { + if ($ck == 0) { + if ($v[ 'lineHeight' ] > 0) { + $item_line = $v[ 'lineHeight' ] / 2; + } else { + $item_line = 0; + } + } else { + $item_line = $v[ 'lineHeight' ] + $font_size; + } + $base_y_num += $item_line; + //计算文本框宽度 + $im = $im->buildText($content, $this->getX($v[ 'x' ]), $base_y_num, $font_size, $this->getRgbColor($v[ 'fontColor' ]), $v[ 'width' ], $font, $v[ 'weight' ] ? 10 : null); # 合成文字 + } + break; + case 'image': + if (is_file($v[ 'value' ])) { + $im = $im->buildImage($v[ 'value' ], $this->getX($v[ 'x' ]), $this->getY($v[ 'y' ]), 0, 0, $v[ 'width' ], $v[ 'height' ], false, $v[ 'shape' ] ?? 'normal'); # 合成图片 + } + break; + case 'draw': + if (!empty($v[ 'draw_type' ]) && $v[ 'draw_type' ] == 'Polygon') { + $points = $v[ 'points' ]; + $im = $im->buildLine($points[ 0 ][ 0 ], $points[ 0 ][ 1 ], $points[ 2 ][ 0 ], $points[ 2 ][ 1 ], $this->getRgbColor($v[ 'bgColor' ]), 'filled_rectangle'); + } + break; + } + } + + $path = $im->getPoster(); + + return str_replace(DIRECTORY_SEPARATOR, '/', str_replace(realpath(''), '', $path[ 'url' ])); + } + + + public function getX($dst_x) + { + if (is_int($dst_x)) { + return $dst_x; + } else { + return [ $dst_x, 0 ]; + } + } + + public function getY($dst_y) + { + if (is_int($dst_y)) { + return $dst_y; + } else { + return [ $dst_y, 0 ]; + } + } + + public function getRgbColor($color) + { + $color = $color ? : '#FFFFFF'; + if (!str_contains($color, '#')) { + $color = str_replace('rgba(', '', $color); + $color = str_replace(')', '', $color); + list($r, $g, $b) = explode(',', $color); + list($r, $g, $b) = array_map(function($v) { return (int) $v; }, [ $r, $g, $b ]); + } else { + list($r, $g, $b) = sscanf($color, "#%02x%02x%02x"); + } + return [ $r, $g, $b, 1 ]; + } + + /** + * 获取高度限制过后的文本 + * @param $content + * @param $fontSize + * @param $font + * @param $space + * @param $max_ws + * @param $max_hs + * @param $line_height + * @return mixed + */ + public function getText($content, $fontSize, $font, $space, $max_ws, $max_hs, $line_height) + { + $calcSpace = $space > $fontSize ? ( $space - $fontSize ) : 0; // 获取间距计算值 + + $fontSize = ( $fontSize * 3 ) / 4; // px 转化为 pt + + mb_internal_encoding('UTF-8'); // 设置编码 + // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度 + $contents = ''; + $contentsArr = []; + $letter = []; + $line = 1; + $calcSpaceRes = 0; + // 将字符串拆分成一个个单字 保存到数组 letter 中 + for ($i = 0; $i < mb_strlen($content); $i++) { + $letter[] = mb_substr($content, $i, 1); + } + $textWidthArr = []; + $contentStr = ''; + $line_num = 1; + $total_width = 0; + $content_list = []; + foreach ($letter as $l) { + $textStr = $contentStr . $l; + $fontBox = imagettfbbox($fontSize, 0, $font, $textStr); + $textWidth = abs($fontBox[ 2 ]) + $calcSpaceRes; + $textWidthArr[ $line ] = $textWidth; + // 判断拼接后的字符串是否超过预设的宽度 + if (( $textWidth > $max_ws ) && ( $contents !== '' )) { + $line_num++; + if (( $line_num * $line_height ) > $max_hs) { + break; + } + $contents .= "\n"; + $contentStr = ""; + $line++; + } + if (empty($content_list[ $line_num - 1 ])) $content_list[ $line_num - 1 ] = ''; + $content_list[ $line_num - 1 ] .= $l; + $contents .= $l; + $contentStr .= $l; + $line === 1 && $calcSpaceRes += $calcSpace; + $text_width = max(array_values($textWidthArr)); + } + return $content_list; + } +} \ No newline at end of file diff --git a/niucloud/core/core/poster/PosterLoader.php b/niucloud/core/core/poster/PosterLoader.php new file mode 100644 index 00000000..82265b01 --- /dev/null +++ b/niucloud/core/core/poster/PosterLoader.php @@ -0,0 +1,42 @@ +config = $config; + } + + /** + * 打印小票 + * @param array $data + * @return mixed|void + */ + public function printTicket(array $data) + { + } +} \ No newline at end of file diff --git a/niucloud/core/core/printer/PrinterLoader.php b/niucloud/core/core/printer/PrinterLoader.php new file mode 100644 index 00000000..28c2f9c8 --- /dev/null +++ b/niucloud/core/core/printer/PrinterLoader.php @@ -0,0 +1,39 @@ +client->call('expressprint/index', array('machine_code' => $machineCode, 'content' => $content, 'origin_id' => $originId, 'sandbox' => $sandbox)); + } + + /** + * 面单取消接口 + * + * @param $machineCode + * @param $content + * @return mixed + * @throws \Exception + */ + public function cancel($machineCode, $content) + { + return $this->client->call('expressprint/cancel', array('machine_code' => $machineCode, 'content' => $content)); + } + +} diff --git a/niucloud/core/core/printer/sdk/yilianyun/api/OauthService.php b/niucloud/core/core/printer/sdk/yilianyun/api/OauthService.php new file mode 100644 index 00000000..c712be22 --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/api/OauthService.php @@ -0,0 +1,22 @@ +client->call('oauth/setpushurl', array('cmd' => $cmd, 'url' => $url, 'status' => $status)); + } +} + + diff --git a/niucloud/core/core/printer/sdk/yilianyun/api/PicturePrintService.php b/niucloud/core/core/printer/sdk/yilianyun/api/PicturePrintService.php new file mode 100644 index 00000000..dfb4b4c4 --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/api/PicturePrintService.php @@ -0,0 +1,22 @@ +client->call('pictureprint/index', array('machine_code' => $machineCode, 'picture_url' => $pictureUrl, 'origin_id' => $originId, $idempotence => $idempotence)); + } +} diff --git a/niucloud/core/core/printer/sdk/yilianyun/api/PrintMenuService.php b/niucloud/core/core/printer/sdk/yilianyun/api/PrintMenuService.php new file mode 100644 index 00000000..6f4a5ede --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/api/PrintMenuService.php @@ -0,0 +1,19 @@ +client->call('printmenu/addprintmenu', array('machine_code' => $machineCode, 'content' => $content)); + } + +} \ No newline at end of file diff --git a/niucloud/core/core/printer/sdk/yilianyun/api/PrintService.php b/niucloud/core/core/printer/sdk/yilianyun/api/PrintService.php new file mode 100644 index 00000000..7ff2309e --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/api/PrintService.php @@ -0,0 +1,20 @@ +client->call('print/index', array('machine_code' => $machineCode, 'content' => $content, 'origin_id' => $originId, 'idempotence' => $idempotence)); + } +} diff --git a/niucloud/core/core/printer/sdk/yilianyun/api/PrinterService.php b/niucloud/core/core/printer/sdk/yilianyun/api/PrinterService.php new file mode 100644 index 00000000..d7b6bd66 --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/api/PrinterService.php @@ -0,0 +1,313 @@ + $machineCode, + 'msign' => $mSign, + ); + if (!empty($phone)) { + $params['phone'] = $phone; + } + if (!empty($printName)) { + $params['print_name'] = $printName; + } + return $this->client->call('printer/addprinter', $params); + } + + + /** + * 设置内置语音接口 + * 注意: 仅支持K4-WA、K4-GAD、K4-WGEAD型号 + * + * @param $machineCode string 机器码 + * @param $content string 在线语音地址链接 or 自定义语音内容 + * @param bool $isFile true or false + * @param string $aid int 0~9 , 定义需设置的语音编号,若不提交,默认升序 + * @return mixed + */ + public function setVoice($machineCode, $content, $isFile = false, $aid = '') + { + $params = array( + 'machine_code' => $machineCode, + 'content' => $content, + 'is_file' => $isFile, + ); + if (!empty($aid)){ + $params ['aid'] = $aid; + } + return $this->client->call('printer/setvoice', $params); + } + + + /** + * 删除内置语音接口 + * 注意: 仅支持K4-WA、K4-GAD、K4-WGEAD型号 + * + * @param $machineCode string 机器码 + * @param $aid int 0 ~ 9 编号 + * @return mixed + */ + public function deleteVoice($machineCode, $aid) + { + return $this->client->call('printer/deletevoice', array('machine_code' => $machineCode, 'aid' => $aid)); + } + + + /** + * 删除终端授权接口 + * + * @param $machineCode string 机器码 + * @return mixed + */ + public function deletePrinter($machineCode) + { + return $this->client->call('printer/deleteprinter', array('machine_code' => $machineCode)); + } + + + /** + * 关机重启接口 + * + * @param $machineCode string 机器码 + * @param $responseType string restart or shutdown + * @return mixed + */ + public function shutdownRestart($machineCode, $responseType) + { + return $this->client->call('printer/shutdownrestart', array('machine_code' => $machineCode, 'response_type' => $responseType)); + } + + + /** + * 声音调节接口 + * + * @param $machineCode string 机器码 + * @param $voice string 音量 0 or 1 or 2 or 3 + * @param $responseType string buzzer (蜂鸣器) or horn (喇叭) + * @return mixed + */ + public function setsound($machineCode, $voice, $responseType) + { + return $this->client->call('printer/setsound', array('machine_code' => $machineCode, 'voice' => $voice, 'response_type' => $responseType)); + } + + + /** + * 获取机型打印宽度接口 + * + * @param $machineCode string 机器码 + * @return mixed + */ + public function printInfo($machineCode) + { + return $this->client->call('printer/printinfo', array('machine_code' => $machineCode)); + } + + + /** + * 获取机型软硬件版本接口 + * + * @param $machineCode string 机器码 + * @return mixed + */ + public function getVersion($machineCode) + { + return $this->client->call('printer/getversion', array('machine_code' => $machineCode)); + } + + + /** + * 取消所有未打印订单接口 + * + * @param $machineCode string 机器码 + * @return mixed + */ + public function cancelAll($machineCode) + { + return $this->client->call('printer/cancelall', array('machine_code' => $machineCode)); + } + + + /** + * 取消单条未打印订单接口 + * + * @param $machineCode string 机器码 + * @param $orderId string 未打印的易联云ID + * @return mixed + */ + public function cancelOne($machineCode, $orderId) + { + return $this->client->call('printer/cancelone', array('machine_code' => $machineCode, 'order_id' => $orderId)); + } + + + /** + * 设置logo接口 + * + * @param $machineCode string 机器码 + * @param $imgUrl string logo链接地址 + * @return mixed + */ + public function setIcon($machineCode, $imgUrl) + { + return $this->client->call('printer/seticon', array('machine_code' => $machineCode, 'img_url' => $imgUrl)); + } + + + /** + * 取消logo接口 + * + * @param $machineCode string 机器码 + * @return mixed + */ + public function deleteIcon($machineCode) + { + return $this->client->call('printer/deleteicon', array('machine_code' => $machineCode)); + } + + + /** + * 打印方式接口 + * + * @param $machineCode string 机器码 + * @param $responseType string btnopen or btnclose + * @return mixed + */ + public function btnPrint($machineCode, $responseType) + { + return $this->client->call('printer/btnprint', array('machine_code' => $machineCode, 'response_type' => $responseType)); + } + + + /** + * 接单拒单设置接口 + * + * @param $machineCode string 机器码 + * @param $responseType string open or close + * @return mixed + */ + public function getOrder($machineCode, $responseType) + { + return $this->client->call('printer/getorder', array('machine_code' => $machineCode, 'response_type' => $responseType)); + } + + + /** + * 获取订单状态接口 + * + * @param $machineCode string 机器码 + * @param $orderId string 易联云订单id + * @return mixed + */ + public function getOrderStatus($machineCode, $orderId) + { + return $this->client->call('printer/getorderstatus', array('machine_code' => $machineCode, 'order_id' => $orderId)); + } + + + /** + * 获取订单列表接口 + * + * @param $machineCode string 机器码 + * @param $pageIndex int 第几页 + * @param $pageSize int 查询条数 + * @return mixed + */ + public function getOrderPagingList($machineCode, $pageIndex = 1 , $pageSize = 10) + { + return $this->client->call('printer/getorderpaginglist', array('machine_code' => $machineCode, 'page_index' => $pageIndex, 'page_size' => $pageSize)); + } + + /** + * 获取终端状态接口 + * + * @param $machineCode string 机器码 + * @return mixed + */ + public function getPrintStatus($machineCode) + { + return $this->client->call('printer/getprintstatus', array('machine_code' => $machineCode)); + } + + /** + * 订单重打(单订单) + * + * @param $machineCode + * @param $orderId + * @return mixed + * @throws \Exception + */ + public function reprintOrder($machineCode, $orderId) + { + return $this->client->call('printer/reprintorder', array('machine_code' => $machineCode, 'order_id' => $orderId)); + } + + /** + * K8 推送开关设置 + * + * @param $machineCode + * @param $status + * @param $mode + * @return mixed + * @throws \Exception + */ + public function pushSwitch($machineCode, $status, $mode = 1) + { + return $this->client->call('printer/pushswitch', array('machine_code' => $machineCode, 'status' => $status, $mode)); + } + + /** + * K8 关键词设置接口 + * + * @param $machineCode + * @param $keys + * @param $type + * @param $content + * @return mixed + * @throws \Exception + */ + public function setKeyWords($machineCode, $keys, $type, $content) + { + return $this->client->call('printer/setkeywords', array('machine_code' => $machineCode, 'keys' => $keys, 'type' => $type, 'content' => $content)); + } + + /** + * K8 高级设置接口 + * + * @param $machineCode + * @param null $usbPrintMode + * @param null $usbInputMode + * @param null $cameraDecodeTxMode + * @return mixed + * @throws \Exception + */ + public function setting($machineCode, $usbPrintMode = null, $usbInputMode = null, $cameraDecodeTxMode = null) + { + $params = array('machine_code' => $machineCode); + if (!is_null($usbPrintMode) && in_array($usbPrintMode, [0, 1])) { + $params['usb_print_mode'] = (int)$usbInputMode; + } + if (!is_null($usbInputMode) && in_array($usbInputMode, [0, 1])) { + $params['usb_input_mode'] = (int)$usbInputMode; + } + if (!is_null($cameraDecodeTxMode) && in_array($cameraDecodeTxMode, [0, 1])) { + $params['camera_decode_tx_mode'] = (int)$cameraDecodeTxMode; + } + return $this->client->call('printer/setting', $params); + } + +} diff --git a/niucloud/core/core/printer/sdk/yilianyun/api/RpcService.php b/niucloud/core/core/printer/sdk/yilianyun/api/RpcService.php new file mode 100644 index 00000000..22596e68 --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/api/RpcService.php @@ -0,0 +1,19 @@ +client = new YlyRpcClient($token, $config); + } + +} \ No newline at end of file diff --git a/niucloud/core/core/printer/sdk/yilianyun/config/YlyConfig.php b/niucloud/core/core/printer/sdk/yilianyun/config/YlyConfig.php new file mode 100644 index 00000000..cdf00b9e --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/config/YlyConfig.php @@ -0,0 +1,68 @@ +clientId = $clientId; + $this->clientSecret = $clientSecret; + } + + public function getClientId() + { + return $this->clientId; + } + + + public function getClientSecret() + { + return $this->clientSecret; + } + + public function getRequestUrl() + { + return $this->requestUrl; + } + + public function setRequestUrl($requestUrl) + { + $this->requestUrl = $requestUrl; + } + + public function getLog() + { + return $this->log; + } + + public function setLog($log) + { + if (!method_exists($log, "info")) { + throw new InvalidArgumentException("logger need have method 'info(\$message)'"); + } + if (!method_exists($log, "error")) { + throw new InvalidArgumentException("logger need have method 'error(\$message)'"); + } + $this->log = $log; + } + +} diff --git a/niucloud/core/core/printer/sdk/yilianyun/demo/authorization_code_mode/callback.php b/niucloud/core/core/printer/sdk/yilianyun/demo/authorization_code_mode/callback.php new file mode 100644 index 00000000..aa8786c3 --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/demo/authorization_code_mode/callback.php @@ -0,0 +1,141 @@ +getToken($code); +} catch (Exception $e) { + echo $e->getMessage() . "\n"; + print_r(json_decode($e->getMessage(), true)); + return; +} + +$access_token = $token->access_token; //调用API凭证AccessToken +$refresh_token = $token->refresh_token; //刷新AccessToken凭证 失效时间35天 +$machine_code = $token->machine_code; //商户授权机器码 +$expires_in = $token->expires_in; //AccessToken失效时间30天 +$refresh_expires_in = $token->refresh_expires_in; //RefreshToken失效时间35天 +$origin_id = ''; //内部订单号(32位以内) + + +if (empty($machine_code)) { + echo 'The machine_code cannot be empty'; + return; +} + +if (empty($origin_id)) { + echo 'The origin_id cannot be empty'; + return; +} + +/**文本接口开始**/ +$print = new PrintService($access_token, $config); +//58mm排版 排版指令详情请看 http://doc2.10ss.net/332006 +$content = "
**#1 美团**
"; +$content .= str_repeat('.', 32); +$content .= "
--在线支付--
"; +$content .= "
张周兄弟烧烤
"; +$content .= "订单时间:" . date("Y-m-d H:i") . "\n"; +$content .= "订单编号:40807050607030\n"; +$content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14); +$content .= ""; +$content .= ""; +$content .= ""; +$content .= ""; +$content .= ""; +$content .= ""; +$content .= "
烤土豆(超级辣)x35.96
烤豆干(超级辣)x23.88
烤鸡翅(超级辣)x317.96
烤排骨(香辣)x312.44
烤韭菜(超级辣)x38.96
"; +$content .= str_repeat('.', 32); +$content .= "这是二维码内容"; +$content .= "小计:¥82\n"; +$content .= "折扣:¥4 \n"; +$content .= str_repeat('*', 32); +$content .= "订单总价:¥78 \n"; +$content .= "
**#1 完**
"; + +try { + var_dump($print->index($machine_code, $content, $origin_id)); +} catch (Exception $e) { + echo $e->getMessage(); +} +/**文本接口结束**/ + + +///**图形接口开始**/ +//$picturePrint = new PicturePrintService($access_token, $config); +//$content = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497000905083&di=7c3cffef1dd40edffbd0a37c4eabb277&imgtype=0&src=http://img1.touxiang.cn/uploads/20131114/14-054929_462.jpg"; +//try{ +// var_dump($picturePrint->index($machine_code, $content, $origin_id)); +//}catch (Exception $e) { +// echo $e->getMessage(); +//} +///**图形接口结束**/ + + +///**面单接口开始**/ //打印机型必须为k5; +//$expressPrint = new ExpressPrintService($access_token, $config); +//$content = array( +// "OrderCode"=> "0126578665784971", +// "ShipperCode"=> "SF", //SF YZPY HTKY YD +// "PayType"=> 1, +// "ExpType"=> 1, +// "Cost"=>6.0, +// "OtherCost"=> 7.0, +// "CustomerName" => '1264546', +// "CustomerPwd" => '4545454', +// "MonthCode" => '', +// "Sender"=> array( +// "Company" => "5645645", +// "Name" => "Taylor", +// "Mobile" => "15018442396", +// "ProvinceName" => "上海", +// "CityName" => "上海", +// "PostCode" => '61000', +// "ExpAreaName" => "青浦区", +// "Address" => "明珠路73号" +// ), +// "Receiver"=> array( +// "Company"=> "789789", +// "Name"=> "Yann", +// "Mobile"=> "15018442396", +// "ProvinceName"=> "北京", +// "CityName"=> "北京", +// "PostCode" => '61000', +// "ExpAreaName"=> "朝阳区", +// "Address"=> "三里屯街道雅秀大厦" +// ), +// "Commodity" => array( +// array( +// "GoodsName"=> "鞋子", +// ) +// ), +// "AddService"=> array( +// array( +// "Name"=> "COD", +// "Value"=> "1020", +// "CustomerID" => "44564" +// ) +// ), +// "StartDate" => date("y-M-d H:i:s",time() + 7200), +// "Weight"=> 1.0, +// "Quantity"=> 1, +// "Volume"=> 0.0, +// "Remark"=> "小心轻放", +//); +// +//try{ +// var_dump($expressPrint->index($machine_code, $content, $origin_id)); +//}catch (Exception $e) { +// echo $e->getMessage(); +//} +///**面单接口结束**/ diff --git a/niucloud/core/core/printer/sdk/yilianyun/demo/client_mode/callback.php b/niucloud/core/core/printer/sdk/yilianyun/demo/client_mode/callback.php new file mode 100644 index 00000000..bba4a61e --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/demo/client_mode/callback.php @@ -0,0 +1,136 @@ +getToken(); +} catch (Exception $e) { + echo $e->getMessage() . "\n"; + print_r(json_decode($e->getMessage(), true)); + return; +} + +$access_token = $token->access_token; //调用API凭证AccessToken 永久有效,请妥善保存. +$refresh_token = $token->refresh_token; //刷新AccessToken凭证 失效时间35天 +$expires_in = $token->expires_in; //自有型应用可忽略此回调参数, AccessToken失效时间30天 +$refresh_expires_in = $token->refresh_expires_in; //自有型应用可忽略此回调参数, RefreshToken失效时间35天 +$machine_code = ''; //机器码 +$origin_id = ''; //内部订单号(32位以内) + +if (empty($machine_code)) { + echo 'The machine_code cannot be empty'; + return; +} + +if (empty($origin_id)) { + echo 'The origin_id cannot be empty'; + return; +} + + +/**文本接口开始**/ +$print = new PrintService($access_token, $config); +//58mm排版 排版指令详情请看 http://doc2.10ss.net/332006 +$content = "
**#1 美团**
"; +$content .= str_repeat('.', 32); +$content .= "
--在线支付--
"; +$content .= "
张周兄弟烧烤
"; +$content .= "订单时间:" . date("Y-m-d H:i") . "\n"; +$content .= "订单编号:40807050607030\n"; +$content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14); +$content .= ""; +$content .= ""; +$content .= ""; +$content .= ""; +$content .= ""; +$content .= ""; +$content .= "
烤土豆(超级辣)x35.96
烤豆干(超级辣)x23.88
烤鸡翅(超级辣)x317.96
烤排骨(香辣)x312.44
烤韭菜(超级辣)x38.96
"; +$content .= str_repeat('.', 32); +$content .= "这是二维码内容"; +$content .= "小计:¥82\n"; +$content .= "折扣:¥4 \n"; +$content .= str_repeat('*', 32); +$content .= "订单总价:¥78 \n"; +$content .= "
**#1 完**
"; + +try { + var_dump($print->index($machine_code, $content, $origin_id)); +} catch (Exception $e) { + echo $e->getMessage(); +} +/**文本接口结束**/ + + +///**图形接口开始**/ +//$picturePrint = new PicturePrintService($access_token, $config); +//$content = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497000905083&di=7c3cffef1dd40edffbd0a37c4eabb277&imgtype=0&src=http://img1.touxiang.cn/uploads/20131114/14-054929_462.jpg"; +//try{ +// var_dump($picturePrint->index($machine_code, $content, $origin_id)); +//}catch (Exception $e) { +// echo $e->getMessage(); +//} +///**图形接口结束**/ + + +///**面单接口开始**/ //打印机型必须为k5; +//$expressPrint = new ExpressPrintService($access_token, $config); +//$content = array( +// "OrderCode"=> "0126578665784971", +// "ShipperCode"=> "SF", //SF YZPY HTKY YD +// "PayType"=> 1, +// "ExpType"=> 1, +// "Cost"=>6.0, +// "OtherCost"=> 7.0, +// "CustomerName" => '1264546', +// "CustomerPwd" => '4545454', +// "MonthCode" => '', +// "Sender"=> array( +// "Company" => "5645645", +// "Name" => "Taylor", +// "Mobile" => "15018442396", +// "ProvinceName" => "上海", +// "CityName" => "上海", +// "PostCode" => '61000', +// "ExpAreaName" => "青浦区", +// "Address" => "明珠路73号" +// ), +// "Receiver"=> array( +// "Company"=> "789789", +// "Name"=> "Yann", +// "Mobile"=> "15018442396", +// "ProvinceName"=> "北京", +// "CityName"=> "北京", +// "PostCode" => '61000', +// "ExpAreaName"=> "朝阳区", +// "Address"=> "三里屯街道雅秀大厦" +// ), +// "Commodity" => array( +// array( +// "GoodsName"=> "鞋子", +// ) +// ), +// "AddService"=> array( +// array( +// "Name"=> "COD", +// "Value"=> "1020", +// "CustomerID" => "44564" +// ) +// ), +// "StartDate" => date("y-M-d H:i:s",time() + 7200), +// "Weight"=> 1.0, +// "Quantity"=> 1, +// "Volume"=> 0.0, +// "Remark"=> "小心轻放", +//); +// +//try{ +// var_dump($expressPrint->index($machine_code, $content, $origin_id)); +//}catch (Exception $e) { +// echo $e->getMessage(); +//} +///**面单接口结束**/ diff --git a/niucloud/core/core/printer/sdk/yilianyun/demo/index.php b/niucloud/core/core/printer/sdk/yilianyun/demo/index.php new file mode 100644 index 00000000..30cabdd0 --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/demo/index.php @@ -0,0 +1,11 @@ +setRequestUrl('https://open-api.10ss.net/v2'); diff --git a/niucloud/core/core/printer/sdk/yilianyun/oauth/YlyOauthClient.php b/niucloud/core/core/printer/sdk/yilianyun/oauth/YlyOauthClient.php new file mode 100644 index 00000000..ffc8510d --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/oauth/YlyOauthClient.php @@ -0,0 +1,152 @@ +clientId = $config->getClientId(); + $this->clientSecret = $config->getClientSecret(); + $this->requestUrl = $config->getRequestUrl(); + $this->log = $config->getLog(); + } + + + public function getToken($code = '') + { + $time = time(); + $params = array( + 'client_id' => $this->clientId, + 'timestamp' => $time, + 'sign' => $this->getSign($time), + 'id' => $this->uuid4(), + 'scope' => 'all' + ); + $params[ 'grant_type' ] = 'client_credentials'; + if (!empty($code)) { + $params[ 'code' ] = $code; + $params[ 'grant_type' ] = 'authorization_code'; + } + + $url = sprintf("%s/%s", $this->requestUrl, 'oauth/oauth'); + return $this->send($params, $url); + } + + + public function getTokenBySecret($machineCode, $secret, $secretType = 0) + { + $time = time(); + $params = array( + 'client_id' => $this->clientId, + 'timestamp' => $time, + 'sign' => $this->getSign($time), + 'id' => $this->uuid4(), + 'machine_code' => $machineCode, + 'scope' => 'all' + ); + if ($secretType == 1) { + $params[ 'qr_key' ] = $secret; + } else { + $params[ 'msign' ] = $secret; + } + + $url = sprintf("%s/%s", $this->requestUrl, 'oauth/scancodemodel'); + return $this->send($params, $url); + } + + public function refreshToken($refreshToken) + { + $time = time(); + $params = array( + 'client_id' => $this->clientId, + 'timestamp' => $time, + 'sign' => $this->getSign($time), + 'id' => $this->uuid4(), + 'scope' => 'all', + 'grant_type' => 'refresh_token', + 'refresh_token' => $refreshToken, + ); + + $url = sprintf("%s/%s", $this->requestUrl, 'oauth/oauth'); + return $this->send($params, $url); + } + + + public function getSign($timestamp) + { + return md5( + $this->clientId . + $timestamp . + $this->clientSecret + ); + } + + + public function uuid4() + { + mt_srand(mt_rand()); + $charid = strtolower(md5(uniqid(rand(), true))); + $hyphen = '-'; + $uuidV4 = + substr($charid, 0, 8) . $hyphen . + substr($charid, 8, 4) . $hyphen . + substr($charid, 12, 4) . $hyphen . + substr($charid, 16, 4) . $hyphen . + substr($charid, 20, 12); + return $uuidV4; + } + + + public function send($data, $url) + { + $requestInfo = http_build_query($data); + $log = $this->log; + if ($log != null) { + $log->info("request data: " . $requestInfo); + } + $curl = curl_init(); // 启动一个CURL会话 + curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测 + curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Expect:' )); // 解决数据包大不能提交 + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer + curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 + curl_setopt($curl, CURLOPT_POSTFIELDS, $requestInfo); // Post提交的数据包 + curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循 + curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 + $requestResponse = curl_exec($curl); // 执行操作 + $response = json_decode($requestResponse); + if (curl_errno($curl)) { + if ($log != null) { + $log->error("error: " . curl_error($curl)); + } + throw new Exception(curl_error($curl)); + } + if (is_null($response)) { + throw new Exception("illegal response :" . $requestResponse); + } + + if ($response->error != 0 && $response->error_description != 'success') { + throw new Exception($response->error_description); + } + if ($this->log != null) { + $this->log->info("response: " . json_encode($response)); + } + curl_close($curl); // 关键CURL会话 + return $response->body; // 返回数据 + } + + +} diff --git a/niucloud/core/core/printer/sdk/yilianyun/protocol/YlyRpcClient.php b/niucloud/core/core/printer/sdk/yilianyun/protocol/YlyRpcClient.php new file mode 100644 index 00000000..4099af9b --- /dev/null +++ b/niucloud/core/core/printer/sdk/yilianyun/protocol/YlyRpcClient.php @@ -0,0 +1,104 @@ +clientId = $config->getClientId(); + $this->clientSecret = $config->getClientSecret(); + $this->requestUrl = $config->getRequestUrl(); + $this->log = $config->getLog(); + $this->token = $token; + } + + + public function call($action, array $params) + { + $time = time(); + $params = array_merge(array( + 'client_id' => $this->clientId, + 'timestamp' => $time, + 'sign' => $this->getSign($time), + 'id' => $this->uuid4(), + 'access_token' => $this->token, + ), $params); + + $result = $this->send($params, $this->requestUrl . '/' . $action); + $response = json_decode($result, false, 512, JSON_BIGINT_AS_STRING); + + return $response; + } + + + public function getSign($timestamp) + { + return md5( + $this->clientId . + $timestamp . + $this->clientSecret + ); + } + + + public function uuid4() + { + mt_srand(mt_rand()); + $charid = strtolower(md5(uniqid(rand(), true))); + $hyphen = '-'; + $uuidV4 = + substr($charid, 0, 8) . $hyphen . + substr($charid, 8, 4) . $hyphen . + substr($charid, 12, 4) . $hyphen . + substr($charid, 16, 4) . $hyphen . + substr($charid, 20, 12); + return $uuidV4; + } + + + public function send($data, $url) + { + $requestInfo = http_build_query($data); + $log = $this->log; + if ($log != null) { + $log->info("request data: " . $requestInfo); + } + $curl = curl_init(); // 启动一个CURL会话 + curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测 + curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Expect:' )); // 解决数据包大不能提交 + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer + curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 + curl_setopt($curl, CURLOPT_POSTFIELDS, $requestInfo); // Post提交的数据包 + curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循 + curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 + $response = curl_exec($curl); // 执行操作 + if (curl_errno($curl)) { + if ($log != null) { + $log->error("error: " . curl_error($curl)); + } + throw new Exception(curl_error($curl)); + } + if ($log != null) { + $log->info("response: " . $response); + } + curl_close($curl); // 关键CURL会话 + return $response; // 返回数据 + } + + +} diff --git a/niucloud/core/core/sms/Aliyun.php b/niucloud/core/core/sms/Aliyun.php new file mode 100644 index 00000000..dc66a8ef --- /dev/null +++ b/niucloud/core/core/sms/Aliyun.php @@ -0,0 +1,98 @@ +app_key = $config[ 'app_key' ] ?? ''; + $this->secret_key = $config[ 'secret_key' ] ?? ''; + $this->sign = $config[ 'sign' ] ?? ''; + } + + + /** + * 发送短信 + * @param string $mobile + * @param string $template_id + * @param array $data + * @return array + */ + public function send(string $mobile, string $template_id, array $data = []) + { + try { + AlibabaCloud::accessKeyClient($this->app_key, $this->secret_key) + ->regionId('cn-hangzhou') + ->asDefaultClient(); + $result = AlibabaCloud::rpcRequest() + ->product('Dysmsapi') + ->host('dysmsapi.aliyuncs.com') + ->version('2017-05-25') + ->action('SendSms') + ->method('POST') + ->debug(false) + ->options([ + 'query' => [ + 'PhoneNumbers' => $mobile, + 'SignName' => $this->sign, + 'TemplateCode' => $template_id, + 'TemplateParam' => json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE), + ], + ]) + ->request(); + + $res = $result->toArray(); + if (isset($res[ 'Code' ]) && $res[ 'Code' ] == 'OK') { + return $res; + } + $message = $res[ 'Message' ] ?? $res; + throw new NoticeException($message); + } catch (Exception $e) { + throw new NoticeException($e->getMessage()); + } + } + + public function modify(string $sign, string $mobile, string $code) + { + } + + public function template(int $page = 0, int $limit = 10, int $type = 1) + { + } + + public function apply(string $title, string $content, int $type) + { + } + + public function localTemplate(int $type, int $page, int $limit) + { + } + + public function record($id) + { + } +} \ No newline at end of file diff --git a/niucloud/core/core/sms/BaseSms.php b/niucloud/core/core/sms/BaseSms.php new file mode 100644 index 00000000..4559cf23 --- /dev/null +++ b/niucloud/core/core/sms/BaseSms.php @@ -0,0 +1,83 @@ +secret_id = $config[ 'secret_id' ] ?? ''; + $this->secret_key = $config[ 'secret_key' ] ?? ''; + $this->sign = $config[ 'sign' ] ?? ''; + $this->app_id = $config[ 'app_id' ] ?? ''; + } + + + /** + * 发送短信 + * @return bool|mixed + */ + public function send(string $mobile, string $template_id, array $data = []) + { + try { + $cred = new Credential($this->secret_id, $this->secret_key); + $httpProfile = new HttpProfile(); + $httpProfile->setEndpoint("sms.tencentcloudapi.com"); + + $clientProfile = new ClientProfile(); + $clientProfile->setHttpProfile($httpProfile); + + $client = new SmsClient($cred, 'ap-guangzhou', $clientProfile); + $params = [ + 'PhoneNumberSet' => [ '+86' . $mobile ], + 'TemplateID' => $template_id, + 'Sign' => $this->sign, + 'TemplateParamSet' => $data, + 'SmsSdkAppid' => $this->app_id, + ]; + $req = new SendSmsRequest(); + $req->fromJsonString(json_encode($params, JSON_THROW_ON_ERROR)); + $resp = json_decode($client->SendSms($req)->toJsonString(), true, 512, JSON_THROW_ON_ERROR); + if (isset($resp[ 'SendStatusSet' ]) && $resp[ 'SendStatusSet' ][ 0 ][ 'Code' ] == 'Ok') { + return $resp; + } else { + $message = $res[ 'SendStatusSet' ][ 0 ][ 'Message' ] ?? json_encode($resp, JSON_THROW_ON_ERROR); + throw new CommonException($message); + } + } catch (Exception $e) { + throw new NoticeException($e->getMessage()); + } + } + + + public function modify(string $sign, string $mobile, string $code) + { + } + + public function template(int $page = 0, int $limit = 15, int $type = 1) + { + } + + public function apply(string $title, string $content, int $type) + { + } + + public function localTemplate(int $type, int $page, int $limit) + { + } + + public function record($id) + { + } +} \ No newline at end of file diff --git a/niucloud/core/core/template/BaseTemplate.php b/niucloud/core/core/template/BaseTemplate.php new file mode 100644 index 00000000..73d5a978 --- /dev/null +++ b/niucloud/core/core/template/BaseTemplate.php @@ -0,0 +1,60 @@ +postJson('cgi-bin/message/subscribe/send', [ + 'template_id' => $data['template_id'], // 所需下发的订阅模板id + 'touser' => $data['openid'], // 接收者(用户)的 openid + 'page' => $data['page'], // 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 + 'data' => $data['data'], + ]); + } + + /** + * 添加模板消息 + * @param array $data + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException + */ + public function addTemplate(array $data) + { + $api = CoreWeappService::appApiClient(); + return $api->postJson('wxaapi/newtmpl/addtemplate', [ + 'tid' => $data['tid'], + 'kidList' => $data['kid_list'], + 'sceneDesc' => $data['scene_desc'], + ]); + } + + /** + * 删除 + * @param array $data + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException + */ + public function delete(array $data) + { + $api = CoreWeappService::appApiClient(); + return $api->postJson('wxaapi/newtmpl/deltemplate', [ + 'priTmplId' => $data['template_id'], + ]); + } + + /** + * 获取 + * @return void + */ + public function get() + { + + } +} diff --git a/niucloud/core/core/template/Wechat.php b/niucloud/core/core/template/Wechat.php new file mode 100644 index 00000000..f9aea6f7 --- /dev/null +++ b/niucloud/core/core/template/Wechat.php @@ -0,0 +1,111 @@ + $v){ + $temp_data[$k] = ['value' => $v]; + } + + if (!empty($first)) $data[ 'first' ] = $first; + if (!empty($remark)) $data[ 'remark' ] = $remark; + $api = CoreWechatService::appApiClient(); + $param = [ + 'touser' => $openid, + 'template_id' => $template_id, + 'url' => $url, + 'miniprogram' => $miniprogram, + 'data' => $temp_data, + ]; + if(!empty($client_msg_id)){ + $param['client_msg_id'] = $client_msg_id; + } + return $api->postJson('cgi-bin/message/template/send', $param); + } + + /** + * 添加模板消息 + * @param array $data + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException + */ + public function addTemplate(array $data) + { + $api = CoreWechatService::appApiClient(); + return $api->postJson('cgi-bin/template/api_add_template', [ + 'template_id_short' => $data[ 'shortId' ], + 'keyword_name_list' => $data[ 'keyword_name_list' ] + ]); + } + + /** + * 删除 + * @param array $data + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException + */ + public function delete(array $data) + { + $api = CoreWechatService::appApiClient(); + + return $api->postJson('cgi-bin/template/del_private_template', [ + 'template_id' => $data[ 'templateId' ], + ]); + } + + /** + * 获取 + * @return void + */ + public function get() + { + + } +} diff --git a/niucloud/core/core/upload/Aliyun.php b/niucloud/core/core/upload/Aliyun.php new file mode 100644 index 00000000..238a4c97 --- /dev/null +++ b/niucloud/core/core/upload/Aliyun.php @@ -0,0 +1,133 @@ +config['access_key']; + $access_key_secret = $this->config['secret_key']; + + $endpoint = $this->config['endpoint'];// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 + return new OssClient($access_key_id, $access_key_secret, $endpoint); + } + + /** + * 执行上传 + * @param string $dir + * @return true + */ + public function upload(string $dir) + { + $this->validate(); + $bucket = $this->config['bucket']; + try { + $this->client()->uploadFile( + $bucket, + $this->getFullPath($dir), + $this->getRealPath() + ); + return true; + } catch ( OssException $e ) { + throw new UploadFileException($e->getMessage()); + } + + } + + /** + * base64上云 + * @param string $base64_data + * @param string|null $key + * @return true + */ + public function base64(string $base64_data, ?string $key = null) + { + $bucket = $this->config['bucket']; + try { + $base64_file = base64_decode($base64_data); + if (!$base64_file) throw new UploadFileException('FILE_ERROR'); + $this->client()->putObject( + $bucket, + $key, + $base64_file + ); + return true; + } catch ( OssException $e ) { + throw new UploadFileException($e->getMessage()); + } + } + /** + * Notes: 抓取远程资源 + * @param string $url + * @param string|null $key + * @return true + */ + public function fetch(string $url, ?string $key = null) + { + $bucket = $this->config['bucket']; + try { + $content = file_get_contents($url); + $this->client()->putObject( + $bucket, + $key, + $content + ); + return true; + } catch ( OssException $e ) { + throw new UploadFileException($e->getMessage()); + } + + } + + /** + * 删除文件 + * @param string $file_name + * @return true + */ + public function delete(string $file_name) + { + $bucket = $this->config['bucket']; + try { + $this->client()->deleteObject($bucket, $file_name); + return true; + } catch ( OssException $e ) { + throw new UploadFileException($e->getMessage()); + } + + } + + public function thumb($file_path, $thumb_type) + { + $thumb_config = config('upload.thumb.thumb_type'); + $thumb_data = []; + foreach ($thumb_config as $k => $v) { + if ($thumb_type == 'all' || $thumb_type == $k || (is_array($thumb_type) && in_array($k, $thumb_type))) { + $width = $v['width']; + $height = $v['height']; + //拼装缩略路径 + $item_thumb = $file_path . '?x-oss-process=image/resize,h_' . $height . ',w_' . $width; + $thumb_data[$k] = $item_thumb; + } + } + + return $thumb_data; + } + +} diff --git a/niucloud/core/core/upload/BaseUpload.php b/niucloud/core/core/upload/BaseUpload.php new file mode 100644 index 00000000..6e367e7d --- /dev/null +++ b/niucloud/core/core/upload/BaseUpload.php @@ -0,0 +1,240 @@ +config = $config; + $this->storage_type = $config['storage_type']; + } + + /** + * 附件上传 + * @param string $dir + * @return mixed + */ + abstract protected function upload(string $dir); + + /** + * 抓取远程附件 + * @param string $url + * @param string|null $key + * @return mixed + */ + abstract protected function fetch(string $url, ?string $key); + + /** + * base64文件上云 + * @param string $base64_data + * @param string|null $key + * @return mixed + */ + abstract protected function base64(string $base64_data, ?string $key = null); + /** + * 附件删除 + * @param string $file_name + * @return mixed + */ + abstract protected function delete(string $file_name); + + /** + * 缩略图 + * @param string $file_path + * @param $thumb_type + * @return mixed + */ + abstract protected function thumb(string $file_path, $thumb_type); + + /** + * 读取文件 + * @param string $name + * @param bool $is_rename + */ + public function read(string $name, bool $is_rename = true) + { + $this->name = $name; + $this->file = request()->file($name); + if (empty($this->file)) + throw new UploadFileException(100012); + $this->file_info = [ + 'name' => $this->file->getOriginalName(),//文件原始名称 + 'mime' => $this->file->getOriginalMime(),//上传文件类型信息 + 'real_path' => $this->file->getRealPath(),//上传文件真实路径 + 'ext' => $this->file->getOriginalExtension(),//上传文件后缀 + 'size' => $this->file->getSize(),//上传文件大小 + ]; + if ($is_rename) { + $this->file_name = $this->createFileName(); + } else { + $this->file_name = $this->file_info['name']; + } + + } + + /** + * 设置文件类型 + * @param string $type + * @return $this + */ + public function setType(string $type) + { + $this->type = $type; + return $this; + } + + /** + * 校验文件是否合法 + */ + public function check() + { + + } + + /** + * 生成新的文件名 + * @return string + */ + public function createFileName(string $key = '', string $ext = '') + { + //DIRECTORY_SEPARATOR 常量 + $storage_tag = '_' . $this->storage_type; + if (empty($key)) { + return time() . md5($this->file_info['real_path']) . $storage_tag . '.' . $this->file_info['ext']; + } else { + return time() . md5($key) . $storage_tag . '.' . $ext; + } + + } + + /** + * 获取原始附件信息 + * @return mixed + */ + public function getFileInfo() + { + return $this->file_info; + } + + /** + * 获取上传文件的真实完整路径 + * @return mixed + */ + public function getRealPath() + { + return $this->file_info['real_path']; + } + + /** + * 获取生成的文件完整地址 + * @return string + */ + public function getFullPath(string $dir = '') + { + return $this->full_path ?: $this->concatFullPath($dir); + } + + /** + * 合并路径和文件名 + * @param string $dir + * @return string + */ + public function concatFullPath(string $dir = '') + { + $this->full_path = implode('/', array_filter([$dir, $this->getFileName()])); + return $this->full_path; + } + + /** + * 获取文件名 + * @return mixed + */ + public function getFileName() + { + return $this->file_name; + } + + public function getUrl(string $path = '') + { + $path = !empty($path) ? $path : $this->getFullPath(); + $domain = $this->config['domain'] ?? ''; + $domain = empty($domain) ? '' : $domain . '/'; + return $domain . $path; + } + + /** + * 验证 + * @param array $validate + * @return $this + */ + public function setValidate(array $validate = []) + { + $this->validate = $validate ?: config('upload.rules')[$this->type] ?? []; + return $this; + } + + /** + * 根据上传文件的类型来校验文件是否符合配置 + * @return void + */ + public function validate() + { + if (empty($this->file)) + throw new UploadFileException('UPLOAD_FAIL'); + $config['file_ext'] = $this->validate['ext'] ?? []; + $config['file_mime'] = $this->validate['mime'] ?? []; + $config['file_size'] = $this->validate['size'] ?? 0; + $rule = []; + $file_size = $config['file_size'] ?? 0; + if ($file_size > 0) { + $rule[] = 'fileSize:' . $file_size; + } + //验证上传文件类型 + $file_mime = $config['file_mime'] ?? []; + $file_ext = $config['file_ext'] ?? []; + if (!empty($file_ext)) { + $rule[] = 'fileExt:' . implode(',', $file_ext); + } + if (!empty($rule)) { + if (!in_array($this->file->getOriginalMime(), $file_mime)) { + throw new UploadFileException('UPLOAD_TYPE_NOT_SUPPORT'); + } + validate([$this->name => implode('|', $rule)])->check([$this->name => $this->file]); + } + + } +} diff --git a/niucloud/core/core/upload/Local.php b/niucloud/core/core/upload/Local.php new file mode 100644 index 00000000..872baa30 --- /dev/null +++ b/niucloud/core/core/upload/Local.php @@ -0,0 +1,253 @@ + 'top-left', + 'top-center' => 'top-center', + 'top-right' => 'top-right', + 'center-left' => 'center-left', + 'center' => 'center', + 'center-right' => 'center-right', + 'bottom-left' => 'bottom-left', + 'bottom-center' => 'bottom-center', + 'bottom-right' => 'bottom-right', + ); + + protected function initialize(array $config = []) + { + parent::initialize($config); + + } + + public function upload(string $dir) + { + $this->validate(); + + mkdirs_or_notexist($dir, 0777); + $this->file->move($dir, $this->file_name); + //错误一般是已经被抛出了 + return true; + } + + + /** + * 远程获取图片 + * @param string $url + * @param string|null $key + * @return true + */ + public function fetch(string $url, ?string $key) + { + try { + mkdirs_or_notexist(dirname($key), 0777); + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $content = curl_exec($ch); + curl_close($ch); + // $content = @file_get_contents($url);//file_get_contents下载网络图片慢,更换为curl下载 + if (!empty($content)) { + file_put_contents($key, $content); + + + $image_info = getimagesize($key); + $image_type = $image_info[2]; +// if($image_type == IMAGETYPE_JPEG){ +// // 保存图片为PNG格式 +// $image = imagecreatefromjpeg($key); +// }else if($image_type == IMAGETYPE_PNG){ +// // 保存图片为PNG格式 +// $image = imagecreatefrompng($key); +// } + if($image_type == IMAGETYPE_WEBP){ + // 保存图片为PNG格式 + $image = imagecreatefromwebp($key); + } + // 创建图片资源 + // 检查图片是否创建成功 + if (!empty($image)){ + + // 图片类型常量定义:IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF + if ($image_type == IMAGETYPE_WEBP) { + $temp_arr = explode('.', $key); + $ext = end($temp_arr); + if($ext == 'jpg' || $ext == 'jpeg'){ + // 保存图片为PNG格式 + imagejpeg($image, $key); + }else if($ext = 'png'){ + // 保存图片为PNG格式 + imagepng($image, $key); + } + } + // 释放内存 + imagedestroy($image); + } + + } else { + throw new UploadFileException(203006); + } + return true; + } catch ( Exception $e ) { + throw new UploadFileException($e->getMessage()); + } + } + + /** + * base64转图片 + * @param string $content + * @param string|null $key + * @return true + */ + public function base64(string $content, ?string $key = null) + { + + mkdirs_or_notexist(dirname($key)); + file_put_contents(url_to_path($key), base64_decode($content)); + return true; + } + + /** + * 删除本地附件 + * @param string $file_name + * @return bool + */ + public function delete(string $file_name) + { + $file_path = url_to_path($file_name); + if (file_exists($file_path)) { + $result = unlink($file_path); +// throw new UploadFileException(100013); + }else{ + $result = true; + } + //顺便删除相关的缩略图 + $dirname = dirname($file_name); + $file_list = []; + search_dir($dirname, $file_list); + if(!empty($file_list)){ + $file_arr = explode('/', $file_name); + $only_file_name = end($file_arr); + foreach($file_list as $v){ + if(str_contains($v, $only_file_name) && file_exists($v)){ + unlink($v); + } + } + } + return $result; + } + + /** + * 缩略图 + * @param $file_path + * @param $thumb_type + * @return array + * @throws Exception + */ + public function thumb($file_path, $thumb_type) + { + //todo 判断缩略图是否存在 + $thumb_config = config('upload.thumb.thumb_type'); + // …… + //获取文件原名 获取 + $file_arr = explode('/', $file_path); + $file_name = end($file_arr); + $thumb_list = []; + //获取文件后缀 + foreach ($thumb_config as $k => $v) { + if ($thumb_type == 'all' || $thumb_type == $k || (is_array($thumb_type) && in_array($k, $thumb_type))) { + $new_width = $v['width']; + $new_height = $v['height']; + $new_thumb_path = str_replace($file_name, $new_width . 'x' . $new_height . '_' . $file_name, $file_path); + + if (!file_exists($new_thumb_path)) { + $editor = Grafika::createEditor(); + $editor->open($image, $file_path); + $editor->resizeFit($image, $new_width, $new_height); + //新缩略图文件名称 + $editor->save($image, $new_thumb_path, null, null, false, 0777); + } + $thumb_list[$k] = $new_thumb_path; + } + + } + return $thumb_list; + } + + /** + * 图片水印 + * @param $file_path + * @return mixed + * @throws Exception + */ + public function water($file_path) + { + $water_config = []; + if (!empty($water_config)) { + $status = $water_config['status'];//是否启用 + if ($status) { + $editor = Grafika::createEditor(); + $editor->open($image, $file_path); + if ($water_config['type'] == 'image') { + $water_image = $water_config['image']; + if (!empty($water_image)) { + //判断水印图片是否是本地图片 + if (check_file_is_remote($water_image)) { + $file_arr = explode('.', $water_image); + $ext_name = end($file_arr); + $name = $this->createFileName($water_image, $ext_name); + $watermark_image = 'upload/water/' . $name; + $this->fetch($water_image, $watermark_image); + } + if (file_exists($water_image)) { + + } + $editor->open($image1, $water_config['image']); + $editor->blend($image, $image1, 'normal', $water_config['opacity'], $this->position[$water_config['position']], $water_config['offset_x'], $water_config['offset_y']); + } + } else { + if ($water_config['text']) { + $position = $this->position[$water_config['position']]; + $offset_x = $water_config['offset_x'];//水平偏移值 + $offset_y = $water_config['offset_y'];//垂直偏移值 + $width = $image->getWidth(); + $height = $image->getHeight(); + + //获取文字信息 + $info = imagettfbbox($water_config['size'], $water_config['angle'], $water_config['font'], $water_config['text']); + $minx = min($info[0], $info[2], $info[4], $info[6]); + $maxx = max($info[0], $info[2], $info[4], $info[6]); + $miny = min($info[1], $info[3], $info[5], $info[7]); + $maxy = max($info[1], $info[3], $info[5], $info[7]); + /* 计算文字初始坐标和尺寸 */ + $x = $minx; + $y = abs($miny); + $w = $maxx - $minx; + $h = $maxy - $miny; + //转化坐标 + $position = new Position($position, $offset_x, $offset_y); + // Position is for $image2. $image1 is canvas. + list($offset_x, $offset_y) = $position->getXY($width, $height, $w, $h); + + $editor->text($image, $water_config['text'], $water_config['size'], $offset_x, $offset_y, new Color($water_config['color']), $water_config['font'], $water_config['angle']); + } + $editor->save($image, $file_path); + + + } + } + return $file_path; + } + } +} diff --git a/niucloud/core/core/upload/Qiniu.php b/niucloud/core/core/upload/Qiniu.php new file mode 100644 index 00000000..ea3ecbdf --- /dev/null +++ b/niucloud/core/core/upload/Qiniu.php @@ -0,0 +1,180 @@ + 'NorthWest', + 'top-center' => 'North', + 'top-right' => 'NorthEast', + 'center-left' => 'West', + 'center' => 'Center', + 'center-right' => 'East', + 'bottom-left' => 'SouthWest', + 'bottom-center' => 'South', + 'bottom-right' => 'SouthEast', + ); + + protected function initialize(array $config = []) + { + parent::initialize($config); + } + + /** + * 获取一个鉴权对象 + * @return Auth + */ + public function auth() + { + $access_key = $this->config['access_key']; + $secret_key = $this->config['secret_key']; + return new Auth($access_key, $secret_key); + } + + /** + * @throws Exception + */ + public function upload(string $dir) + { + $this->validate(); + $bucket = $this->config['bucket']; + //todo 这儿可以定义凭证的过期时间 + $up_token = $this->auth()->uploadToken($bucket); + // 初始化 UploadManager 对象并进行文件的上传。 + $upload_mgr = new UploadManager(); + [$ret, $err] = $upload_mgr->putFile($up_token, $this->getFullPath($dir), $this->getRealPath()); + if ($err !== null) + throw new UploadFileException($err->message()); + return true; + } + + /** + * 抓取网络资源到空间 + * @param string $url + * @param string|null $key + * @return true + * @throws Exception + */ + public function fetch(string $url, ?string $key = null) + { + $bucket = $this->config['bucket']; + $auth = $this->auth(); + if (!str_contains($url, 'http://') && !str_contains($url, 'https://')) { + $token = $auth->uploadToken($bucket); + $upload_mgr = new UploadManager(); + [$ret, $err] = $upload_mgr->putFile($token, $key, $url); + } else { + //抓取网络资源到空间 + $bucket_manager = new BucketManager($auth); + [$ret, $err] = $bucket_manager->fetch($url, $bucket, $key);//不指定key时,以文件内容的hash作为文件名 + } + + if ($err !== null) + throw new UploadFileException($err->message()); + return true; + } + + /** + * base64资源上传 + * @param string $base64_data + * @param string|null $key + * @return true + */ + public function base64(string $base64_data, ?string $key = null) + { + $bucket = $this->config['bucket']; + $auth = $this->auth(); + $up_token = $this->auth()->uploadToken($bucket); + // 初始化 UploadManager 对象并进行文件的上传。 + $upload_mgr = new UploadManager(); + //将 base64 编码的图片数据解码 + $base64_file = base64_decode($base64_data); + if (!$base64_file) throw new UploadFileException('FILE_ERROR'); + // 初始化 UpLoadManager 对象并进行文件的上传 + list($ret, $err) = $upload_mgr->put($up_token, $key, $base64_file); + if ($err !== null) throw new UploadFileException($err->message); + return true; + } + + /** + * 删除空间中的文件 + * @param string $file_name + * @return true + */ + public function delete(string $file_name) + { + $bucket = $this->config['bucket']; + $auth = $this->auth(); + $config = new Config(); + $bucket_manager = new BucketManager($auth, $config); + [$ret, $err] = $bucket_manager->delete($bucket, $file_name); + if ($err !== null) + throw new UploadFileException($err->message()); + return true; + } + + public function thumb($file_path, $thumb_type) + { +// mageView2/1/w/400/h/600/q/85 + $thumb_config = config('upload.thumb.thumb_type'); + $thumb_data = []; + foreach ($thumb_config as $k => $v) { + if ($thumb_type == 'all' || $thumb_type == $k || (is_array($thumb_type) && in_array($k, $thumb_type))) { +// ?x-oss-process=image/resize,m_fill,w_200,h_600,quality,q_60 + $width = $v['width']; + $height = $v['height']; + //拼装缩略路径 + $item_thumb = $file_path . '?imageView2/2/w/' . $width . '/h/' . $height; + $thumb_data[$k] = $item_thumb; + } + } + + return $thumb_data; + } + + + /** + * 图片水印 + * @param $file_path + * @return mixed + * @throws Exception + */ + public function water($file_path) + { + $water_config = []; + $water_path = $file_path; + if (!empty($water_config)) { + $status = $water_config['status'];//是否启用 + if ($status) { + //判断当前的云图片是否存在?,存在符号的话需要用|连接 + if (str_contains($file_path, '?')) { + $water_path .= '|watermark'; + } else { + $water_path .= '?watermark'; + } + if ($water_config['type'] == 'image') { + $water_image = $water_config['image']; + if (!empty($water_image)) { + $water_path .= '/1/image/' . base64_encode($water_image) . '/gravity/' . $this->position[$water_config['position']] . '/dissolve/' . $water_config['opacity'] . '/dx/' . $water_config['offset_x'] . '/dy/' . $water_config['offset_y']; + } + } else { + $water_path .= '/2/text/' . base64_encode($water_config['text']) . '/font/' . base64_encode($water_config['font']) . '/fill/' . base64_encode($water_config['color']) . '/fontsize/' . $water_config['size'] . '/gravity/' . $this->position[$water_config['position']] . '/dx/' . $water_config['offset_x'] . '/dy/' . $water_config['offset_y']; + } + } + } + return $water_path; + } + +} \ No newline at end of file diff --git a/niucloud/core/core/upload/Tencent.php b/niucloud/core/core/upload/Tencent.php new file mode 100644 index 00000000..a5b03ceb --- /dev/null +++ b/niucloud/core/core/upload/Tencent.php @@ -0,0 +1,195 @@ + 'northwest', + 'top-center' => 'north', + 'top-right' => 'northeast', + 'center-left' => 'west', + 'center' => 'center', + 'center-right' => 'east', + 'bottom-left' => 'southwest', + 'bottom-center' => 'south', + 'bottom-right' => 'southeast', + ); + + protected function initialize(array $config = []) + { + parent::initialize($config); + } + + /** + * 获取服务主体 + * @return Client + */ + public function client() + { + $secret_id = $this->config['access_key']; //替换为用户的 secretId,请登录访问管理控制台进行查看和管理,https://console.tencentcloud.com/cam/capi + $secret_key = $this->config['secret_key']; //替换为用户的 secretKey,请登录访问管理控制台进行查看和管理,https://console.tencentcloud.com/cam/capi + $region = $this->config['region']; //替换为用户的 region,已创建桶归属的region可以在控制台查看,https://console.tencentcloud.com/cos5/bucket + + return new Client( + array( + 'region' => $region, +// 'schema' => 'https', //协议头部,默认为http + 'credentials' => array( + 'secretId' => $secret_id, + 'secretKey' => $secret_key) + ) + ); + } + + + /** + * 执行上传 + * @param string $dir + * @return true + */ + public function upload(string $dir) + { + $this->validate(); + $bucket = $this->config['bucket']; + try { + $result = $this->client()->putObject(array( + 'Bucket' => $bucket, //存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.tencentcloud.com/cos5/bucket + 'Key' => $this->getFullPath($dir), + 'Body' => fopen($this->getRealPath(), 'rb'), + )); + // 请求成功 + return true; + } catch ( Exception $e ) { + throw new UploadFileException($e->getMessage()); + } + } + + /** + * base文件上云 + * @param string $base64_data + * @param string|null $key + * @return true + */ + public function base64(string $base64_data, ?string $key = null) + { + $bucket = $this->config['bucket']; + try { + $base64_file = base64_decode($base64_data); + if (!$base64_file) throw new UploadFileException('FILE_ERROR'); + $result = $this->client()->putObject(array( + 'Bucket' => $bucket, //存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.tencentcloud.com/cos5/bucket + 'Key' => $key, + 'Body' => $base64_file, + )); + // 请求成功 + return true; + } catch ( Exception $e ) { + throw new UploadFileException($e->getMessage()); + } + } + /** + * notes: 抓取远程资源(最大支持上传5G文件) + * @param string $url + * @param string|null $key + * @return true + */ + public function fetch(string $url, ?string $key = null) + { + + $bucket = $this->config['bucket']; + try { + $result = $this->client()->putObject(array( + 'Bucket' => $bucket, //存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.tencentcloud.com/cos5/bucket + 'Key' => $key, + 'Body' => fopen($url, 'rb'), + )); + // 请求成功 + return true; + } catch ( Exception $e ) { + throw new UploadFileException($e->getMessage()); + } + } + + /** + * 删除一个简单对象 + * @param string $file_name + * @return true + */ + public function delete(string $file_name) + { + $bucket = $this->config['bucket']; + try { + $this->client()->deleteObject(array( + 'Bucket' => $bucket, + 'Key' => $file_name + )); + return true; + } catch ( Exception $e ) { + throw new UploadFileException($e->getMessage()); + } + } + + public function thumb($file_path, $thumb_type) + { + //腾讯云缩略图地址 + + $thumb_config = config('upload.thumb.thumb_type'); + $thumb_data = []; + foreach ($thumb_config as $k => $v) { + if ($thumb_type == 'all' || $thumb_type == $k || (is_array($thumb_type) && in_array($k, $thumb_type))) { +// ?x-oss-process=image/resize,m_fill,w_200,h_600,quality,q_60 + $width = $v['width']; + $height = $v['height']; + //拼装缩略路径 + $item_thumb = $file_path . '?imageMogr2/thumbnail/' . $width . 'x' . $height; + $thumb_data[$k] = $item_thumb; + } + } + + return $thumb_data; + } + + + /** + * 图片水印 + * @param $file_path + * @return mixed + * @throws Exception + */ + public function water($file_path) + { + $water_config = []; + $water_path = $file_path; + if (!empty($water_config)) { + $status = $water_config['status'];//是否启用 + if($status){ + //判断当前的云图片是否存在?,存在符号的话需要用|连接 + if(str_contains($file_path, '?')){ + $water_path .= '&watermark'; + }else{ + $water_path .= '?watermark'; + } + if ($water_config['type'] == 'image') { + $water_image = $water_config['image']; + if(!empty($water_image)){ + //http://examples-1251000004.cos.ap-shanghai.myqcloud.com/sample.jpeg?watermark/1/image/aHR0cDovL2V4YW1wbGVzLTEyNTEwMDAwMDQucGljc2gubXlxY2xvdWQuY29tL3NodWl5aW4uanBn/gravity/southeast + $water_path .= '/1/image/' . base64_encode($water_image) . '/gravity/' . $this->position[$water_config['position']] . '/blogo/1/dx/' . $water_config['offset_x'] . '/dy/' . $water_config['offset_y'].'/dissolve/'.$water_config['opacity']; + } + } else { + //http://examples-1251000004.cos.ap-shanghai.myqcloud.com/sample.jpeg?q-sign-algorithm=&watermark/2/text/6IW-6K6v5LqRwrfkuIfosaHkvJjlm74/fill/IzNEM0QzRA/fontsize/20/dissolve/50/gravity/northeast/dx/20/dy/20/batch/1/degree/45 + $water_path .= '/2/text/' . base64_encode($water_config['text']) . '/font/' . base64_encode($water_config['font']) . '/fill/' . base64_encode($water_config['color']) . '/fontsize/' . $water_config['size'] . '/gravity/' . $this->position[$water_config['position']] . '/dx/' . $water_config['offset_x'] . '/dy/' . $water_config['offset_y']; + } + } + } + return $water_path; + } +} diff --git a/niucloud/core/core/upload/UploadLoader.php b/niucloud/core/core/upload/UploadLoader.php new file mode 100644 index 00000000..75175677 --- /dev/null +++ b/niucloud/core/core/upload/UploadLoader.php @@ -0,0 +1,44 @@ +color_black = new \BCGColor(0, 0, 0); + $this->color_white = new \BCGColor(255, 255, 255); + $this->size = $size; + $this->fontPath = str_replace("\\", "/", root_path() . "core/util/barcode/font/Arial.ttf"); + $this->font = new \BCGFontFile($this->fontPath, $this->size); + $this->content = $content; + } + + //生成条形码 + public function generateBarcode($path = '', $scale = 2) + { + try { + $code = new \BCGcode128(); + $code->setScale($scale); + $code->setThickness(30); // 条形码的厚度 + $code->setForegroundColor($this->color_black); // 条形码颜色 + $code->setBackgroundColor($this->color_white); // 空白间隙颜色 + $code->setFont($this->font); // + $code->parse($this->content); // 条形码需要的数据内容 + } catch (Exception $exception) { + $this->drawException = $exception; + } + + if ($path == '') { + $path = 'upload/barcode';//条形码存放路径 + } + + if (!is_dir($path)) { + $mode = intval('0777', 8); + mkdir($path, $mode, true); + chmod($path, $mode); + } + $path = $path . '/' . $this->content . '.png'; + if (file_exists($path)) { + unlink($path); + } + + //根据以上条件绘制条形码 + $drawing = new \BCGDrawing('', $this->color_white); + if ($this->drawException) { + $drawing->drawException($this->drawException); + } else { + $drawing->setBarcode($code); + $drawing->setFilename($path); + $drawing->draw(); + } + // 生成PNG格式的图片 + $drawing->finish(\BCGDrawing::IMG_FORMAT_PNG); + return $path; + } +} + +?> \ No newline at end of file diff --git a/niucloud/core/core/util/DbBackup.php b/niucloud/core/core/util/DbBackup.php new file mode 100644 index 00000000..5bad871b --- /dev/null +++ b/niucloud/core/core/util/DbBackup.php @@ -0,0 +1,532 @@ + './backup/', + // 数据库备份卷大小 + 'part' => 20971520, + // 数据库备份文件是否启用压缩 0不压缩 1 压缩 + 'compress' => 0, + // 数据库备份文件压缩级别 1普通 4 一般 9最高 + 'level' => 9, + ); + + /** + * 数据库备份构造方法 + * @param array $file 备份或还原的文件信息 + * @param array $config 备份配置信息 + */ + public function __construct($config = []) + { + $this->config = is_array($config) && !empty($config) ? array_merge($this->config, $config) : $this->config; + //初始化文件名 + $this->setFile(); + //初始化数据库连接参数 + $this->setDbConn(); + //检查文件是否可写 + if (!$this->checkPath($this->config['path'])) { + throw new \Exception("The current directory is not writable"); + } + } + + /** + * 设置脚本运行超时时间 + * 0表示不限制,支持连贯操作 + */ + public function setTimeout($time = null) + { + if (!is_null($time)) { + set_time_limit($time) || ini_set("max_execution_time", $time); + } + return $this; + } + + /** + * 设置数据库连接必备参数 + * @param array $dbconfig 数据库连接配置信息 + * @return object + */ + public function setDbConn($dbconfig = []) + { + if (empty($dbconfig)) { + $this->dbconfig = config('database.connections.'.config('database.default')); + } else { + $this->dbconfig = $dbconfig; + } + return $this; + } + + /** + * 设置备份文件名 + * + * @param Array $file 文件名字 + * @return object + */ + public function setFile($file = null) + { + if (is_null($file)) { + $this->file = ['name' => date('Ymd-His'), 'part' => 1]; + } else { + if (!array_key_exists("name", $file) && !array_key_exists("part", $file)) { + $this->file = $file['1']; + } else { + $this->file = $file; + } + } + return $this; + } + + /** + * 数据库表列表 + * + * @param null $table + * @param int $type + * @return array + */ + public function dataList($table = null, $type = 1) + { + if (is_null($table)) { + $list = Db::query("SHOW TABLE STATUS"); + } else { + if ($type) { + $list = Db::query("SHOW FULL COLUMNS FROM {$table}"); + } else { + $list = Db::query("show columns from {$table}"); + } + } + + return array_map('array_change_key_case', $list); + } + + /** + * 数据库备份文件列表 + * + * @return array + */ + public function fileList() + { + if (!is_dir($this->config['path'])) { + mkdir($this->config['path'], 0755, true); + } + $path = realpath($this->config['path']); + $flag = \FilesystemIterator::KEY_AS_FILENAME; + $glob = new \FilesystemIterator($path, $flag); + $list = array(); + foreach ($glob as $name => $file) { + if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) { + $name1 = $name; + $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d'); + $date = "{$name[0]}-{$name[1]}-{$name[2]}"; + $time = "{$name[3]}:{$name[4]}:{$name[5]}"; + $part = $name[6]; + if (isset($list["{$date} {$time}"])) { + $info = $list["{$date} {$time}"]; + $info['part'] = max($info['part'], $part); + $info['size'] = $info['size'] + $file->getSize(); + } else { + $info['part'] = $part; + $info['size'] = $file->getSize(); + } + $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION)); + $info['name'] = $name1; + $info['compress'] = $extension === 'SQL' ? '-' : $extension; + $info['time'] = strtotime("{$date} {$time}"); + $list["{$date} {$time}"] = $info; + } + } + return $list; + } + + /** + * 获取文件名称 + * + * @param string $type + * @param int $time + * @return array|false|mixed|string + * @throws \Exception + */ + public function getFile($type = '', $time = 0) + { + // + if (!is_numeric($time)) { + throw new \Exception("{$time} Illegal data type"); + } + switch ($type) { + case 'time': + $name = date('Ymd-His', $time).'-*.sql*'; + $path = realpath($this->config['path']).DIRECTORY_SEPARATOR.$name; + return glob($path); + break; + case 'timeverif': + $name = date('Ymd-His', $time).'-*.sql*'; + $path = realpath($this->config['path']).DIRECTORY_SEPARATOR.$name; + $files = glob($path); + $list = array(); + foreach ($files as $name) { + $basename = basename($name); + $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d'); + $gz = preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql.gz$/', $basename); + $list[$match[6]] = array($match[6], $name, $gz); + } + $last = end($list); + if (count($list) === $last[0]) { + return $list; + } else { + throw new \Exception("File {$files['0']} may be damaged, please check again"); + } + break; + case 'pathname': + return "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql"; + break; + case 'filename': + return "{$this->file['name']}-{$this->file['part']}.sql"; + break; + case 'filepath': + return $this->config['path']; + break; + default: + $arr = array( + 'pathname' => "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql", + 'filename' => "{$this->file['name']}-{$this->file['part']}.sql", + 'filepath' => $this->config['path'], 'file' => $this->file + ); + return $arr; + } + } + + /** + * 删除备份文件 + * + * @param $time + * @return mixed + * @throws \Exception + */ + public function delFile($time) + { + if ($time) { + $file = $this->getFile('time', $time); + array_map("unlink", $file); + $file = $this->getFile('time', $time); + if (count($file)) { + throw new \Exception("File ".implode('##', $file)." deleted failed"); + } else { + return $time; + } + } else { + throw new \Exception("{$time} Time parameter is incorrect"); + } + } + + /** + * 下载备份 + * + * @param string $time + * @param integer $part + * @return array|mixed|string + */ + public function downloadFile($time, $part = 0) + { + $file = $this->getFile('time', $time); + $fileName = $file[$part]; + if (file_exists($fileName)) { + ob_end_clean(); + header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); + header('Content-Description: File Transfer'); + header('Content-Type: application/octet-stream'); + header('Content-Length: '.filesize($fileName)); + header('Content-Disposition: attachment; filename='.basename($fileName)); + readfile($fileName); + } else { + throw new \Exception("{$time} File is abnormal"); + } + } + + public function setSqlMode() { + Db::query("SET sql_mode = '';"); + return true; + } + + /** + * 导入表 + * + * @param $start + * @param $time + * @return array|false|int + * @throws Exception + */ + public function import($start, $time) + { + //还原数据 + $this->file = $this->getFile('time', $time); + if ($this->config['compress']) { + $gz = gzopen($this->file[0], 'r'); + $size = 0; + } else { + $size = filesize($this->file[0]); + $gz = fopen($this->file[0], 'r'); + } + $sql = ''; + if ($start) { + $this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start); + } + for ($i = 0; $i < 1000; $i++) { + $sql .= $this->config['compress'] ? gzgets($gz) : fgets($gz); + if (preg_match('/.*;$/', trim($sql))) { + if (false !== Db::query($sql)) { + $start += strlen($sql); + } else { + return false; + } + $sql = ''; + } elseif ($this->config['compress'] ? gzeof($gz) : feof($gz)) { + return 0; + } + } + return array($start, $size); + } + + /** + * 写入初始数据 + * + * @return boolean true - 写入成功,false - 写入失败 + */ + public function backupInit() + { + $sql = "-- -----------------------------\n"; + $sql .= "-- Think MySQL Data Transfer \n"; + $sql .= "-- \n"; + $sql .= "-- Host : ".$this->dbconfig['hostname']."\n"; + $sql .= "-- Port : ".$this->dbconfig['hostport']."\n"; + $sql .= "-- Database : ".$this->dbconfig['database']."\n"; + $sql .= "-- \n"; + $sql .= "-- Part : #{$this->file['part']}\n"; + $sql .= "-- Date : ".date("Y-m-d H:i:s")."\n"; + $sql .= "-- -----------------------------\n\n"; + $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n"; + return $this->write($sql); + } + + /** + * 查询单条 + * @param $sql + * @return array|mixed + */ + public function selectOne($sql) { + $result = Db::query($sql); + return $result[0] ?? []; + } + + /** + * 备份表结构 + * + * @param string $table 表名 + * @param integer $start 起始行数 + * @return boolean false - 备份失败 + */ + public function backup($table, $start = 0) + { + // 备份表结构 + if (0 == $start) { + $result = $this->selectOne("SHOW CREATE TABLE `{$table}`"); + $sql = "\n"; + $sql .= "-- -----------------------------\n"; + $sql .= "-- Table structure for `{$table}`\n"; + $sql .= "-- -----------------------------\n"; + $sql .= "DROP TABLE IF EXISTS `{$table}`;\n"; + $sql .= trim($result['Create Table']).";\n\n"; + if (false === $this->write($sql)) { + return false; + } + } + //数据总数 + $result = $this->selectOne("SELECT COUNT(*) AS count FROM `{$table}`"); + $count = $result['count']; + //备份表数据 + if ($count) { + //写入数据注释 + if (0 == $start) { + $sql = "-- -----------------------------\n"; + $sql .= "-- Records of `{$table}`\n"; + $sql .= "-- -----------------------------\n"; + $this->write($sql); + } + //备份数据记录 + $result = Db::query("SELECT * FROM `{$table}` LIMIT {$start}, 1000"); + $sql = "INSERT INTO `{$table}` VALUES\n"; + foreach ($result as $index => $row) { + $row = array_map(function ($item){ + return is_string($item) ? addslashes($item) : $item; + }, $row); + $sql .= "('".str_replace(array("\r", "\n"), array('\\r', '\\n'), + implode("', '", $row))."')"; + $sql .= $index < (count($result) - 1) ? ",\n" : ";\n"; + } + + if (false === $this->write($sql)) { + return false; + } + //还有更多数据 + if ($count > $start + 1000) { + return $this->backup($table, $start + 1000); + } + } + //备份下一表 + return true; + } + + /** + * 优化表 + * + * @param String $tables 表名 + * @return String $tables + */ + public function optimize($tables = null) + { + if ($tables) { + if (is_array($tables)) { + $tables = implode('`,`', $tables); + $list = db ::select("OPTIMIZE TABLE `{$tables}`"); + } else { + $list = Db::query("OPTIMIZE TABLE `{$tables}`"); + } + if ($list) { + return $tables; + } else { + throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!"); + } + } else { + throw new \Exception("Please specify the table to be repaired!"); + } + } + + /** + * 修复表 + * + * @param String $tables 表名 + * @return String $tables + */ + public function repair($tables = null) + { + if ($tables) { + if (is_array($tables)) { + $tables = implode('`,`', $tables); + $list = Db::query("REPAIR TABLE `{$tables}`"); + } else { + $list = Db::query("REPAIR TABLE `{$tables}`"); + } + if ($list) { + + return $list; + } else { + throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!"); + } + } else { + throw new \Exception("Please specify the table to be repaired!"); + } + } + + /** + * 写入SQL语句 + * + * @param string $sql 要写入的SQL语句 + * @return boolean true - 写入成功,false - 写入失败! + */ + private function write($sql) + { + $size = strlen($sql); + //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%, + //一般情况压缩率都会高于50%; + $size = $this->config['compress'] ? $size / 2 : $size; + $this->open($size); + return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql); + } + + /** + * 打开一个卷,用于写入数据 + * + * @param integer $size 写入数据的大小 + */ + private function open($size) + { + if ($this->fp) { + $this->size += $size; + if ($this->size > $this->config['part']) { + $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp); + $this->fp = null; + $this->file['part']++; + session('backup_file', $this->file); + $this->backupInit(); + } + } else { + $backuppath = $this->config['path']; + $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql"; + if ($this->config['compress']) { + $filename = "{$filename}.gz"; + $this->fp = @gzopen($filename, "a{$this->config['level']}"); + } else { + $this->fp = @fopen($filename, 'a'); + } + $this->size = filesize($filename) + $size; + } + } + + /** + * 检查目录是否可写 + * + * @param string $path 目录 + * @return boolean + */ + protected function checkPath($path) + { + if (is_dir($path)) { + return true; + } + if (mkdir($path, 0755, true)) { + return true; + } else { + return false; + } + } + + /** + * 析构方法,用于关闭文件资源 + */ + public function __destruct() + { + if ($this->fp) { + $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp); + } + } + +} diff --git a/niucloud/core/core/util/QRcode.php b/niucloud/core/core/util/QRcode.php new file mode 100644 index 00000000..52c92ce7 --- /dev/null +++ b/niucloud/core/core/util/QRcode.php @@ -0,0 +1,3312 @@ + + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + + +/* + * Version: 1.1.4 + * Build: 2010100721 + */ + + + +//---- qrconst.php ----------------------------- + + + + + +/* + * PHP QR Code encoder + * + * Common constants + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + // Encoding modes + + define('QR_MODE_NUL', -1); + define('QR_MODE_NUM', 0); + define('QR_MODE_AN', 1); + define('QR_MODE_8', 2); + define('QR_MODE_KANJI', 3); + define('QR_MODE_STRUCTURE', 4); + + // Levels of error correction. + + define('QR_ECLEVEL_L', 0); + define('QR_ECLEVEL_M', 1); + define('QR_ECLEVEL_Q', 2); + define('QR_ECLEVEL_H', 3); + + // Supported output formats + + define('QR_FORMAT_TEXT', 0); + define('QR_FORMAT_PNG', 1); + + class qrstr { + public static function set(&$srctab, $x, $y, $repl, $replLen = false) { + $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); + } + } + + + +//---- merged_config.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Config file, tuned-up for merged verion + */ + + define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there + define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true + define('QR_LOG_DIR', false); // default error logs dir + + define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code + define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly + define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false + + define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images + + + + +//---- qrtools.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Toolset, handy and debug utilites. + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRtools { + + //---------------------------------------------------------------------- + public static function binarize($frame) + { + $len = count($frame); + foreach ($frame as &$frameLine) { + + for($i=0; $i<$len; $i++) { + $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0'; + } + } + + return $frame; + } + + //---------------------------------------------------------------------- + public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') + { + $barcode_array = array(); + + if (!is_array($mode)) + $mode = explode(',', $mode); + + $eccLevel = 'L'; + + if (count($mode) > 1) { + $eccLevel = $mode[1]; + } + + $qrTab = QRcode::text($code, false, $eccLevel); + $size = count($qrTab); + + $barcode_array['num_rows'] = $size; + $barcode_array['num_cols'] = $size; + $barcode_array['bcode'] = array(); + + foreach ($qrTab as $line) { + $arrAdd = array(); + foreach(str_split($line) as $char) + $arrAdd[] = ($char=='1')?1:0; + $barcode_array['bcode'][] = $arrAdd; + } + + return $barcode_array; + } + + //---------------------------------------------------------------------- + public static function clearCache() + { + self::$frames = array(); + } + + //---------------------------------------------------------------------- + public static function buildCache() + { + QRtools::markTime('before_build_cache'); + + $mask = new QRmask(); + for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) { + $frame = QRspec::newFrame($a); + if (QR_IMAGE) { + $fileName = QR_CACHE_DIR.'frame_'.$a.'.png'; + QRimage::png(self::binarize($frame), $fileName, 1, 0); + } + + $width = count($frame); + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + for ($maskNo=0; $maskNo<8; $maskNo++) + $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + } + + QRtools::markTime('after_build_cache'); + } + + //---------------------------------------------------------------------- + public static function log($outfile, $err) + { + if (QR_LOG_DIR !== false) { + if ($err != '') { + if ($outfile !== false) { + file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); + } else { + file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); + } + } + } + } + + //---------------------------------------------------------------------- + public static function dumpMask($frame) + { + $width = count($frame); + for($y=0;$y<$width;$y++) { + for($x=0;$x<$width;$x++) { + echo ord($frame[$y][$x]).','; + } + } + } + + //---------------------------------------------------------------------- + public static function markTime($markerId) + { + list($usec, $sec) = explode(" ", microtime()); + $time = ((float)$usec + (float)$sec); + + if (!isset($GLOBALS['qr_time_bench'])) + $GLOBALS['qr_time_bench'] = array(); + + $GLOBALS['qr_time_bench'][$markerId] = $time; + } + + //---------------------------------------------------------------------- + public static function timeBenchmark() + { + self::markTime('finish'); + + $lastTime = 0; + $startTime = 0; + $p = 0; + + echo ' + + '; + + foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) { + if ($p > 0) { + echo ''; + } else { + $startTime = $thisTime; + } + + $p++; + $lastTime = $thisTime; + } + + echo ' + + +
BENCHMARK
till '.$markerId.': '.number_format($thisTime-$lastTime, 6).'s
TOTAL: '.number_format($lastTime-$startTime, 6).'s
'; + } + + } + + //########################################################################## + + QRtools::markTime('start'); + + + + +//---- qrspec.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * QR Code specifications + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * The following data / specifications are taken from + * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) + * or + * "Automatic identification and data capture techniques -- + * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('QRSPEC_VERSION_MAX', 40); + define('QRSPEC_WIDTH_MAX', 177); + + define('QRCAP_WIDTH', 0); + define('QRCAP_WORDS', 1); + define('QRCAP_REMINDER', 2); + define('QRCAP_EC', 3); + + class QRspec { + + public static $capacity = array( + array( 0, 0, 0, array( 0, 0, 0, 0)), + array( 21, 26, 0, array( 7, 10, 13, 17)), // 1 + array( 25, 44, 7, array( 10, 16, 22, 28)), + array( 29, 70, 7, array( 15, 26, 36, 44)), + array( 33, 100, 7, array( 20, 36, 52, 64)), + array( 37, 134, 7, array( 26, 48, 72, 88)), // 5 + array( 41, 172, 7, array( 36, 64, 96, 112)), + array( 45, 196, 0, array( 40, 72, 108, 130)), + array( 49, 242, 0, array( 48, 88, 132, 156)), + array( 53, 292, 0, array( 60, 110, 160, 192)), + array( 57, 346, 0, array( 72, 130, 192, 224)), //10 + array( 61, 404, 0, array( 80, 150, 224, 264)), + array( 65, 466, 0, array( 96, 176, 260, 308)), + array( 69, 532, 0, array( 104, 198, 288, 352)), + array( 73, 581, 3, array( 120, 216, 320, 384)), + array( 77, 655, 3, array( 132, 240, 360, 432)), //15 + array( 81, 733, 3, array( 144, 280, 408, 480)), + array( 85, 815, 3, array( 168, 308, 448, 532)), + array( 89, 901, 3, array( 180, 338, 504, 588)), + array( 93, 991, 3, array( 196, 364, 546, 650)), + array( 97, 1085, 3, array( 224, 416, 600, 700)), //20 + array(101, 1156, 4, array( 224, 442, 644, 750)), + array(105, 1258, 4, array( 252, 476, 690, 816)), + array(109, 1364, 4, array( 270, 504, 750, 900)), + array(113, 1474, 4, array( 300, 560, 810, 960)), + array(117, 1588, 4, array( 312, 588, 870, 1050)), //25 + array(121, 1706, 4, array( 336, 644, 952, 1110)), + array(125, 1828, 4, array( 360, 700, 1020, 1200)), + array(129, 1921, 3, array( 390, 728, 1050, 1260)), + array(133, 2051, 3, array( 420, 784, 1140, 1350)), + array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30 + array(141, 2323, 3, array( 480, 868, 1290, 1530)), + array(145, 2465, 3, array( 510, 924, 1350, 1620)), + array(149, 2611, 3, array( 540, 980, 1440, 1710)), + array(153, 2761, 3, array( 570, 1036, 1530, 1800)), + array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35 + array(161, 3034, 0, array( 600, 1120, 1680, 1980)), + array(165, 3196, 0, array( 630, 1204, 1770, 2100)), + array(169, 3362, 0, array( 660, 1260, 1860, 2220)), + array(173, 3532, 0, array( 720, 1316, 1950, 2310)), + array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40 + ); + + //---------------------------------------------------------------------- + public static function getDataLength($version, $level) + { + return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getECCLength($version, $level) + { + return self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getWidth($version) + { + return self::$capacity[$version][QRCAP_WIDTH]; + } + + //---------------------------------------------------------------------- + public static function getRemainder($version) + { + return self::$capacity[$version][QRCAP_REMINDER]; + } + + //---------------------------------------------------------------------- + public static function getMinimumVersion($size, $level) + { + + for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) { + $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; + if($words >= $size) + return $i; + } + + return -1; + } + + //###################################################################### + + public static $lengthTableBits = array( + array(10, 12, 14), + array( 9, 11, 13), + array( 8, 16, 16), + array( 8, 10, 12) + ); + + //---------------------------------------------------------------------- + public static function lengthIndicator($mode, $version) + { + if ($mode == QR_MODE_STRUCTURE) + return 0; + + if ($version <= 9) { + $l = 0; + } else if ($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + return self::$lengthTableBits[$mode][$l]; + } + + //---------------------------------------------------------------------- + public static function maximumWords($mode, $version) + { + if($mode == QR_MODE_STRUCTURE) + return 3; + + if($version <= 9) { + $l = 0; + } else if($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + $bits = self::$lengthTableBits[$mode][$l]; + $words = (1 << $bits) - 1; + + if($mode == QR_MODE_KANJI) { + $words *= 2; // the number of bytes is required + } + + return $words; + } + + // Error correction code ----------------------------------------------- + // Table of the error correction code (Reed-Solomon block) + // See Table 12-16 (pp.30-36), JIS X0510:2004. + + public static $eccTable = array( + array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)), + array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1 + array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), + array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)), + array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)), + array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5 + array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)), + array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)), + array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)), + array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)), + array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10 + array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)), + array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)), + array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)), + array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)), + array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15 + array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)), + array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)), + array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)), + array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)), + array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20 + array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)), + array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)), + array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)), + array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)), + array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25 + array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), + array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)), + array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), + array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)), + array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 + array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)), + array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), + array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), + array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), + array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 + array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), + array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), + array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), + array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), + array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40 + ); + + //---------------------------------------------------------------------- + // CACHEABLE!!! + + public static function getEccSpec($version, $level, array &$spec) + { + if (count($spec) < 5) { + $spec = array(0,0,0,0,0); + } + + $b1 = self::$eccTable[$version][$level][0]; + $b2 = self::$eccTable[$version][$level][1]; + $data = self::getDataLength($version, $level); + $ecc = self::getECCLength($version, $level); + + if($b2 == 0) { + $spec[0] = $b1; + $spec[1] = (int)($data / $b1); + $spec[2] = (int)($ecc / $b1); + $spec[3] = 0; + $spec[4] = 0; + } else { + $spec[0] = $b1; + $spec[1] = (int)($data / ($b1 + $b2)); + $spec[2] = (int)($ecc / ($b1 + $b2)); + $spec[3] = $b2; + $spec[4] = $spec[1] + 1; + } + } + + // Alignment pattern --------------------------------------------------- + + // Positions of alignment patterns. + // This array includes only the second and the third position of the + // alignment patterns. Rest of them can be calculated from the distance + // between them. + + // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. + + public static $alignmentPattern = array( + array( 0, 0), + array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 + array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 + array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 + array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 + array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 + array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 + array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 + array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 + ); + + + /** -------------------------------------------------------------------- + * Put an alignment marker. + * @param frame + * @param width + * @param ox,oy center coordinate of the pattern + */ + public static function putAlignmentMarker(array &$frame, $ox, $oy) + { + $finder = array( + "\xa1\xa1\xa1\xa1\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa0\xa1\xa0\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa1\xa1\xa1\xa1" + ); + + $yStart = $oy-2; + $xStart = $ox-2; + + for($y=0; $y<5; $y++) { + QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function putAlignmentPattern($version, &$frame, $width) + { + if($version < 2) + return; + + $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; + if($d < 0) { + $w = 2; + } else { + $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2); + } + + if($w * $w - 3 == 1) { + $x = self::$alignmentPattern[$version][0]; + $y = self::$alignmentPattern[$version][0]; + self::putAlignmentMarker($frame, $x, $y); + return; + } + + $cx = self::$alignmentPattern[$version][0]; + for($x=1; $x<$w - 1; $x++) { + self::putAlignmentMarker($frame, 6, $cx); + self::putAlignmentMarker($frame, $cx, 6); + $cx += $d; + } + + $cy = self::$alignmentPattern[$version][0]; + for($y=0; $y<$w-1; $y++) { + $cx = self::$alignmentPattern[$version][0]; + for($x=0; $x<$w-1; $x++) { + self::putAlignmentMarker($frame, $cx, $cy); + $cx += $d; + } + $cy += $d; + } + } + + // Version information pattern ----------------------------------------- + + // Version information pattern (BCH coded). + // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. + + // size: [QRSPEC_VERSION_MAX - 6] + + public static $versionPattern = array( + 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, + 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, + 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, + 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, + 0x27541, 0x28c69 + ); + + //---------------------------------------------------------------------- + public static function getVersionPattern($version) + { + if($version < 7 || $version > QRSPEC_VERSION_MAX) + return 0; + + return self::$versionPattern[$version -7]; + } + + // Format information -------------------------------------------------- + // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) + + public static $formatInfo = array( + array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), + array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), + array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), + array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) + ); + + public static function getFormatInfo($mask, $level) + { + if($mask < 0 || $mask > 7) + return 0; + + if($level < 0 || $level > 3) + return 0; + + return self::$formatInfo[$level][$mask]; + } + + // Frame --------------------------------------------------------------- + // Cache of initial frames. + + public static $frames = array(); + + /** -------------------------------------------------------------------- + * Put a finder pattern. + * @param frame + * @param width + * @param ox,oy upper-left coordinate of the pattern + */ + public static function putFinderPattern(&$frame, $ox, $oy) + { + $finder = array( + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" + ); + + for($y=0; $y<7; $y++) { + QRstr::set($frame, $ox, $oy+$y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function createFrame($version) + { + $width = self::$capacity[$version][QRCAP_WIDTH]; + $frameLine = str_repeat ("\0", $width); + $frame = array_fill(0, $width, $frameLine); + + // Finder pattern + self::putFinderPattern($frame, 0, 0); + self::putFinderPattern($frame, $width - 7, 0); + self::putFinderPattern($frame, 0, $width - 7); + + // Separator + $yOffset = $width - 7; + + for($y=0; $y<7; $y++) { + $frame[$y][7] = "\xc0"; + $frame[$y][$width - 8] = "\xc0"; + $frame[$yOffset][7] = "\xc0"; + $yOffset++; + } + + $setPattern = str_repeat("\xc0", 8); + + QRstr::set($frame, 0, 7, $setPattern); + QRstr::set($frame, $width-8, 7, $setPattern); + QRstr::set($frame, 0, $width - 8, $setPattern); + + // Format info + $setPattern = str_repeat("\x84", 9); + QRstr::set($frame, 0, 8, $setPattern); + QRstr::set($frame, $width - 8, 8, $setPattern, 8); + + $yOffset = $width - 8; + + for($y=0; $y<8; $y++,$yOffset++) { + $frame[$y][8] = "\x84"; + $frame[$yOffset][8] = "\x84"; + } + + // Timing pattern + + for($i=1; $i<$width-15; $i++) { + $frame[6][7+$i] = chr(0x90 | ($i & 1)); + $frame[7+$i][6] = chr(0x90 | ($i & 1)); + } + + // Alignment pattern + self::putAlignmentPattern($version, $frame, $width); + + // Version information + if($version >= 7) { + $vinf = self::getVersionPattern($version); + + $v = $vinf; + + for($x=0; $x<6; $x++) { + for($y=0; $y<3; $y++) { + $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1)); + $v = $v >> 1; + } + } + + $v = $vinf; + for($y=0; $y<6; $y++) { + for($x=0; $x<3; $x++) { + $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1)); + $v = $v >> 1; + } + } + } + + // and a little bit... + $frame[$width - 8][8] = "\x81"; + + return $frame; + } + + //---------------------------------------------------------------------- + public static function debug($frame, $binary_mode = false) + { + if ($binary_mode) { + + foreach ($frame as &$frameLine) { + $frameLine = join('  ', explode('0', $frameLine)); + $frameLine = join('██', explode('1', $frameLine)); + } + + ?> + +


        '; + echo join("
        ", $frame); + echo '






'; + + } else { + + foreach ($frame as &$frameLine) { + $frameLine = join(' ', explode("\xc0", $frameLine)); + $frameLine = join('', explode("\xc1", $frameLine)); + $frameLine = join(' ', explode("\xa0", $frameLine)); + $frameLine = join('', explode("\xa1", $frameLine)); + $frameLine = join('', explode("\x84", $frameLine)); //format 0 + $frameLine = join('', explode("\x85", $frameLine)); //format 1 + $frameLine = join('', explode("\x81", $frameLine)); //special bit + $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 + $frameLine = join('', explode("\x91", $frameLine)); //clock 1 + $frameLine = join(' ', explode("\x88", $frameLine)); //version + $frameLine = join('', explode("\x89", $frameLine)); //version + $frameLine = join('♦', explode("\x01", $frameLine)); + $frameLine = join('⋅', explode("\0", $frameLine)); + } + + ?> + + "; + echo join("
", $frame); + echo "
"; + + } + } + + //---------------------------------------------------------------------- + public static function serial($frame) + { + return gzcompress(join("\n", $frame), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + return explode("\n", gzuncompress($code)); + } + + //---------------------------------------------------------------------- + public static function newFrame($version) + { + if($version < 1 || $version > QRSPEC_VERSION_MAX) + return null; + + if(!isset(self::$frames[$version])) { + + $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + self::$frames[$version] = self::unserial(file_get_contents($fileName)); + } else { + self::$frames[$version] = self::createFrame($version); + file_put_contents($fileName, self::serial(self::$frames[$version])); + } + } else { + self::$frames[$version] = self::createFrame($version); + } + } + + if(is_null(self::$frames[$version])) + return null; + + return self::$frames[$version]; + } + + //---------------------------------------------------------------------- + public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; } + public static function rsBlockNum1($spec) { return $spec[0]; } + public static function rsDataCodes1($spec) { return $spec[1]; } + public static function rsEccCodes1($spec) { return $spec[2]; } + public static function rsBlockNum2($spec) { return $spec[3]; } + public static function rsDataCodes2($spec) { return $spec[4]; } + public static function rsEccCodes2($spec) { return $spec[2]; } + public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); } + public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; } + + } + + + +//---- qrimage.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Image output of code using GD2 + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('QR_IMAGE', true); + + class QRimage { + + //---------------------------------------------------------------------- + public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/png"); + ImagePng($image); + } else { + if($saveandprint===TRUE){ + ImagePng($image, $filename); + header("Content-type: image/png"); + ImagePng($image); + }else{ + ImagePng($image, $filename); + } + } + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/jpeg"); + ImageJpeg($image, null, $q); + } else { + ImageJpeg($image, $filename, $q); + } + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) + { + $h = count($frame); + $w = strlen($frame[0]); + + $imgW = $w + 2*$outerFrame; + $imgH = $h + 2*$outerFrame; + + $base_image =ImageCreate($imgW, $imgH); + + $col[0] = ImageColorAllocate($base_image,255,255,255); + $col[1] = ImageColorAllocate($base_image,0,0,0); + + imagefill($base_image, 0, 0, $col[0]); + + for($y=0; $y<$h; $y++) { + for($x=0; $x<$w; $x++) { + if ($frame[$y][$x] == '1') { + ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]); + } + } + } + + $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); + ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); + ImageDestroy($base_image); + + return $target_image; + } + } + + + +//---- qrinput.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Input encoding class + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('STRUCTURE_HEADER_BITS', 20); + define('MAX_STRUCTURED_SYMBOLS', 16); + + class QRinputItem { + + public $mode; + public $size; + public $data; + public $bstream; + + public function __construct($mode, $size, $data, $bstream = null) + { + $setData = array_slice($data, 0, $size); + + if (count($setData) < $size) { + $setData = array_merge($setData, array_fill(0,$size-count($setData),0)); + } + + if(!QRinput::check($mode, $size, $setData)) { + throw new \Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData)); + return null; + } + + $this->mode = $mode; + $this->size = $size; + $this->data = $setData; + $this->bstream = $bstream; + } + + //---------------------------------------------------------------------- + public function encodeModeNum($version) + { + try { + + $words = (int)($this->size / 3); + $bs = new QRbitstream(); + + $val = 0x1; + $bs->appendNum(4, $val); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); + + for($i=0; $i<$words; $i++) { + $val = (ord($this->data[$i*3 ]) - ord('0')) * 100; + $val += (ord($this->data[$i*3+1]) - ord('0')) * 10; + $val += (ord($this->data[$i*3+2]) - ord('0')); + $bs->appendNum(10, $val); + } + + if($this->size - $words * 3 == 1) { + $val = ord($this->data[$words*3]) - ord('0'); + $bs->appendNum(4, $val); + } else if($this->size - $words * 3 == 2) { + $val = (ord($this->data[$words*3 ]) - ord('0')) * 10; + $val += (ord($this->data[$words*3+1]) - ord('0')); + $bs->appendNum(7, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeAn($version) + { + try { + $words = (int)($this->size / 2); + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x02); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); + + for($i=0; $i<$words; $i++) { + $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45; + $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1])); + + $bs->appendNum(11, $val); + } + + if($this->size & 1) { + $val = QRinput::lookAnTable(ord($this->data[$words * 2])); + $bs->appendNum(6, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeMode8($version) + { + try { + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x4); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); + + for($i=0; $i<$this->size; $i++) { + $bs->appendNum(8, ord($this->data[$i])); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeKanji($version) + { + try { + + $bs = new QRbitrtream(); + + $bs->appendNum(4, 0x8); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2)); + + for($i=0; $i<$this->size; $i+=2) { + $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]); + if($val <= 0x9ffc) { + $val -= 0x8140; + } else { + $val -= 0xc140; + } + + $h = ($val >> 8) * 0xc0; + $val = ($val & 0xff) + $h; + + $bs->appendNum(13, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeStructure() + { + try { + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x03); + $bs->appendNum(4, ord($this->data[1]) - 1); + $bs->appendNum(4, ord($this->data[0]) - 1); + $bs->appendNum(8, ord($this->data[2])); + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function estimateBitStreamSizeOfEntry($version) + { + $bits = 0; + + if($version == 0) + $version = 1; + + switch($this->mode) { + case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break; + case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break; + case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break; + case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break; + case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; + default: + return 0; + } + + $l = QRspec::lengthIndicator($this->mode, $version); + $m = 1 << $l; + $num = (int)(($this->size + $m - 1) / $m); + + $bits += $num * (4 + $l); + + return $bits; + } + + //---------------------------------------------------------------------- + public function encodeBitStream($version) + { + try { + + unset($this->bstream); + $words = QRspec::maximumWords($this->mode, $version); + + if($this->size > $words) { + + $st1 = new QRinputItem($this->mode, $words, $this->data); + $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); + + $st1->encodeBitStream($version); + $st2->encodeBitStream($version); + + $this->bstream = new QRbitstream(); + $this->bstream->append($st1->bstream); + $this->bstream->append($st2->bstream); + + unset($st1); + unset($st2); + + } else { + + $ret = 0; + + switch($this->mode) { + case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break; + case QR_MODE_AN: $ret = $this->encodeModeAn($version); break; + case QR_MODE_8: $ret = $this->encodeMode8($version); break; + case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break; + case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break; + + default: + break; + } + + if($ret < 0) + return -1; + } + + return $this->bstream->size(); + + } catch (Exception $e) { + return -1; + } + } + }; + + //########################################################################## + + class QRinput { + + public $items; + + private $version; + private $level; + + //---------------------------------------------------------------------- + public function __construct($version = 0, $level = QR_ECLEVEL_L) + { + if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { + throw new \Exception('Invalid version no'); + return NULL; + } + + $this->version = $version; + $this->level = $level; + } + + //---------------------------------------------------------------------- + public function getVersion() + { + return $this->version; + } + + //---------------------------------------------------------------------- + public function setVersion($version) + { + if($version < 0 || $version > QRSPEC_VERSION_MAX) { + throw new \Exception('Invalid version no'); + return -1; + } + + $this->version = $version; + + return 0; + } + + //---------------------------------------------------------------------- + public function getErrorCorrectionLevel() + { + return $this->level; + } + + //---------------------------------------------------------------------- + public function setErrorCorrectionLevel($level) + { + if($level > QR_ECLEVEL_H) { + throw new \Exception('Invalid ECLEVEL'); + return -1; + } + + $this->level = $level; + + return 0; + } + + //---------------------------------------------------------------------- + public function appendEntry(QRinputItem $entry) + { + $this->items[] = $entry; + } + + //---------------------------------------------------------------------- + public function append($mode, $size, $data) + { + try { + $entry = new QRinputItem($mode, $size, $data); + $this->items[] = $entry; + return 0; + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + + public function insertStructuredAppendHeader($size, $index, $parity) + { + if( $size > MAX_STRUCTURED_SYMBOLS ) { + throw new \Exception('insertStructuredAppendHeader wrong size'); + } + + if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) { + throw new \Exception('insertStructuredAppendHeader wrong index'); + } + + $buf = array($size, $index, $parity); + + try { + $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); + array_unshift($this->items, $entry); + return 0; + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function calcParity() + { + $parity = 0; + + foreach($this->items as $item) { + if($item->mode != QR_MODE_STRUCTURE) { + for($i=$item->size-1; $i>=0; $i--) { + $parity ^= $item->data[$i]; + } + } + } + + return $parity; + } + + //---------------------------------------------------------------------- + public static function checkModeNum($size, $data) + { + for($i=0; $i<$size; $i++) { + if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){ + return false; + } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeNum($size) + { + $w = (int)$size / 3; + $bits = $w * 10; + + switch($size - $w * 3) { + case 1: + $bits += 4; + break; + case 2: + $bits += 7; + break; + default: + break; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static $anTable = array( + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + ); + + //---------------------------------------------------------------------- + public static function lookAnTable($c) + { + return (($c > 127)?-1:self::$anTable[$c]); + } + + //---------------------------------------------------------------------- + public static function checkModeAn($size, $data) + { + for($i=0; $i<$size; $i++) { + if (self::lookAnTable(ord($data[$i])) == -1) { + return false; + } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeAn($size) + { + $w = (int)($size / 2); + $bits = $w * 11; + + if($size & 1) { + $bits += 6; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static function estimateBitsMode8($size) + { + return $size * 8; + } + + //---------------------------------------------------------------------- + public function estimateBitsModeKanji($size) + { + return (int)(($size / 2) * 13); + } + + //---------------------------------------------------------------------- + public static function checkModeKanji($size, $data) + { + if($size & 1) + return false; + + for($i=0; $i<$size; $i+=2) { + $val = (ord($data[$i]) << 8) | ord($data[$i+1]); + if( $val < 0x8140 + || ($val > 0x9ffc && $val < 0xe040) + || $val > 0xebbf) { + return false; + } + } + + return true; + } + + /*********************************************************************** + * Validation + **********************************************************************/ + + public static function check($mode, $size, $data) + { + if($size <= 0) + return false; + + switch($mode) { + case QR_MODE_NUM: return self::checkModeNum($size, $data); break; + case QR_MODE_AN: return self::checkModeAn($size, $data); break; + case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break; + case QR_MODE_8: return true; break; + case QR_MODE_STRUCTURE: return true; break; + + default: + break; + } + + return false; + } + + + //---------------------------------------------------------------------- + public function estimateBitStreamSize($version) + { + $bits = 0; + + foreach($this->items as $item) { + $bits += $item->estimateBitStreamSizeOfEntry($version); + } + + return $bits; + } + + //---------------------------------------------------------------------- + public function estimateVersion() + { + $version = 0; + $prev = 0; + do { + $prev = $version; + $bits = $this->estimateBitStreamSize($prev); + $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + if ($version < 0) { + return -1; + } + } while ($version > $prev); + + return $version; + } + + //---------------------------------------------------------------------- + public static function lengthOfCode($mode, $version, $bits) + { + $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); + switch($mode) { + case QR_MODE_NUM: + $chunks = (int)($payload / 10); + $remain = $payload - $chunks * 10; + $size = $chunks * 3; + if($remain >= 7) { + $size += 2; + } else if($remain >= 4) { + $size += 1; + } + break; + case QR_MODE_AN: + $chunks = (int)($payload / 11); + $remain = $payload - $chunks * 11; + $size = $chunks * 2; + if($remain >= 6) + $size++; + break; + case QR_MODE_8: + $size = (int)($payload / 8); + break; + case QR_MODE_KANJI: + $size = (int)(($payload / 13) * 2); + break; + case QR_MODE_STRUCTURE: + $size = (int)($payload / 8); + break; + default: + $size = 0; + break; + } + + $maxsize = QRspec::maximumWords($mode, $version); + if($size < 0) $size = 0; + if($size > $maxsize) $size = $maxsize; + + return $size; + } + + //---------------------------------------------------------------------- + public function createBitStream() + { + $total = 0; + + foreach($this->items as $item) { + $bits = $item->encodeBitStream($this->version); + + if($bits < 0) + return -1; + + $total += $bits; + } + + return $total; + } + + //---------------------------------------------------------------------- + public function convertData() + { + $ver = $this->estimateVersion(); + if($ver > $this->getVersion()) { + $this->setVersion($ver); + } + + for(;;) { + $bits = $this->createBitStream(); + + if($bits < 0) + return -1; + + $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + if($ver < 0) { + throw new \Exception('WRONG VERSION'); + return -1; + } else if($ver > $this->getVersion()) { + $this->setVersion($ver); + } else { + break; + } + } + + return 0; + } + + //---------------------------------------------------------------------- + public function appendPaddingBit(&$bstream) + { + $bits = $bstream->size(); + $maxwords = QRspec::getDataLength($this->version, $this->level); + $maxbits = $maxwords * 8; + + if ($maxbits == $bits) { + return 0; + } + + if ($maxbits - $bits < 5) { + return $bstream->appendNum($maxbits - $bits, 0); + } + + $bits += 4; + $words = (int)(($bits + 7) / 8); + + $padding = new QRbitstream(); + $ret = $padding->appendNum($words * 8 - $bits + 4, 0); + + if($ret < 0) + return $ret; + + $padlen = $maxwords - $words; + + if($padlen > 0) { + + $padbuf = array(); + for($i=0; $i<$padlen; $i++) { + $padbuf[$i] = ($i&1)?0x11:0xec; + } + + $ret = $padding->appendBytes($padlen, $padbuf); + + if($ret < 0) + return $ret; + + } + + $ret = $bstream->append($padding); + + return $ret; + } + + //---------------------------------------------------------------------- + public function mergeBitStream() + { + if($this->convertData() < 0) { + return null; + } + + $bstream = new QRbitstream(); + + foreach($this->items as $item) { + $ret = $bstream->append($item->bstream); + if($ret < 0) { + return null; + } + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getBitStream() + { + + $bstream = $this->mergeBitStream(); + + if($bstream == null) { + return null; + } + + $ret = $this->appendPaddingBit($bstream); + if($ret < 0) { + return null; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getByteStream() + { + $bstream = $this->getBitStream(); + if($bstream == null) { + return null; + } + + return $bstream->toByte(); + } + } + + + + + + +//---- qrbitstream.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Bitstream class + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRbitstream { + + public $data = array(); + + //---------------------------------------------------------------------- + public function size() + { + return count($this->data); + } + + //---------------------------------------------------------------------- + public function allocate($setLength) + { + $this->data = array_fill(0, $setLength, 0); + return 0; + } + + //---------------------------------------------------------------------- + public static function newFromNum($bits, $num) + { + $bstream = new QRbitstream(); + $bstream->allocate($bits); + + $mask = 1 << ($bits - 1); + for($i=0; $i<$bits; $i++) { + if($num & $mask) { + $bstream->data[$i] = 1; + } else { + $bstream->data[$i] = 0; + } + $mask = $mask >> 1; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public static function newFromBytes($size, $data) + { + $bstream = new QRbitstream(); + $bstream->allocate($size * 8); + $p=0; + + for($i=0; $i<$size; $i++) { + $mask = 0x80; + for($j=0; $j<8; $j++) { + if($data[$i] & $mask) { + $bstream->data[$p] = 1; + } else { + $bstream->data[$p] = 0; + } + $p++; + $mask = $mask >> 1; + } + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function append(QRbitstream $arg) + { + if (is_null($arg)) { + return -1; + } + + if($arg->size() == 0) { + return 0; + } + + if($this->size() == 0) { + $this->data = $arg->data; + return 0; + } + + $this->data = array_values(array_merge($this->data, $arg->data)); + + return 0; + } + + //---------------------------------------------------------------------- + public function appendNum($bits, $num) + { + if ($bits == 0) + return 0; + + $b = QRbitstream::newFromNum($bits, $num); + + if(is_null($b)) + return -1; + + $ret = $this->append($b); + unset($b); + + return $ret; + } + + //---------------------------------------------------------------------- + public function appendBytes($size, $data) + { + if ($size == 0) + return 0; + + $b = QRbitstream::newFromBytes($size, $data); + + if(is_null($b)) + return -1; + + $ret = $this->append($b); + unset($b); + + return $ret; + } + + //---------------------------------------------------------------------- + public function toByte() + { + + $size = $this->size(); + + if($size == 0) { + return array(); + } + + $data = array_fill(0, (int)(($size + 7) / 8), 0); + $bytes = (int)($size / 8); + + $p = 0; + + for($i=0; $i<$bytes; $i++) { + $v = 0; + for($j=0; $j<8; $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$i] = $v; + } + + if($size & 7) { + $v = 0; + for($j=0; $j<($size & 7); $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$bytes] = $v; + } + + return $data; + } + + } + + + + +//---- qrsplit.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Input splitting classes + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * The following data / specifications are taken from + * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) + * or + * "Automatic identification and data capture techniques -- + * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + class QRsplit { + + public $dataStr = ''; + public $input; + public $modeHint; + + //---------------------------------------------------------------------- + public function __construct($dataStr, $input, $modeHint) + { + $this->dataStr = $dataStr; + $this->input = $input; + $this->modeHint = $modeHint; + } + + //---------------------------------------------------------------------- + public static function isdigitat($str, $pos) + { + if ($pos >= strlen($str)) + return false; + + return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9'))); + } + + //---------------------------------------------------------------------- + public static function isalnumat($str, $pos) + { + if ($pos >= strlen($str)) + return false; + + return (QRinput::lookAnTable(ord($str[$pos])) >= 0); + } + + //---------------------------------------------------------------------- + public function identifyMode($pos) + { + if ($pos >= strlen($this->dataStr)) + return QR_MODE_NUL; + + $c = $this->dataStr[$pos]; + + if(self::isdigitat($this->dataStr, $pos)) { + return QR_MODE_NUM; + } else if(self::isalnumat($this->dataStr, $pos)) { + return QR_MODE_AN; + } else if($this->modeHint == QR_MODE_KANJI) { + + if ($pos+1 < strlen($this->dataStr)) + { + $d = $this->dataStr[$pos+1]; + $word = (ord($c) << 8) | ord($d); + if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { + return QR_MODE_KANJI; + } + } + } + + return QR_MODE_8; + } + + //---------------------------------------------------------------------- + public function eatNum() + { + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + while(self::isdigitat($this->dataStr, $p)) { + $p++; + } + + $run = $p; + $mode = $this->identifyMode($p); + + if($mode == QR_MODE_8) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if($dif > 0) { + return $this->eat8(); + } + } + if($mode == QR_MODE_AN) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsModeAn(1) // + 4 + la + - QRinput::estimateBitsModeAn($run + 1);// - 4 - la + if($dif > 0) { + return $this->eatAn(); + } + } + + $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eatAn() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + + while(self::isalnumat($this->dataStr, $p)) { + if(self::isdigitat($this->dataStr, $p)) { + $q = $p; + while(self::isdigitat($this->dataStr, $q)) { + $q++; + } + + $dif = QRinput::estimateBitsModeAn($p) // + 4 + la + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsModeAn($q); // - 4 - la + + if($dif < 0) { + break; + } else { + $p = $q; + } + } else { + $p++; + } + } + + $run = $p; + + if(!self::isalnumat($this->dataStr, $p)) { + $dif = QRinput::estimateBitsModeAn($run) + 4 + $la + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if($dif > 0) { + return $this->eat8(); + } + } + + $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eatKanji() + { + $p = 0; + + while($this->identifyMode($p) == QR_MODE_KANJI) { + $p += 2; + } + + $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eat8() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 1; + $dataStrLen = strlen($this->dataStr); + + while($p < $dataStrLen) { + + $mode = $this->identifyMode($p); + if($mode == QR_MODE_KANJI) { + break; + } + if($mode == QR_MODE_NUM) { + $q = $p; + while(self::isdigitat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if($dif < 0) { + break; + } else { + $p = $q; + } + } else if($mode == QR_MODE_AN) { + $q = $p; + while(self::isalnumat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeAn($q - $p) + 4 + $la + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if($dif < 0) { + break; + } else { + $p = $q; + } + } else { + $p++; + } + } + + $run = $p; + $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); + + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function splitString() + { + while (strlen($this->dataStr) > 0) + { + if($this->dataStr == '') + return 0; + + $mode = $this->identifyMode(0); + + switch ($mode) { + case QR_MODE_NUM: $length = $this->eatNum(); break; + case QR_MODE_AN: $length = $this->eatAn(); break; + case QR_MODE_KANJI: + if ($hint == QR_MODE_KANJI) + $length = $this->eatKanji(); + else $length = $this->eat8(); + break; + default: $length = $this->eat8(); break; + + } + + if($length == 0) return 0; + if($length < 0) return -1; + + $this->dataStr = substr($this->dataStr, $length); + } + } + + //---------------------------------------------------------------------- + public function toUpper() + { + $stringLen = strlen($this->dataStr); + $p = 0; + + while ($p<$stringLen) { + $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); + if($mode == QR_MODE_KANJI) { + $p += 2; + } else { + if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { + $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); + } + $p++; + } + } + + return $this->dataStr; + } + + //---------------------------------------------------------------------- + public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) + { + if(is_null($string) || $string == '\0' || $string == '') { + throw new \Exception('empty string!!!'); + } + + $split = new QRsplit($string, $input, $modeHint); + + if(!$casesensitive) + $split->toUpper(); + + return $split->splitString(); + } + } + + + +//---- qrrscode.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Reed-Solomon error correction support + * + * Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q + * (libfec is released under the GNU Lesser General Public License.) + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRrsItem { + + public $mm; // Bits per symbol + public $nn; // Symbols per block (= (1<= $this->nn) { + $x -= $this->nn; + $x = ($x >> $this->mm) + ($x & $this->nn); + } + + return $x; + } + + //---------------------------------------------------------------------- + public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + // Common code for intializing a Reed-Solomon control block (char or int symbols) + // Copyright 2004 Phil Karn, KA9Q + // May be used under the terms of the GNU Lesser General Public License (LGPL) + + $rs = null; + + // Check parameter ranges + if($symsize < 0 || $symsize > 8) return $rs; + if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs; + if($prim <= 0 || $prim >= (1<<$symsize)) return $rs; + if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values! + if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding + + $rs = new QRrsItem(); + $rs->mm = $symsize; + $rs->nn = (1<<$symsize)-1; + $rs->pad = $pad; + + $rs->alpha_to = array_fill(0, $rs->nn+1, 0); + $rs->index_of = array_fill(0, $rs->nn+1, 0); + + // PHP style macro replacement ;) + $NN =& $rs->nn; + $A0 =& $NN; + + // Generate Galois field lookup tables + $rs->index_of[0] = $A0; // log(zero) = -inf + $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 + $sr = 1; + + for($i=0; $i<$rs->nn; $i++) { + $rs->index_of[$sr] = $i; + $rs->alpha_to[$i] = $sr; + $sr <<= 1; + if($sr & (1<<$symsize)) { + $sr ^= $gfpoly; + } + $sr &= $rs->nn; + } + + if($sr != 1){ + // field generator polynomial is not primitive! + $rs = NULL; + return $rs; + } + + /* Form RS code generator polynomial from its roots */ + $rs->genpoly = array_fill(0, $nroots+1, 0); + + $rs->fcr = $fcr; + $rs->prim = $prim; + $rs->nroots = $nroots; + $rs->gfpoly = $gfpoly; + + /* Find prim-th root of 1, used in decoding */ + for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn) + ; // intentional empty-body loop! + + $rs->iprim = (int)($iprim / $prim); + $rs->genpoly[0] = 1; + + for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) { + $rs->genpoly[$i+1] = 1; + + // Multiply rs->genpoly[] by @**(root + x) + for ($j = $i; $j > 0; $j--) { + if ($rs->genpoly[$j] != 0) { + $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; + } else { + $rs->genpoly[$j] = $rs->genpoly[$j-1]; + } + } + // rs->genpoly[0] can never be zero + $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; + } + + // convert rs->genpoly[] to index form for quicker encoding + for ($i = 0; $i <= $nroots; $i++) + $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; + + return $rs; + } + + //---------------------------------------------------------------------- + public function encode_rs_char($data, &$parity) + { + $MM =& $this->mm; + $NN =& $this->nn; + $ALPHA_TO =& $this->alpha_to; + $INDEX_OF =& $this->index_of; + $GENPOLY =& $this->genpoly; + $NROOTS =& $this->nroots; + $FCR =& $this->fcr; + $PRIM =& $this->prim; + $IPRIM =& $this->iprim; + $PAD =& $this->pad; + $A0 =& $NN; + + $parity = array_fill(0, $NROOTS, 0); + + for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) { + + $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; + if($feedback != $A0) { + // feedback term is non-zero + + // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must + // always be for the polynomials constructed by init_rs() + $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); + + for($j=1;$j<$NROOTS;$j++) { + $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])]; + } + } + + // Shift + array_shift($parity); + if($feedback != $A0) { + array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); + } else { + array_push($parity, 0); + } + } + } + } + + //########################################################################## + + class QRrs { + + public static $items = array(); + + //---------------------------------------------------------------------- + public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + foreach(self::$items as $rs) { + if($rs->pad != $pad) continue; + if($rs->nroots != $nroots) continue; + if($rs->mm != $symsize) continue; + if($rs->gfpoly != $gfpoly) continue; + if($rs->fcr != $fcr) continue; + if($rs->prim != $prim) continue; + + return $rs; + } + + $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad); + array_unshift(self::$items, $rs); + + return $rs; + } + } + + + +//---- qrmask.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Masking + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('N1', 3); + define('N2', 3); + define('N3', 40); + define('N4', 10); + + class QRmask { + + public $runLength = array(); + + //---------------------------------------------------------------------- + public function __construct() + { + $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); + } + + //---------------------------------------------------------------------- + public function writeFormatInformation($width, &$frame, $mask, $level) + { + $blacks = 0; + $format = QRspec::getFormatInfo($mask, $level); + + for($i=0; $i<8; $i++) { + if($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; + } + + $frame[8][$width - 1 - $i] = chr($v); + if($i < 6) { + $frame[$i][8] = chr($v); + } else { + $frame[$i + 1][8] = chr($v); + } + $format = $format >> 1; + } + + for($i=0; $i<7; $i++) { + if($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; + } + + $frame[$width - 7 + $i][8] = chr($v); + if($i == 0) { + $frame[8][7] = chr($v); + } else { + $frame[8][6 - $i] = chr($v); + } + + $format = $format >> 1; + } + + return $blacks; + } + + //---------------------------------------------------------------------- + public function mask0($x, $y) { return ($x+$y)&1; } + public function mask1($x, $y) { return ($y&1); } + public function mask2($x, $y) { return ($x%3); } + public function mask3($x, $y) { return ($x+$y)%3; } + public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; } + public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; } + public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; } + public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; } + + //---------------------------------------------------------------------- + private function generateMaskNo($maskNo, $width, $frame) + { + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + + for($y=0; $y<$width; $y++) { + for($x=0; $x<$width; $x++) { + if(ord($frame[$y][$x]) & 0x80) { + $bitMask[$y][$x] = 0; + } else { + $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y); + $bitMask[$y][$x] = ($maskFunc == 0)?1:0; + } + + } + } + + return $bitMask; + } + + //---------------------------------------------------------------------- + public static function serial($bitFrame) + { + $codeArr = array(); + + foreach ($bitFrame as $line) + $codeArr[] = join('', $line); + + return gzcompress(join("\n", $codeArr), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + $codeArr = array(); + + $codeLines = explode("\n", gzuncompress($code)); + foreach ($codeLines as $line) + $codeArr[] = str_split($line); + + return $codeArr; + } + + //---------------------------------------------------------------------- + public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) + { + $b = 0; + $bitMask = array(); + + $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + $bitMask = self::unserial(file_get_contents($fileName)); + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) + mkdir(QR_CACHE_DIR.'mask_'.$maskNo); + file_put_contents($fileName, self::serial($bitMask)); + } + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + } + + if ($maskGenOnly) + return; + + $d = $s; + + for($y=0; $y<$width; $y++) { + for($x=0; $x<$width; $x++) { + if($bitMask[$y][$x] == 1) { + $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]); + } + $b += (int)(ord($d[$y][$x]) & 1); + } + } + + return $b; + } + + //---------------------------------------------------------------------- + public function makeMask($width, $frame, $maskNo, $level) + { + $masked = array_fill(0, $width, str_repeat("\0", $width)); + $this->makeMaskNo($maskNo, $width, $frame, $masked); + $this->writeFormatInformation($width, $masked, $maskNo, $level); + + return $masked; + } + + //---------------------------------------------------------------------- + public function calcN1N3($length) + { + $demerit = 0; + + for($i=0; $i<$length; $i++) { + + if($this->runLength[$i] >= 5) { + $demerit += (N1 + ($this->runLength[$i] - 5)); + } + if($i & 1) { + if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) { + $fact = (int)($this->runLength[$i] / 3); + if(($this->runLength[$i-2] == $fact) && + ($this->runLength[$i-1] == $fact) && + ($this->runLength[$i+1] == $fact) && + ($this->runLength[$i+2] == $fact)) { + if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) { + $demerit += N3; + } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) { + $demerit += N3; + } + } + } + } + } + return $demerit; + } + + //---------------------------------------------------------------------- + public function evaluateSymbol($width, $frame) + { + $head = 0; + $demerit = 0; + + for($y=0; $y<$width; $y++) { + $head = 0; + $this->runLength[0] = 1; + + $frameY = $frame[$y]; + + if ($y>0) + $frameYM = $frame[$y-1]; + + for($x=0; $x<$width; $x++) { + if(($x > 0) && ($y > 0)) { + $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]); + $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]); + + if(($b22 | ($w22 ^ 1))&1) { + $demerit += N2; + } + } + if(($x == 0) && (ord($frameY[$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if($x > 0) { + if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) { + $head++; + $this->runLength[$head] = 1; + } else { + $this->runLength[$head]++; + } + } + } + + $demerit += $this->calcN1N3($head+1); + } + + for($x=0; $x<$width; $x++) { + $head = 0; + $this->runLength[0] = 1; + + for($y=0; $y<$width; $y++) { + if($y == 0 && (ord($frame[$y][$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if($y > 0) { + if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) { + $head++; + $this->runLength[$head] = 1; + } else { + $this->runLength[$head]++; + } + } + } + + $demerit += $this->calcN1N3($head+1); + } + + return $demerit; + } + + + //---------------------------------------------------------------------- + public function mask($width, $frame, $level) + { + $minDemerit = PHP_INT_MAX; + $bestMaskNum = 0; + $bestMask = array(); + + $checked_masks = array(0,1,2,3,4,5,6,7); + + if (QR_FIND_FROM_RANDOM !== false) { + + $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9); + for ($i = 0; $i < $howManuOut; $i++) { + $remPos = rand (0, count($checked_masks)-1); + unset($checked_masks[$remPos]); + $checked_masks = array_values($checked_masks); + } + + } + + $bestMask = $frame; + + foreach($checked_masks as $i) { + $mask = array_fill(0, $width, str_repeat("\0", $width)); + + $demerit = 0; + $blacks = 0; + $blacks = $this->makeMaskNo($i, $width, $frame, $mask); + $blacks += $this->writeFormatInformation($width, $mask, $i, $level); + $blacks = (int)(100 * $blacks / ($width * $width)); + $demerit = (int)((int)(abs($blacks - 50) / 5) * N4); + $demerit += $this->evaluateSymbol($width, $mask); + + if($demerit < $minDemerit) { + $minDemerit = $demerit; + $bestMask = $mask; + $bestMaskNum = $i; + } + } + + return $bestMask; + } + + //---------------------------------------------------------------------- + } + + + + +//---- qrencode.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Main encoder classes. + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRrsblock { + public $dataLength; + public $data = array(); + public $eccLength; + public $ecc = array(); + + public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) + { + $rs->encode_rs_char($data, $ecc); + + $this->dataLength = $dl; + $this->data = $data; + $this->eccLength = $el; + $this->ecc = $ecc; + } + }; + + //########################################################################## + + class QRrawcode { + public $version; + public $datacode = array(); + public $ecccode = array(); + public $blocks; + public $rsblocks = array(); //of RSblock + public $count; + public $dataLength; + public $eccLength; + public $b1; + + //---------------------------------------------------------------------- + public function __construct(QRinput $input) + { + $spec = array(0,0,0,0,0); + + $this->datacode = $input->getByteStream(); + if(is_null($this->datacode)) { + throw new \Exception('null imput string'); + } + + QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec); + + $this->version = $input->getVersion(); + $this->b1 = QRspec::rsBlockNum1($spec); + $this->dataLength = QRspec::rsDataLength($spec); + $this->eccLength = QRspec::rsEccLength($spec); + $this->ecccode = array_fill(0, $this->eccLength, 0); + $this->blocks = QRspec::rsBlockNum($spec); + + $ret = $this->init($spec); + if($ret < 0) { + throw new \Exception('block alloc error'); + return null; + } + + $this->count = 0; + } + + //---------------------------------------------------------------------- + public function init(array $spec) + { + $dl = QRspec::rsDataCodes1($spec); + $el = QRspec::rsEccCodes1($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + + $blockNo = 0; + $dataPos = 0; + $eccPos = 0; + for($i=0; $iecccode,$eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + if(QRspec::rsBlockNum2($spec) == 0) + return 0; + + $dl = QRspec::rsDataCodes2($spec); + $el = QRspec::rsEccCodes2($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + if($rs == NULL) return -1; + + for($i=0; $iecccode,$eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + return 0; + } + + //---------------------------------------------------------------------- + public function getCode() + { + $ret; + + if($this->count < $this->dataLength) { + $row = $this->count % $this->blocks; + $col = $this->count / $this->blocks; + if($col >= $this->rsblocks[0]->dataLength) { + $row += $this->b1; + } + $ret = $this->rsblocks[$row]->data[$col]; + } else if($this->count < $this->dataLength + $this->eccLength) { + $row = ($this->count - $this->dataLength) % $this->blocks; + $col = ($this->count - $this->dataLength) / $this->blocks; + $ret = $this->rsblocks[$row]->ecc[$col]; + } else { + return 0; + } + $this->count++; + + return $ret; + } + } + + //########################################################################## + + class QRcode { + + public $version; + public $width; + public $data; + + //---------------------------------------------------------------------- + public function encodeMask(QRinput $input, $mask) + { + if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { + throw new \Exception('wrong version'); + } + if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { + throw new \Exception('wrong level'); + } + + $raw = new QRrawcode($input); + + QRtools::markTime('after_raw'); + + $version = $raw->version; + $width = QRspec::getWidth($version); + $frame = QRspec::newFrame($version); + + $filler = new FrameFiller($width, $frame); + if(is_null($filler)) { + return NULL; + } + + // inteleaved data and ecc codes + for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) { + $code = $raw->getCode(); + $bit = 0x80; + for($j=0; $j<8; $j++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); + $bit = $bit >> 1; + } + } + + QRtools::markTime('after_filler'); + + unset($raw); + + // remainder bits + $j = QRspec::getRemainder($version); + for($i=0; $i<$j; $i++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02); + } + + $frame = $filler->frame; + unset($filler); + + + // masking + $maskObj = new QRmask(); + if($mask < 0) { + + if (QR_FIND_BEST_MASK) { + $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); + } else { + $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel()); + } + } else { + $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); + } + + if($masked == NULL) { + return NULL; + } + + QRtools::markTime('after_mask'); + + $this->version = $version; + $this->width = $width; + $this->data = $masked; + + return $this; + } + + //---------------------------------------------------------------------- + public function encodeInput(QRinput $input) + { + return $this->encodeMask($input, -1); + } + + //---------------------------------------------------------------------- + public function encodeString8bit($string, $version, $level) + { + if(string == NULL) { + throw new \Exception('empty string!'); + return NULL; + } + + $input = new QRinput($version, $level); + if($input == NULL) return NULL; + + $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); + if($ret < 0) { + unset($input); + return NULL; + } + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public function encodeString($string, $version, $level, $hint, $casesensitive) + { + + if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { + throw new \Exception('bad hint'); + return NULL; + } + + $input = new QRinput($version, $level); + if($input == NULL) return NULL; + + $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); + if($ret < 0) { + return NULL; + } + + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodePNG($text, $outfile, $saveandprint=false); + } + + //---------------------------------------------------------------------- + public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encode($text, $outfile); + } + + //---------------------------------------------------------------------- + public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodeRAW($text, $outfile); + } + } + + //########################################################################## + + class FrameFiller { + + public $width; + public $frame; + public $x; + public $y; + public $dir; + public $bit; + + //---------------------------------------------------------------------- + public function __construct($width, &$frame) + { + $this->width = $width; + $this->frame = $frame; + $this->x = $width - 1; + $this->y = $width - 1; + $this->dir = -1; + $this->bit = -1; + } + + //---------------------------------------------------------------------- + public function setFrameAt($at, $val) + { + $this->frame[$at['y']][$at['x']] = chr($val); + } + + //---------------------------------------------------------------------- + public function getFrameAt($at) + { + return ord($this->frame[$at['y']][$at['x']]); + } + + //---------------------------------------------------------------------- + public function next() + { + do { + + if($this->bit == -1) { + $this->bit = 0; + return array('x'=>$this->x, 'y'=>$this->y); + } + + $x = $this->x; + $y = $this->y; + $w = $this->width; + + if($this->bit == 0) { + $x--; + $this->bit++; + } else { + $x++; + $y += $this->dir; + $this->bit--; + } + + if($this->dir < 0) { + if($y < 0) { + $y = 0; + $x -= 2; + $this->dir = 1; + if($x == 6) { + $x--; + $y = 9; + } + } + } else { + if($y == $w) { + $y = $w - 1; + $x -= 2; + $this->dir = -1; + if($x == 6) { + $x--; + $y -= 8; + } + } + } + if($x < 0 || $y < 0) return null; + + $this->x = $x; + $this->y = $y; + + } while(ord($this->frame[$y][$x]) & 0x80); + + return array('x'=>$x, 'y'=>$y); + } + + } ; + + //########################################################################## + + class QRencode { + + public $casesensitive = true; + public $eightbit = false; + + public $version = 0; + public $size = 3; + public $margin = 4; + + public $structured = 0; // not supported yet + + public $level = QR_ECLEVEL_L; + public $hint = QR_MODE_8; + + //---------------------------------------------------------------------- + public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = new QRencode(); + $enc->size = $size; + $enc->margin = $margin; + + switch ($level.'') { + case '0': + case '1': + case '2': + case '3': + $enc->level = $level; + break; + case 'l': + case 'L': + $enc->level = QR_ECLEVEL_L; + break; + case 'm': + case 'M': + $enc->level = QR_ECLEVEL_M; + break; + case 'q': + case 'Q': + $enc->level = QR_ECLEVEL_Q; + break; + case 'h': + case 'H': + $enc->level = QR_ECLEVEL_H; + break; + } + + return $enc; + } + + //---------------------------------------------------------------------- + public function encodeRAW($intext, $outfile = false) + { + $code = new QRcode(); + + if($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + return $code->data; + } + + //---------------------------------------------------------------------- + public function encode($intext, $outfile = false) + { + $code = new QRcode(); + + if($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + QRtools::markTime('after_encode'); + + if ($outfile!== false) { + file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); + } else { + return QRtools::binarize($code->data); + } + } + + //---------------------------------------------------------------------- + public function encodePNG($intext, $outfile = false,$saveandprint=false) + { + try { + + ob_start(); + $tab = $this->encode($intext); + $err = ob_get_contents(); + ob_end_clean(); + + if ($err != '') + QRtools::log($outfile, $err); + + $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin)); + + QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint); + + } catch (Exception $e) { + + QRtools::log($outfile, $e->getMessage()); + + } + } + } + + diff --git a/niucloud/core/core/util/Queue.php b/niucloud/core/core/util/Queue.php new file mode 100644 index 00000000..912b4db1 --- /dev/null +++ b/niucloud/core/core/util/Queue.php @@ -0,0 +1,251 @@ +default_method = $this->method; + } + + /** + * 实例化当前队列 + * @return static + */ + public static function instance() + { + if (is_null(self::$instance)) { + self::$instance = new static(); + } + return self::$instance; + } + + /** + * 设置队列名称 + * @param string $queue_name + * @return $this + */ + public function setQueueName(string $queue_name) + { + $this->queue_name = $queue_name; + return $this; + } + + /** + * 加入队列 + * @param array|null $data + * @return bool + */ + public function push() + { + if (!$this->job) { + return $this->setError('JOB_NOT_EXISTS'); + } + $jodValue = $this->getValues(); + $res = $this->send(...$jodValue); + if (!$res) { + $res = $this->send(...$jodValue); + if (!$res) { + Log::error('队列推送失败,参数:' . json_encode($jodValue, JSON_THROW_ON_ERROR)); + } + } +// //todo 队列扩展策略调度, + + $this->clean(); + return $res; + } + + /** + * 向队列发送一条消息 + * @param $queue + * @param $data + * @param $delay + * @return mixed + */ + public function send($queue, $data, $delay = 0) + { + $pre_queue = md5(root_path()); //1.0.5版本之前为redis-queue + $queue_waiting = $pre_queue.'{redis-queue}-waiting'; //1.0.5版本之前为redis-queue-waiting + $queue_delay = $pre_queue.'{redis-queue}-delayed';//1.0.5版本之前为redis-queue-delayed + $now = time(); + if (extension_loaded('redis')) { + try { + $redis = new \Redis(); + $redis->connect(env('redis.redis_hostname'), env('redis.port'), 8); + if (env('redis.redis_password', '')) { + $redis->auth(env('redis.redis_password', '')); + } + $redis->select(env('redis.select')); + if(!$redis->ping()){ + $redis->connect(env('redis.redis_hostname'), env('redis.port'), 8); + if (env('redis.redis_password', '')) { + $redis->auth(env('redis.redis_password', '')); + } + $redis->select(env('redis.select')); + } + $package_str = json_encode([ + 'id' => rand(), + 'time' => $now, + 'delay' => $delay, + 'attempts' => 0, + 'queue' => $queue, + 'data' => $data + ]); + if ($delay) { + if(!$redis->zAdd($queue_delay, ($now + $delay), $package_str)){ + $redis->zAdd($queue_delay, ($now + $delay), $package_str); + } + return true; + } + if(!$redis->lPush($queue_waiting . $queue, $package_str)){ + $res = $redis->lPush($queue_waiting . $queue, $package_str); + Log::write($res); + } + return true; + } catch ( Throwable $e ) { + return false; + } + }else{ + return false; + } + + } + + /** + * 清除数据 + */ + public function clean() + { + $this->secs = 0; + $this->data = []; + $this->queue_name = null; + $this->method = $this->default_method; + } + + /** + * 获取参数 + * @param $data + * @return array + */ + protected function getValues() + { + + return [$this->job, ['method' => $this->method, 'data' => $this->data], $this->secs]; + } + + /** + * 不可访问时调用 + * @param $method + * @param $arguments + * @return $this + * @throws Exception + * @throws Exception + * @throws Exception + */ + public function __call($method, $arguments) + { + if (in_array($method, $this->allow_function)) { + if ($method === 'data') { + $this->{$method} = $arguments; + } else { + $this->{$method} = $arguments[0] ?? null; + } + return $this; + } else { + throw new Exception('Method does not exist' . __CLASS__ . '->' . $method . '()'); + } + } + + /** + * 设置错误信息 + * @param string|null $error + * @return bool + */ + protected function setError(?string $error = null) + { + $this->error = $error; + return false; + } + + /** + * 获取错误信息 + * @return string + */ + public function getError() + { + $error = $this->error; + $this->error = null; + return $error; + } +} diff --git a/niucloud/core/core/util/Snowflake.php b/niucloud/core/core/util/Snowflake.php new file mode 100644 index 00000000..84f2322c --- /dev/null +++ b/niucloud/core/core/util/Snowflake.php @@ -0,0 +1,91 @@ + self::MAX_DATA_CENTER_ID || $data_center_id < 0) { +// throw new Exception('Data center ID can not be greater than ' . self::MAX_DATA_CENTER_ID . ' or less than 0'); +// } +// +// if ($machine_id > self::MAX_MACHINE_ID || $machine_id < 0) { +// throw new Exception('Machine ID can not be greater than ' . self::MAX_MACHINE_ID . ' or less than 0'); +// } + +// $this->data_center_id = $data_center_id; +// $this->machine_id = $machine_id; + $this->last_timestamp = 0; + $this->sequence = 0; + } + + /** + * @throws Exception + */ + public function generateId() + { + $timestamp = $this->getTimestamp(); + + // 当前时间小于上一次生成时间,发生时钟回拨 + if ($timestamp < $this->last_timestamp) { + throw new Exception('Clock moved backwards.'); + } + + // 当前时间与上一次生成时间相同 + if ($timestamp == $this->last_timestamp) { + $this->sequence = ($this->sequence + 1) & self::MAX_SEQUENCE; + + // 当前毫秒的序列已经达到最大值,等待下一毫秒 + if ($this->sequence == 0) { + $timestamp = $this->nextMillis($this->last_timestamp); + } + } else { + // 新的一毫秒,序列从0开始 + $this->sequence = 0; + } + + $this->last_timestamp = $timestamp; + + return (($timestamp - self::START_EPOCH) << (self::SEQUENCE_BITS)) +// | ($this->data_center_id << (self::SEQUENCE_BITS + self::MACHINE_ID_BITS)) +// | ($this->machine_id << self::SEQUENCE_BITS) + | $this->sequence; + } + + private function getTimestamp() + { + return floor(microtime(true) * 1000); + } + + private function nextMillis($last_timestamp) + { + $timestamp = $this->getTimestamp(); + + while ($timestamp <= $last_timestamp) { + $timestamp = $this->getTimestamp(); + } + + return $timestamp; + } +} \ No newline at end of file diff --git a/niucloud/core/core/util/Terminal.php b/niucloud/core/core/util/Terminal.php new file mode 100644 index 00000000..964097e8 --- /dev/null +++ b/niucloud/core/core/util/Terminal.php @@ -0,0 +1,56 @@ + array("pipe", "r"), // 标准输入,我们不需要 + 1 => array("pipe", "w"), // 标准输出,我们需要将其捕获 + 2 => array("pipe", "w") // 标准错误,我们也需要将其捕获 + ); + $process = proc_open($command, $descriptorspec, $pipes, $cwd); + + // 检查进程是否成功创建 + if (!is_resource($process)) { + return "Could not execute command: $command"; + } + + // 从管道中获取命令的输出 + $output = ''; + while (!feof($pipes[1])) { + $output .= fgets($pipes[1]); + } + while (!feof($pipes[2])) { + $output .= fgets($pipes[2]); + } + + // 关闭管道和进程 + fclose($pipes[0]); + fclose($pipes[1]); + fclose($pipes[2]); + $status = proc_close($process); + + // 判断命令的执行结果 + if ($status === 0) { + return str_contains($output, 'Command failed') ? $output : true; + } else { + return $output; + } + } +} \ No newline at end of file diff --git a/niucloud/core/core/util/TokenAuth.php b/niucloud/core/core/util/TokenAuth.php new file mode 100644 index 00000000..35cd7310 --- /dev/null +++ b/niucloud/core/core/util/TokenAuth.php @@ -0,0 +1,109 @@ +request->host(); + $time = time(); + $params += [ + 'iss' => $host, + 'aud' => $host, + 'iat' => $time, + 'nbf' => $time, + 'exp' => $time + $expire_time, + ]; + + $params['jti'] = $id . "_" . $type; + $token = JWT::encode($params, Env::get('app.app_key', 'niucloud456$%^')); + $cache_token = Cache::get("token_" . $params['jti']); + $cache_token_arr = $cache_token ?: []; +// if(!empty($cache_token)) +// { +// +// $cache_token_arr[] = $token; +// } + $cache_token_arr[] = $token; + Cache::tag("token")->set("token_" . $params['jti'], $cache_token_arr); + return compact('token', 'params'); + } + + /** + * 解析token + * @param string $token + * @param string $type + * @return array + */ + public static function parseToken(string $token, string $type): array + { + $payload = JWT::decode($token, Env::get('app.app_key', 'niucloud456$%^'), ['HS256']); + if (!empty($payload)) { + $token_info = json_decode(json_encode($payload), true, 512, JSON_THROW_ON_ERROR); + + if (explode("_", $token_info['jti'])[1] != $type) { + return []; + } + if (!empty($token_info) && !in_array($token, Cache::get('token_' . $token_info['jti'], []))) { + return []; + } + return $token_info; + } else { + return []; + } + } + + /** + * 清理token + * @param int $id + * @param string $type + * @param string|null $token + * @return Response + */ + public static function clearToken(int $id, string $type, ?string $token = '') + { + if (!empty($token)) { + $token_cache = Cache::get("token_" . $id . "_" . $type, []); + //todo 也可以通过修改过期时间来实现 + if (!empty($token_cache)) { + if (($key = array_search($token, $token_cache)) !== false) { + array_splice($token_cache, $key, 1); + } + Cache::set("token_" . $id . "_" . $type, $token_cache); + } + } else { + Cache::set("token_" . $id . "_" . $type, []); + } + return success(); + } +} diff --git a/niucloud/core/core/util/barcode/class/BCGArgumentException.php b/niucloud/core/core/util/barcode/class/BCGArgumentException.php new file mode 100644 index 00000000..030f3e46 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGArgumentException.php @@ -0,0 +1,25 @@ +param = $param; + parent::__construct($message, 20000); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGBarcode.php b/niucloud/core/core/util/barcode/class/BCGBarcode.php new file mode 100644 index 00000000..317e773b --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGBarcode.php @@ -0,0 +1,436 @@ +setOffsetX(0); + $this->setOffsetY(0); + $this->setForegroundColor(0x000000); + $this->setBackgroundColor(0xffffff); + $this->setScale(1); + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + } + + /** + * Gets the foreground color of the barcode. + * + * @return BCGColor + */ + public function getForegroundColor() { + return $this->colorFg; + } + + /** + * Sets the foreground color of the barcode. It could be a BCGColor + * value or simply a language code (white, black, yellow...) or hex value. + * + * @param mixed $code + */ + public function setForegroundColor($code) { + if ($code instanceof BCGColor) { + $this->colorFg = $code; + } else { + $this->colorFg = new BCGColor($code); + } + } + + /** + * Gets the background color of the barcode. + * + * @return BCGColor + */ + public function getBackgroundColor() { + return $this->colorBg; + } + + /** + * Sets the background color of the barcode. It could be a BCGColor + * value or simply a language code (white, black, yellow...) or hex value. + * + * @param mixed $code + */ + public function setBackgroundColor($code) { + if ($code instanceof BCGColor) { + $this->colorBg = $code; + } else { + $this->colorBg = new BCGColor($code); + } + + foreach ($this->labels as $label) { + $label->setBackgroundColor($this->colorBg); + } + } + + /** + * Sets the color. + * + * @param mixed $fg + * @param mixed $bg + */ + public function setColor($fg, $bg) { + $this->setForegroundColor($fg); + $this->setBackgroundColor($bg); + } + + /** + * Gets the scale of the barcode. + * + * @return int + */ + public function getScale() { + return $this->scale; + } + + /** + * Sets the scale of the barcode in pixel. + * If the scale is lower than 1, an exception is raised. + * + * @param int $scale + */ + public function setScale($scale) { + $scale = intval($scale); + if ($scale <= 0) { + throw new BCGArgumentException('The scale must be larger than 0.', 'scale'); + } + + $this->scale = $scale; + } + + /** + * Abstract method that draws the barcode on the resource. + * + * @param resource $im + */ + public abstract function draw($im); + + /** + * Returns the maximal size of a barcode. + * [0]->width + * [1]->height + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $labels = $this->getBiggestLabels(false); + $pixelsAround = array(0, 0, 0, 0); // TRBL + if (isset($labels[BCGLabel::POSITION_TOP])) { + $dimension = $labels[BCGLabel::POSITION_TOP]->getDimension(); + $pixelsAround[0] += $dimension[1]; + } + + if (isset($labels[BCGLabel::POSITION_RIGHT])) { + $dimension = $labels[BCGLabel::POSITION_RIGHT]->getDimension(); + $pixelsAround[1] += $dimension[0]; + } + + if (isset($labels[BCGLabel::POSITION_BOTTOM])) { + $dimension = $labels[BCGLabel::POSITION_BOTTOM]->getDimension(); + $pixelsAround[2] += $dimension[1]; + } + + if (isset($labels[BCGLabel::POSITION_LEFT])) { + $dimension = $labels[BCGLabel::POSITION_LEFT]->getDimension(); + $pixelsAround[3] += $dimension[0]; + } + + $finalW = ($w + $this->offsetX) * $this->scale; + $finalH = ($h + $this->offsetY) * $this->scale; + + // This section will check if a top/bottom label is too big for its width and left/right too big for its height + $reversedLabels = $this->getBiggestLabels(true); + foreach ($reversedLabels as $label) { + $dimension = $label->getDimension(); + $alignment = $label->getAlignment(); + if ($label->getPosition() === BCGLabel::POSITION_LEFT || $label->getPosition() === BCGLabel::POSITION_RIGHT) { + if ($alignment === BCGLabel::ALIGN_TOP) { + $pixelsAround[2] = max($pixelsAround[2], $dimension[1] - $finalH); + } elseif ($alignment === BCGLabel::ALIGN_CENTER) { + $temp = ceil(($dimension[1] - $finalH) / 2); + $pixelsAround[0] = max($pixelsAround[0], $temp); + $pixelsAround[2] = max($pixelsAround[2], $temp); + } elseif ($alignment === BCGLabel::ALIGN_BOTTOM) { + $pixelsAround[0] = max($pixelsAround[0], $dimension[1] - $finalH); + } + } else { + if ($alignment === BCGLabel::ALIGN_LEFT) { + $pixelsAround[1] = max($pixelsAround[1], $dimension[0] - $finalW); + } elseif ($alignment === BCGLabel::ALIGN_CENTER) { + $temp = ceil(($dimension[0] - $finalW) / 2); + $pixelsAround[1] = max($pixelsAround[1], $temp); + $pixelsAround[3] = max($pixelsAround[3], $temp); + } elseif ($alignment === BCGLabel::ALIGN_RIGHT) { + $pixelsAround[3] = max($pixelsAround[3], $dimension[0] - $finalW); + } + } + } + + $this->pushLabel[0] = $pixelsAround[3]; + $this->pushLabel[1] = $pixelsAround[0]; + + $finalW = ($w + $this->offsetX) * $this->scale + $pixelsAround[1] + $pixelsAround[3]; + $finalH = ($h + $this->offsetY) * $this->scale + $pixelsAround[0] + $pixelsAround[2]; + + return array($finalW, $finalH); + } + + /** + * Gets the X offset. + * + * @return int + */ + public function getOffsetX() { + return $this->offsetX; + } + + /** + * Sets the X offset. + * + * @param int $offsetX + */ + public function setOffsetX($offsetX) { + $offsetX = intval($offsetX); + if ($offsetX < 0) { + throw new BCGArgumentException('The offset X must be 0 or larger.', 'offsetX'); + } + + $this->offsetX = $offsetX; + } + + /** + * Gets the Y offset. + * + * @return int + */ + public function getOffsetY() { + return $this->offsetY; + } + + /** + * Sets the Y offset. + * + * @param int $offsetY + */ + public function setOffsetY($offsetY) { + $offsetY = intval($offsetY); + if ($offsetY < 0) { + throw new BCGArgumentException('The offset Y must be 0 or larger.', 'offsetY'); + } + + $this->offsetY = $offsetY; + } + + /** + * Adds the label to the drawing. + * + * @param BCGLabel $label + */ + public function addLabel(BCGLabel $label) { + $label->setBackgroundColor($this->colorBg); + $this->labels[] = $label; + } + + /** + * Removes the label from the drawing. + * + * @param BCGLabel $label + */ + public function removeLabel(BCGLabel $label) { + $remove = -1; + $c = count($this->labels); + for ($i = 0; $i < $c; $i++) { + if ($this->labels[$i] === $label) { + $remove = $i; + break; + } + } + + if ($remove > -1) { + array_splice($this->labels, $remove, 1); + } + } + + /** + * Clears the labels. + */ + public function clearLabels() { + $this->labels = array(); + } + + /** + * Draws the text. + * The coordinate passed are the positions of the barcode. + * $x1 and $y1 represent the top left corner. + * $x2 and $y2 represent the bottom right corner. + * + * @param resource $im + * @param int $x1 + * @param int $y1 + * @param int $x2 + * @param int $y2 + */ + protected function drawText($im, $x1, $y1, $x2, $y2) { + foreach ($this->labels as $label) { + $label->draw($im, + ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], + ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], + ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0], + ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1]); + } + } + + /** + * Draws 1 pixel on the resource at a specific position with a determined color. + * + * @param resource $im + * @param int $x + * @param int $y + * @param int $color + */ + protected function drawPixel($im, $x, $y, $color = self::COLOR_FG) { + $xR = ($x + $this->offsetX) * $this->scale + $this->pushLabel[0]; + $yR = ($y + $this->offsetY) * $this->scale + $this->pushLabel[1]; + + // We always draw a rectangle + imagefilledrectangle($im, + $xR, + $yR, + $xR + $this->scale - 1, + $yR + $this->scale - 1, + $this->getColor($im, $color)); + } + + /** + * Draws an empty rectangle on the resource at a specific position with a determined color. + * + * @param resource $im + * @param int $x1 + * @param int $y1 + * @param int $x2 + * @param int $y2 + * @param int $color + */ + protected function drawRectangle($im, $x1, $y1, $x2, $y2, $color = self::COLOR_FG) { + if ($this->scale === 1) { + imagefilledrectangle($im, + ($x1 + $this->offsetX) + $this->pushLabel[0], + ($y1 + $this->offsetY) + $this->pushLabel[1], + ($x2 + $this->offsetX) + $this->pushLabel[0], + ($y2 + $this->offsetY) + $this->pushLabel[1], + $this->getColor($im, $color)); + } else { + imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color)); + imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color)); + imagefilledrectangle($im, ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color)); + imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color)); + } + } + + /** + * Draws a filled rectangle on the resource at a specific position with a determined color. + * + * @param resource $im + * @param int $x1 + * @param int $y1 + * @param int $x2 + * @param int $y2 + * @param int $color + */ + protected function drawFilledRectangle($im, $x1, $y1, $x2, $y2, $color = self::COLOR_FG) { + if ($x1 > $x2) { // Swap + $x1 ^= $x2 ^= $x1 ^= $x2; + } + + if ($y1 > $y2) { // Swap + $y1 ^= $y2 ^= $y1 ^= $y2; + } + + imagefilledrectangle($im, + ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], + ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], + ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, + ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, + $this->getColor($im, $color)); + } + + /** + * Allocates the color based on the integer. + * + * @param resource $im + * @param int $color + * @return resource + */ + protected function getColor($im, $color) { + if ($color === self::COLOR_BG) { + return $this->colorBg->allocate($im); + } else { + return $this->colorFg->allocate($im); + } + } + + /** + * Returning the biggest label widths for LEFT/RIGHT and heights for TOP/BOTTOM. + * + * @param bool $reversed + * @return BCGLabel[] + */ + private function getBiggestLabels($reversed = false) { + $searchLR = $reversed ? 1 : 0; + $searchTB = $reversed ? 0 : 1; + + $labels = array(); + foreach ($this->labels as $label) { + $position = $label->getPosition(); + if (isset($labels[$position])) { + $savedDimension = $labels[$position]->getDimension(); + $dimension = $label->getDimension(); + if ($position === BCGLabel::POSITION_LEFT || $position === BCGLabel::POSITION_RIGHT) { + if ($dimension[$searchLR] > $savedDimension[$searchLR]) { + $labels[$position] = $label; + } + } else { + if ($dimension[$searchTB] > $savedDimension[$searchTB]) { + $labels[$position] = $label; + } + } + } else { + $labels[$position] = $label; + } + } + + return $labels; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGBarcode1D.php b/niucloud/core/core/util/barcode/class/BCGBarcode1D.php new file mode 100644 index 00000000..7202a8cb --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGBarcode1D.php @@ -0,0 +1,259 @@ +setThickness(30); + + $this->defaultLabel = new BCGLabel(); + $this->defaultLabel->setPosition(BCGLabel::POSITION_BOTTOM); + $this->setLabel(self::AUTO_LABEL); + $this->setFont(new BCGFontPhp(5)); + + $this->text = ''; + $this->checksumValue = false; + $this->positionX = 0; + } + + /** + * Gets the thickness. + * + * @return int + */ + public function getThickness() { + return $this->thickness; + } + + /** + * Sets the thickness. + * + * @param int $thickness + */ + public function setThickness($thickness) { + $thickness = intval($thickness); + if ($thickness <= 0) { + throw new BCGArgumentException('The thickness must be larger than 0.', 'thickness'); + } + + $this->thickness = $thickness; + } + + /** + * Gets the label. + * If the label was set to BCGBarcode1D::AUTO_LABEL, the label will display the value from the text parsed. + * + * @return string + */ + public function getLabel() { + $label = $this->label; + if ($this->label === self::AUTO_LABEL) { + $label = $this->text; + if ($this->displayChecksum === true && ($checksum = $this->processChecksum()) !== false) { + $label .= $checksum; + } + } + + return $label; + } + + /** + * Sets the label. + * You can use BCGBarcode::AUTO_LABEL to have the label automatically written based on the parsed text. + * + * @param string $label + */ + public function setLabel($label) { + $this->label = $label; + } + + /** + * Gets the font. + * + * @return BCGFont + */ + public function getFont() { + return $this->font; + } + + /** + * Sets the font. + * + * @param mixed $font BCGFont or int + */ + public function setFont($font) { + if (is_int($font)) { + if ($font === 0) { + $font = null; + } else { + $font = new BCGFontPhp($font); + } + } + + $this->font = $font; + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + $this->text = $text; + $this->checksumValue = false; // Reset checksumValue + $this->validate(); + + parent::parse($text); + + $this->addDefaultLabel(); + } + + /** + * Gets the checksum of a Barcode. + * If no checksum is available, return FALSE. + * + * @return string + */ + public function getChecksum() { + return $this->processChecksum(); + } + + /** + * Sets if the checksum is displayed with the label or not. + * The checksum must be activated in some case to make this variable effective. + * + * @param boolean $displayChecksum + */ + public function setDisplayChecksum($displayChecksum) { + $this->displayChecksum = (bool)$displayChecksum; + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + $label = $this->getLabel(); + $font = $this->font; + if ($label !== null && $label !== '' && $font !== null && $this->defaultLabel !== null) { + $this->defaultLabel->setText($label); + $this->defaultLabel->setFont($font); + $this->addLabel($this->defaultLabel); + } + } + + /** + * Validates the input + */ + protected function validate() { + // No validation in the abstract class. + } + + /** + * Returns the index in $keys (useful for checksum). + * + * @param mixed $var + * @return mixed + */ + protected function findIndex($var) { + return array_search($var, $this->keys); + } + + /** + * Returns the code of the char (useful for drawing bars). + * + * @param mixed $var + * @return string + */ + protected function findCode($var) { + return $this->code[$this->findIndex($var)]; + } + + /** + * Draws all chars thanks to $code. If $startBar is true, the line begins by a space. + * If $startBar is false, the line begins by a bar. + * + * @param resource $im + * @param string $code + * @param boolean $startBar + */ + protected function drawChar($im, $code, $startBar = true) { + $colors = array(BCGBarcode::COLOR_FG, BCGBarcode::COLOR_BG); + $currentColor = $startBar ? 0 : 1; + $c = strlen($code); + for ($i = 0; $i < $c; $i++) { + for ($j = 0; $j < intval($code[$i]) + 1; $j++) { + $this->drawSingleBar($im, $colors[$currentColor]); + $this->nextX(); + } + + $currentColor = ($currentColor + 1) % 2; + } + } + + /** + * Draws a Bar of $color depending of the resolution. + * + * @param resource $img + * @param int $color + */ + protected function drawSingleBar($im, $color) { + $this->drawFilledRectangle($im, $this->positionX, 0, $this->positionX, $this->thickness - 1, $color); + } + + /** + * Moving the pointer right to write a bar. + */ + protected function nextX() { + $this->positionX++; + } + + /** + * Method that saves FALSE into the checksumValue. This means no checksum + * but this method should be overriden when needed. + */ + protected function calculateChecksum() { + $this->checksumValue = false; + } + + /** + * Returns FALSE because there is no checksum. This method should be + * overriden to return correctly the checksum in string with checksumValue. + * + * @return string + */ + protected function processChecksum() { + return false; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGColor.php b/niucloud/core/core/util/barcode/class/BCGColor.php new file mode 100644 index 00000000..7bd0650d --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGColor.php @@ -0,0 +1,154 @@ +r = intval($args[0]); + $this->g = intval($args[1]); + $this->b = intval($args[2]); + } elseif ($c === 1) { + if (is_string($args[0]) && strlen($args[0]) === 7 && $args[0][0] === '#') { // Hex Value in String + $this->r = intval(substr($args[0], 1, 2), 16); + $this->g = intval(substr($args[0], 3, 2), 16); + $this->b = intval(substr($args[0], 5, 2), 16); + } else { + if (is_string($args[0])) { + $args[0] = self::getColor($args[0]); + } + + $args[0] = intval($args[0]); + $this->r = ($args[0] & 0xff0000) >> 16; + $this->g = ($args[0] & 0x00ff00) >> 8; + $this->b = ($args[0] & 0x0000ff); + } + } else { + $this->r = $this->g = $this->b = 0; + } + } + + /** + * Sets the color transparent. + * + * @param bool $transparent + */ + public function setTransparent($transparent) { + $this->transparent = $transparent; + } + + /** + * Returns Red Color. + * + * @return int + */ + public function r() { + return $this->r; + } + + /** + * Returns Green Color. + * + * @return int + */ + public function g() { + return $this->g; + } + + /** + * Returns Blue Color. + * + * @return int + */ + public function b() { + return $this->b; + } + + /** + * Returns the int value for PHP color. + * + * @param resource $im + * @return int + */ + public function allocate(&$im) { + $allocated = imagecolorallocate($im, $this->r, $this->g, $this->b); + if ($this->transparent) { + return imagecolortransparent($im, $allocated); + } else { + return $allocated; + } + } + + /** + * Returns class of BCGColor depending of the string color. + * + * If the color doens't exist, it takes the default one. + * + * @param string $code + * @param string $default + */ + public static function getColor($code, $default = 'white') { + switch(strtolower($code)) { + case '': + case 'white': + return 0xffffff; + case 'black': + return 0x000000; + case 'maroon': + return 0x800000; + case 'red': + return 0xff0000; + case 'orange': + return 0xffa500; + case 'yellow': + return 0xffff00; + case 'olive': + return 0x808000; + case 'purple': + return 0x800080; + case 'fuchsia': + return 0xff00ff; + case 'lime': + return 0x00ff00; + case 'green': + return 0x008000; + case 'navy': + return 0x000080; + case 'blue': + return 0x0000ff; + case 'aqua': + return 0x00ffff; + case 'teal': + return 0x008080; + case 'silver': + return 0xc0c0c0; + case 'gray': + return 0x808080; + default: + return self::getColor($default, 'white'); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGDrawException.php b/niucloud/core/core/util/barcode/class/BCGDrawException.php new file mode 100644 index 00000000..792732d3 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGDrawException.php @@ -0,0 +1,21 @@ + \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGDrawing.php b/niucloud/core/core/util/barcode/class/BCGDrawing.php new file mode 100644 index 00000000..612522cf --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGDrawing.php @@ -0,0 +1,248 @@ +im = null; + $this->setFilename($filename); + $this->color = $color; + $this->dpi = null; + $this->rotateDegree = 0.0; + } + + /** + * Destructor. + */ + public function __destruct() { + $this->destroy(); + } + + /** + * Gets the filename. + * + * @return string + */ + public function getFilename() { + return $this->filename; + } + + /** + * Sets the filename. + * + * @param string $filaneme + */ + public function setFilename($filename) { + $this->filename = $filename; + } + + /** + * @return resource. + */ + public function get_im() { + return $this->im; + } + + /** + * Sets the image. + * + * @param resource $im + */ + public function set_im($im) { + $this->im = $im; + } + + /** + * Gets Barcode for drawing. + * + * @return BCGBarcode + */ + public function getBarcode() { + return $this->barcode; + } + + /** + * Sets Barcode for drawing. + * + * @param BCGBarcode $Barcode + */ + public function setBarcode(BCGBarcode $barcode) { + $this->barcode = $barcode; + } + + /** + * Gets the DPI for supported filetype. + * + * @return float + */ + public function getDPI() { + return $this->dpi; + } + + /** + * Sets the DPI for supported filetype. + * + * @param float $dpi + */ + public function setDPI($dpi) { + $this->dpi = $dpi; + } + + /** + * Gets the rotation angle in degree clockwise. + * + * @return float + */ + public function getRotationAngle() { + return $this->rotateDegree; + } + + /** + * Sets the rotation angle in degree clockwise. + * + * @param float $degree + */ + public function setRotationAngle($degree) { + $this->rotateDegree = (float)$degree; + } + + /** + * Draws the Barcode on the image $im. + */ + public function draw() { + $size = $this->barcode->getDimension(0, 0); + $this->w = max(1, $size[0]); + $this->h = max(1, $size[1]); + $this->init(); + $this->barcode->draw($this->im); + } + + /** + * Saves $im into the file (many format available). + * + * @param int $image_style + * @param int $quality + */ + public function finish($image_style = self::IMG_FORMAT_PNG, $quality = 100) { + $drawer = null; + + $im = $this->im; + if ($this->rotateDegree > 0.0) { + if (function_exists('imagerotate')) { + $im = imagerotate($this->im, 360 - $this->rotateDegree, $this->color->allocate($this->im)); + } else { + throw new BCGDrawException('The method imagerotate doesn\'t exist on your server. Do not use any rotation.'); + } + } + + if ($image_style === self::IMG_FORMAT_PNG) { + $drawer = new BCGDrawPNG($im); + $drawer->setFilename($this->filename); + $drawer->setDPI($this->dpi); + } elseif ($image_style === self::IMG_FORMAT_JPEG) { + $drawer = new BCGDrawJPG($im); + $drawer->setFilename($this->filename); + $drawer->setDPI($this->dpi); + $drawer->setQuality($quality); + } elseif ($image_style === self::IMG_FORMAT_GIF) { + // Some PHP versions have a bug if passing 2nd argument as null. + if ($this->filename === null || $this->filename === '') { + imagegif($im); + } else { + imagegif($im, $this->filename); + } + } elseif ($image_style === self::IMG_FORMAT_WBMP) { + imagewbmp($im, $this->filename); + } + + if ($drawer !== null) { + $drawer->draw(); + } + } + + /** + * Writes the Error on the picture. + * + * @param Exception $exception + */ + public function drawException($exception) { + $this->w = 1; + $this->h = 1; + $this->init(); + + // Is the image big enough? + $w = imagesx($this->im); + $h = imagesy($this->im); + + $text = 'Error: ' . $exception->getMessage(); + + $width = imagefontwidth(2) * strlen($text); + $height = imagefontheight(2); + if ($width > $w || $height > $h) { + $width = max($w, $width); + $height = max($h, $height); + + // We change the size of the image + $newimg = imagecreatetruecolor($width, $height); + imagefill($newimg, 0, 0, imagecolorat($this->im, 0, 0)); + imagecopy($newimg, $this->im, 0, 0, 0, 0, $w, $h); + $this->im = $newimg; + } + + $black = new BCGColor('black'); + imagestring($this->im, 2, 0, 0, $text, $black->allocate($this->im)); + } + + /** + * Free the memory of PHP (called also by destructor). + */ + public function destroy() { + @imagedestroy($this->im); + } + + /** + * Init Image and color background. + */ + private function init() { + if ($this->im === null) { + $this->im = imagecreatetruecolor($this->w, $this->h) + or die('Can\'t Initialize the GD Libraty'); + imagefilledrectangle($this->im, 0, 0, $this->w - 1, $this->h - 1, $this->color->allocate($this->im)); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGFont.php b/niucloud/core/core/util/barcode/class/BCGFont.php new file mode 100644 index 00000000..c58c0de3 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGFont.php @@ -0,0 +1,23 @@ + \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGFontFile.php b/niucloud/core/core/util/barcode/class/BCGFontFile.php new file mode 100644 index 00000000..4c304eb5 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGFontFile.php @@ -0,0 +1,209 @@ +path = $fontPath; + $this->size = $size; + $this->foregroundColor = new BCGColor('black'); + $this->setRotationAngle(0); + $this->setBoxFix(self::PHP_BOX_FIX); + } + + /** + * Gets the text associated to the font. + * + * @return string + */ + public function getText() { + return $this->text; + } + + /** + * Sets the text associated to the font. + * + * @param string text + */ + public function setText($text) { + $this->text = $text; + $this->box = null; + } + + /** + * Gets the rotation in degree. + * + * @return int + */ + public function getRotationAngle() { + return (360 - $this->rotationAngle) % 360; + } + + /** + * Sets the rotation in degree. + * + * @param int + */ + public function setRotationAngle($rotationAngle) { + $this->rotationAngle = (int)$rotationAngle; + if ($this->rotationAngle !== 90 && $this->rotationAngle !== 180 && $this->rotationAngle !== 270) { + $this->rotationAngle = 0; + } + + $this->rotationAngle = (360 - $this->rotationAngle) % 360; + + $this->box = null; + } + + /** + * Gets the background color. + * + * @return BCGColor + */ + public function getBackgroundColor() { + } + + /** + * Sets the background color. + * + * @param BCGColor $backgroundColor + */ + public function setBackgroundColor($backgroundColor) { + } + + /** + * Gets the foreground color. + * + * @return BCGColor + */ + public function getForegroundColor() { + return $this->foregroundColor; + } + + /** + * Sets the foreground color. + * + * @param BCGColor $foregroundColor + */ + public function setForegroundColor($foregroundColor) { + $this->foregroundColor = $foregroundColor; + } + + /** + * Gets the box fix information. + * + * @return int + */ + public function getBoxFix() { + return $this->boxFix; + } + + /** + * Sets the box fix information. + * + * @param int $value + */ + public function setBoxFix($value) { + $this->boxFix = intval($value); + } + + /** + * Returns the width and height that the text takes to be written. + * + * @return int[] + */ + public function getDimension() { + $w = 0.0; + $h = 0.0; + $box = $this->getBox(); + + if ($box !== null) { + $minX = min(array($box[0], $box[2], $box[4], $box[6])); + $maxX = max(array($box[0], $box[2], $box[4], $box[6])); + $minY = min(array($box[1], $box[3], $box[5], $box[7])); + $maxY = max(array($box[1], $box[3], $box[5], $box[7])); + + $w = $maxX - $minX; + $h = $maxY - $minY; + } + + $rotationAngle = $this->getRotationAngle(); + if ($rotationAngle === 90 || $rotationAngle === 270) { + return array($h + self::PHP_BOX_FIX, $w); + } else { + return array($w + self::PHP_BOX_FIX, $h); + } + } + + /** + * Draws the text on the image at a specific position. + * $x and $y represent the left bottom corner. + * + * @param resource $im + * @param int $x + * @param int $y + */ + public function draw($im, $x, $y) { + $drawingPosition = $this->getDrawingPosition($x, $y); + imagettftext($im, $this->size, $this->rotationAngle, $drawingPosition[0], $drawingPosition[1], $this->foregroundColor->allocate($im), $this->path, $this->text); + } + + private function getDrawingPosition($x, $y) { + $dimension = $this->getDimension(); + $box = $this->getBox(); + $rotationAngle = $this->getRotationAngle(); + if ($rotationAngle === 0) { + $y += abs(min($box[5], $box[7])); + } elseif ($rotationAngle === 90) { + $x += abs(min($box[5], $box[7])); + $y += $dimension[1]; + } elseif ($rotationAngle === 180) { + $x += $dimension[0]; + $y += abs(max($box[1], $box[3])); + } elseif ($rotationAngle === 270) { + $x += abs(max($box[1], $box[3])); + } + + return array($x, $y); + } + + private function getBox() { + if ($this->box === null) { + $gd = imagecreate(1, 1); + $this->box = imagettftext($gd, $this->size, 0, 0, 0, 0, $this->path, $this->text); + } + + return $this->box; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGFontPhp.php b/niucloud/core/core/util/barcode/class/BCGFontPhp.php new file mode 100644 index 00000000..a2f8ba80 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGFontPhp.php @@ -0,0 +1,153 @@ +font = max(0, intval($font)); + $this->backgroundColor = new BCGColor('white'); + $this->foregroundColor = new BCGColor('black'); + $this->setRotationAngle(0); + } + + /** + * Gets the text associated to the font. + * + * @return string + */ + public function getText() { + return $this->text; + } + + /** + * Sets the text associated to the font. + * + * @param string text + */ + public function setText($text) { + $this->text = $text; + } + + /** + * Gets the rotation in degree. + * + * @return int + */ + public function getRotationAngle() { + return (360 - $this->rotationAngle) % 360; + } + + /** + * Sets the rotation in degree. + * + * @param int + */ + public function setRotationAngle($rotationAngle) { + $this->rotationAngle = (int)$rotationAngle; + if ($this->rotationAngle !== 90 && $this->rotationAngle !== 180 && $this->rotationAngle !== 270) { + $this->rotationAngle = 0; + } + + $this->rotationAngle = (360 - $this->rotationAngle) % 360; + } + + /** + * Gets the background color. + * + * @return BCGColor + */ + public function getBackgroundColor() { + return $this->backgroundColor; + } + + /** + * Sets the background color. + * + * @param BCGColor $backgroundColor + */ + public function setBackgroundColor($backgroundColor) { + $this->backgroundColor = $backgroundColor; + } + + /** + * Gets the foreground color. + * + * @return BCGColor + */ + public function getForegroundColor() { + return $this->foregroundColor; + } + + /** + * Sets the foreground color. + * + * @param BCGColor $foregroundColor + */ + public function setForegroundColor($foregroundColor) { + $this->foregroundColor = $foregroundColor; + } + + /** + * Returns the width and height that the text takes to be written. + * + * @return int[] + */ + public function getDimension() { + $w = imagefontwidth($this->font) * strlen($this->text); + $h = imagefontheight($this->font); + + $rotationAngle = $this->getRotationAngle(); + if ($rotationAngle === 90 || $rotationAngle === 270) { + return array($h, $w); + } else { + return array($w, $h); + } + } + + /** + * Draws the text on the image at a specific position. + * $x and $y represent the left bottom corner. + * + * @param resource $im + * @param int $x + * @param int $y + */ + public function draw($im, $x, $y) { + if ($this->getRotationAngle() !== 0) { + if (!function_exists('imagerotate')) { + throw new BCGDrawException('The method imagerotate doesn\'t exist on your server. Do not use any rotation.'); + } + + $w = imagefontwidth($this->font) * strlen($this->text); + $h = imagefontheight($this->font); + $gd = imagecreatetruecolor($w, $h); + imagefilledrectangle($gd, 0, 0, $w - 1, $h - 1, $this->backgroundColor->allocate($gd)); + imagestring($gd, $this->font, 0, 0, $this->text, $this->foregroundColor->allocate($gd)); + $gd = imagerotate($gd, $this->rotationAngle, 0); + imagecopy($im, $gd, $x, $y, 0, 0, imagesx($gd), imagesy($gd)); + } else { + imagestring($im, $this->font, $x, $y, $this->text, $this->foregroundColor->allocate($im)); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGLabel.php b/niucloud/core/core/util/barcode/class/BCGLabel.php new file mode 100644 index 00000000..7c933c74 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGLabel.php @@ -0,0 +1,320 @@ +setFont($font); + $this->setText($text); + $this->setPosition($position); + $this->setAlignment($alignment); + $this->setSpacing(4); + $this->setOffset(0); + $this->setRotationAngle(0); + $this->setBackgroundColor(new BCGColor('white')); + $this->setForegroundColor(new BCGColor('black')); + } + + /** + * Gets the text. + * + * @return string + */ + public function getText() { + return $this->font->getText(); + } + + /** + * Sets the text. + * + * @param string $text + */ + public function setText($text) { + $this->text = $text; + $this->font->setText($this->text); + } + + /** + * Gets the font. + * + * @return BCGFont + */ + public function getFont() { + return $this->font; + } + + /** + * Sets the font. + * + * @param BCGFont $font + */ + public function setFont($font) { + if ($font === null) { + throw new BCGArgumentException('Font cannot be null.', 'font'); + } + + $this->font = clone $font; + $this->font->setText($this->text); + $this->font->setRotationAngle($this->rotationAngle); + $this->font->setBackgroundColor($this->backgroundColor); + $this->font->setForegroundColor($this->foregroundColor); + } + + /** + * Gets the text position for drawing. + * + * @return int + */ + public function getPosition() { + return $this->position; + } + + /** + * Sets the text position for drawing. + * + * @param int $position + */ + public function setPosition($position) { + $position = intval($position); + if ($position !== self::POSITION_TOP && $position !== self::POSITION_RIGHT && $position !== self::POSITION_BOTTOM && $position !== self::POSITION_LEFT) { + throw new BCGArgumentException('The text position must be one of a valid constant.', 'position'); + } + + $this->position = $position; + } + + /** + * Gets the text alignment for drawing. + * + * @return int + */ + public function getAlignment() { + return $this->alignment; + } + + /** + * Sets the text alignment for drawing. + * + * @param int $alignment + */ + public function setAlignment($alignment) { + $alignment = intval($alignment); + if ($alignment !== self::ALIGN_LEFT && $alignment !== self::ALIGN_TOP && $alignment !== self::ALIGN_CENTER && $alignment !== self::ALIGN_RIGHT && $alignment !== self::ALIGN_BOTTOM) { + throw new BCGArgumentException('The text alignment must be one of a valid constant.', 'alignment'); + } + + $this->alignment = $alignment; + } + + /** + * Gets the offset. + * + * @return int + */ + public function getOffset() { + return $this->offset; + } + + /** + * Sets the offset. + * + * @param int $offset + */ + public function setOffset($offset) { + $this->offset = intval($offset); + } + + /** + * Gets the spacing. + * + * @return int + */ + public function getSpacing() { + return $this->spacing; + } + + /** + * Sets the spacing. + * + * @param int $spacing + */ + public function setSpacing($spacing) { + $this->spacing = max(0, intval($spacing)); + } + + /** + * Gets the rotation angle in degree. + * + * @return int + */ + public function getRotationAngle() { + return $this->font->getRotationAngle(); + } + + /** + * Sets the rotation angle in degree. + * + * @param int $rotationAngle + */ + public function setRotationAngle($rotationAngle) { + $this->rotationAngle = intval($rotationAngle); + $this->font->setRotationAngle($this->rotationAngle); + } + + /** + * Gets the background color in case of rotation. + * + * @return BCGColor + */ + public function getBackgroundColor() { + return $this->backgroundColor; + } + + /** + * Sets the background color in case of rotation. + * + * @param BCGColor $backgroundColor + */ + public /*internal*/ function setBackgroundColor($backgroundColor) { + $this->backgroundColor = $backgroundColor; + $this->font->setBackgroundColor($this->backgroundColor); + } + + /** + * Gets the foreground color. + * + * @return BCGColor + */ + public function getForegroundColor() { + return $this->font->getForegroundColor(); + } + + /** + * Sets the foreground color. + * + * @param BCGColor $foregroundColor + */ + public function setForegroundColor($foregroundColor) { + $this->foregroundColor = $foregroundColor; + $this->font->setForegroundColor($this->foregroundColor); + } + + /** + * Gets the dimension taken by the label, including the spacing and offset. + * [0]: width + * [1]: height + * + * @return int[] + */ + public function getDimension() { + $w = 0; + $h = 0; + + $dimension = $this->font->getDimension(); + $w = $dimension[0]; + $h = $dimension[1]; + + if ($this->position === self::POSITION_TOP || $this->position === self::POSITION_BOTTOM) { + $h += $this->spacing; + $w += max(0, $this->offset); + } else { + $w += $this->spacing; + $h += max(0, $this->offset); + } + + return array($w, $h); + } + + /** + * Draws the text. + * The coordinate passed are the positions of the barcode. + * $x1 and $y1 represent the top left corner. + * $x2 and $y2 represent the bottom right corner. + * + * @param resource $im + * @param int $x1 + * @param int $y1 + * @param int $x2 + * @param int $y2 + */ + public /*internal*/ function draw($im, $x1, $y1, $x2, $y2) { + $x = 0; + $y = 0; + + $fontDimension = $this->font->getDimension(); + + if ($this->position === self::POSITION_TOP || $this->position === self::POSITION_BOTTOM) { + if ($this->position === self::POSITION_TOP) { + $y = $y1 - $this->spacing - $fontDimension[1]; + } elseif ($this->position === self::POSITION_BOTTOM) { + $y = $y2 + $this->spacing; + } + + if ($this->alignment === self::ALIGN_CENTER) { + $x = ($x2 - $x1) / 2 + $x1 - $fontDimension[0] / 2 + $this->offset; + } elseif ($this->alignment === self::ALIGN_LEFT) { + $x = $x1 + $this->offset; + } else { + $x = $x2 + $this->offset - $fontDimension[0]; + } + } else { + if ($this->position === self::POSITION_LEFT) { + $x = $x1 - $this->spacing - $fontDimension[0]; + } elseif ($this->position === self::POSITION_RIGHT) { + $x = $x2 + $this->spacing; + } + + if ($this->alignment === self::ALIGN_CENTER) { + $y = ($y2 - $y1) / 2 + $y1 - $fontDimension[1] / 2 + $this->offset; + } elseif ($this->alignment === self::ALIGN_TOP) { + $y = $y1 + $this->offset; + } else { + $y = $y2 + $this->offset - $fontDimension[1]; + } + } + + $this->font->setText($this->text); + $this->font->draw($im, $x, $y); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGParseException.php b/niucloud/core/core/util/barcode/class/BCGParseException.php new file mode 100644 index 00000000..ce4eeb9f --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGParseException.php @@ -0,0 +1,25 @@ +barcode = $barcode; + parent::__construct($message, 10000); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGcodabar.barcode.php b/niucloud/core/core/util/barcode/class/BCGcodabar.barcode.php new file mode 100644 index 00000000..91189fed --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGcodabar.barcode.php @@ -0,0 +1,122 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D'); + $this->code = array( // 0 added to add an extra space + '00000110', /* 0 */ + '00001100', /* 1 */ + '00010010', /* 2 */ + '11000000', /* 3 */ + '00100100', /* 4 */ + '10000100', /* 5 */ + '01000010', /* 6 */ + '01001000', /* 7 */ + '01100000', /* 8 */ + '10010000', /* 9 */ + '00011000', /* - */ + '00110000', /* $ */ + '10001010', /* : */ + '10100010', /* / */ + '10101000', /* . */ + '00111110', /* + */ + '00110100', /* A */ + '01010010', /* B */ + '00010110', /* C */ + '00011100' /* D */ + ); + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + parent::parse(strtoupper($text)); // Only Capital Letters are Allowed + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i]), true); + } + + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textLength = 0; + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $index = $this->findIndex($this->text[$i]); + if ($index !== false) { + $textLength += 8; + $textLength += substr_count($this->code[$index], '1'); + } + } + + $w += $textLength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('codabar', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('codabar', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must start by A, B, C or D + if ($c == 0 || ($this->text[0] !== 'A' && $this->text[0] !== 'B' && $this->text[0] !== 'C' && $this->text[0] !== 'D')) { + throw new BCGParseException('codabar', 'The text must start by the character A, B, C, or D.'); + } + + // Must end by A, B, C or D + $c2 = $c - 1; + if ($c2 === 0 || ($this->text[$c2] !== 'A' && $this->text[$c2] !== 'B' && $this->text[$c2] !== 'C' && $this->text[$c2] !== 'D')) { + throw new BCGParseException('codabar', 'The text must end by the character A, B, C, or D.'); + } + + parent::validate(); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGcode11.barcode.php b/niucloud/core/core/util/barcode/class/BCGcode11.barcode.php new file mode 100644 index 00000000..7c11a22c --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGcode11.barcode.php @@ -0,0 +1,185 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-'); + $this->code = array( // 0 added to add an extra space + '000010', /* 0 */ + '100010', /* 1 */ + '010010', /* 2 */ + '110000', /* 3 */ + '001010', /* 4 */ + '101000', /* 5 */ + '011000', /* 6 */ + '000110', /* 7 */ + '100100', /* 8 */ + '100000', /* 9 */ + '001000' /* - */ + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting Code + $this->drawChar($im, '001100', true); + + // Chars + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i]), true); + } + + // Checksum + $this->calculateChecksum(); + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->code[$this->checksumValue[$i]], true); + } + + // Ending Code + $this->drawChar($im, '00110', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 8; + + $textlength = 0; + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $textlength += $this->getIndexLength($this->findIndex($this->text[$i])); + } + + $checksumlength = 0; + $this->calculateChecksum(); + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $checksumlength += $this->getIndexLength($this->checksumValue[$i]); + } + + $endlength = 7; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('code11', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('code11', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Checksum + // First CheckSUM "C" + // The "C" checksum character is the modulo 11 remainder of the sum of the weighted + // value of the data characters. The weighting value starts at "1" for the right-most + // data character, 2 for the second to last, 3 for the third-to-last, and so on up to 20. + // After 10, the sequence wraps around back to 1. + + // Second CheckSUM "K" + // Same as CheckSUM "C" but we count the CheckSum "C" at the end + // After 9, the sequence wraps around back to 1. + $sequence_multiplier = array(10, 9); + $temp_text = $this->text; + $this->checksumValue = array(); + for ($z = 0; $z < 2; $z++) { + $c = strlen($temp_text); + + // We don't display the K CheckSum if the original text had a length less than 10 + if ($c <= 10 && $z === 1) { + break; + } + + $checksum = 0; + for ($i = $c, $j = 0; $i > 0; $i--, $j++) { + $multiplier = $i % $sequence_multiplier[$z]; + if ($multiplier === 0) { + $multiplier = $sequence_multiplier[$z]; + } + + $checksum += $this->findIndex($temp_text[$j]) * $multiplier; + } + + $this->checksumValue[$z] = $checksum % 11; + $temp_text .= $this->keys[$this->checksumValue[$z]]; + } + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + $ret = ''; + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $ret .= $this->keys[$this->checksumValue[$i]]; + } + + return $ret; + } + + return false; + } + + private function getIndexLength($index) { + $length = 0; + if ($index !== false) { + $length += 6; + $length += substr_count($this->code[$index], '1'); + } + + return $length; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGcode128.barcode.php b/niucloud/core/core/util/barcode/class/BCGcode128.barcode.php new file mode 100644 index 00000000..0cfeed6f --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGcode128.barcode.php @@ -0,0 +1,885 @@ +keysA = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'; + for ($i = 0; $i < 32; $i++) { + $this->keysA .= chr($i); + } + + /* CODE 128 B */ + $this->keysB = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~' . chr(127); + + /* CODE 128 C */ + $this->keysC = '0123456789'; + + $this->code = array( + '101111', /* 00 */ + '111011', /* 01 */ + '111110', /* 02 */ + '010112', /* 03 */ + '010211', /* 04 */ + '020111', /* 05 */ + '011102', /* 06 */ + '011201', /* 07 */ + '021101', /* 08 */ + '110102', /* 09 */ + '110201', /* 10 */ + '120101', /* 11 */ + '001121', /* 12 */ + '011021', /* 13 */ + '011120', /* 14 */ + '002111', /* 15 */ + '012011', /* 16 */ + '012110', /* 17 */ + '112100', /* 18 */ + '110021', /* 19 */ + '110120', /* 20 */ + '102101', /* 21 */ + '112001', /* 22 */ + '201020', /* 23 */ + '200111', /* 24 */ + '210011', /* 25 */ + '210110', /* 26 */ + '201101', /* 27 */ + '211001', /* 28 */ + '211100', /* 29 */ + '101012', /* 30 */ + '101210', /* 31 */ + '121010', /* 32 */ + '000212', /* 33 */ + '020012', /* 34 */ + '020210', /* 35 */ + '001202', /* 36 */ + '021002', /* 37 */ + '021200', /* 38 */ + '100202', /* 39 */ + '120002', /* 40 */ + '120200', /* 41 */ + '001022', /* 42 */ + '001220', /* 43 */ + '021020', /* 44 */ + '002012', /* 45 */ + '002210', /* 46 */ + '022010', /* 47 */ + '202010', /* 48 */ + '100220', /* 49 */ + '120020', /* 50 */ + '102002', /* 51 */ + '102200', /* 52 */ + '102020', /* 53 */ + '200012', /* 54 */ + '200210', /* 55 */ + '220010', /* 56 */ + '201002', /* 57 */ + '201200', /* 58 */ + '221000', /* 59 */ + '203000', /* 60 */ + '110300', /* 61 */ + '320000', /* 62 */ + '000113', /* 63 */ + '000311', /* 64 */ + '010013', /* 65 */ + '010310', /* 66 */ + '030011', /* 67 */ + '030110', /* 68 */ + '001103', /* 69 */ + '001301', /* 70 */ + '011003', /* 71 */ + '011300', /* 72 */ + '031001', /* 73 */ + '031100', /* 74 */ + '130100', /* 75 */ + '110003', /* 76 */ + '302000', /* 77 */ + '130001', /* 78 */ + '023000', /* 79 */ + '000131', /* 80 */ + '010031', /* 81 */ + '010130', /* 82 */ + '003101', /* 83 */ + '013001', /* 84 */ + '013100', /* 85 */ + '300101', /* 86 */ + '310001', /* 87 */ + '310100', /* 88 */ + '101030', /* 89 */ + '103010', /* 90 */ + '301010', /* 91 */ + '000032', /* 92 */ + '000230', /* 93 */ + '020030', /* 94 */ + '003002', /* 95 */ + '003200', /* 96 */ + '300002', /* 97 */ + '300200', /* 98 */ + '002030', /* 99 */ + '003020', /* 100*/ + '200030', /* 101*/ + '300020', /* 102*/ + '100301', /* 103*/ + '100103', /* 104*/ + '100121', /* 105*/ + '122000' /*STOP*/ + ); + $this->setStart($start); + $this->setTilde(true); + + // Latches and Shifts + $this->latch = array( + array(null, self::KEYA_CODEB, self::KEYA_CODEC), + array(self::KEYB_CODEA, null, self::KEYB_CODEC), + array(self::KEYC_CODEA, self::KEYC_CODEB, null) + ); + $this->shift = array( + array(null, self::KEYA_SHIFT), + array(self::KEYB_SHIFT, null) + ); + $this->fnc = array( + array(self::KEYA_FNC1, self::KEYA_FNC2, self::KEYA_FNC3, self::KEYA_FNC4), + array(self::KEYB_FNC1, self::KEYB_FNC2, self::KEYB_FNC3, self::KEYB_FNC4), + array(self::KEYC_FNC1, null, null, null) + ); + + // Method available + $this->METHOD = array(CODE128_A => 'A', CODE128_B => 'B', CODE128_C => 'C'); + } + + /** + * Specifies the start code. Can be 'A', 'B', 'C', or null + * - Table A: Capitals + ASCII 0-31 + punct + * - Table B: Capitals + LowerCase + punct + * - Table C: Numbers + * + * If null is specified, the table selection is automatically made. + * The default is null. + * + * @param string $table + */ + public function setStart($table) { + if ($table !== 'A' && $table !== 'B' && $table !== 'C' && $table !== null) { + throw new BCGArgumentException('The starting table must be A, B, C or null.', 'table'); + } + + $this->starting_text = $table; + } + + /** + * Gets the tilde. + * + * @return bool + */ + public function getTilde() { + return $this->tilde; + } + + /** + * Accepts tilde to be process as a special character. + * If true, you can do this: + * - ~~ : to make ONE tilde + * - ~Fx : to insert FCNx. x is equal from 1 to 4. + * + * @param boolean $accept + */ + public function setTilde($accept) { + $this->tilde = (bool)$accept; + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + $this->setStartFromText($text); + + $this->text = ''; + $seq = ''; + + $currentMode = $this->starting_text; + + // Here, we format correctly what the user gives. + if (!is_array($text)) { + $seq = $this->getSequence($text, $currentMode); + $this->text = $text; + } else { + // This loop checks for UnknownText AND raises an exception if a character is not allowed in a table + reset($text); + while (list($key1, $val1) = each($text)) { // We take each value + if (!is_array($val1)) { // This is not a table + if (is_string($val1)) { // If it's a string, parse as unknown + $seq .= $this->getSequence($val1, $currentMode); + $this->text .= $val1; + } else { + // it's the case of "array(ENCODING, 'text')" + // We got ENCODING in $val1, calling 'each' again will get 'text' in $val2 + list($key2, $val2) = each($text); + $seq .= $this->{'setParse' . $this->METHOD[$val1]}($val2, $currentMode); + $this->text .= $val2; + } + } else { // The method is specified + // $val1[0] = ENCODING + // $val1[1] = 'text' + $value = isset($val1[1]) ? $val1[1] : ''; // If data available + $seq .= $this->{'setParse' . $this->METHOD[$val1[0]]}($value, $currentMode); + $this->text .= $value; + } + } + } + + if ($seq !== '') { + $bitstream = $this->createBinaryStream($this->text, $seq); + $this->setData($bitstream); + } + + $this->addDefaultLabel(); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $c = count($this->data); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->data[$i], true); + } + + $this->drawChar($im, '1', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + // Contains start + text + checksum + stop + $textlength = count($this->data) * 11; + $endlength = 2; // + final bar + + $w += $textlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = count($this->data); + if ($c === 0) { + throw new BCGParseException('code128', 'No data has been entered.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Checksum + // First Char (START) + // + Starting with the first data character following the start character, + // take the value of the character (between 0 and 102, inclusive) multiply + // it by its character position (1) and add that to the running checksum. + // Modulated 103 + $this->checksumValue = $this->indcheck[0]; + $c = count($this->indcheck); + for ($i = 1; $i < $c; $i++) { + $this->checksumValue += $this->indcheck[$i] * $i; + } + + $this->checksumValue = $this->checksumValue % 103; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + if ($this->lastTable === 'C') { + return (string)$this->checksumValue; + } + + return $this->{'keys' . $this->lastTable}[$this->checksumValue]; + } + + return false; + } + + /** + * Specifies the starting_text table if none has been specified earlier. + * + * @param string $text + */ + private function setStartFromText($text) { + if ($this->starting_text === null) { + // If we have a forced table at the start, we get that one... + if (is_array($text)) { + if (is_array($text[0])) { + // Code like array(array(ENCODING, '')) + $this->starting_text = $this->METHOD[$text[0][0]]; + return; + } else { + if (is_string($text[0])) { + // Code like array('test') (Automatic text) + $text = $text[0]; + } else { + // Code like array(ENCODING, '') + $this->starting_text = $this->METHOD[$text[0]]; + return; + } + } + } + + // At this point, we had an "automatic" table selection... + // If we can get at least 4 numbers, go in C; otherwise go in B. + $tmp = preg_quote($this->keysC, '/'); + $length = strlen($text); + if ($length >= 4 && preg_match('/[' . $tmp . ']/', substr($text, 0, 4))) { + $this->starting_text = 'C'; + } else { + if ($length > 0 && strpos($this->keysB, $text[0]) !== false) { + $this->starting_text = 'B'; + } else { + $this->starting_text = 'A'; + } + } + } + } + + /** + * Extracts the ~ value from the $text at the $pos. + * If the tilde is not ~~, ~F1, ~F2, ~F3, ~F4; an error is raised. + * + * @param string $text + * @param int $pos + * @return string + */ + private static function extractTilde($text, $pos) { + if ($text[$pos] === '~') { + if (isset($text[$pos + 1])) { + // Do we have a tilde? + if ($text[$pos + 1] === '~') { + return '~~'; + } elseif ($text[$pos + 1] === 'F') { + // Do we have a number after? + if (isset($text[$pos + 2])) { + $v = intval($text[$pos + 2]); + if ($v >= 1 && $v <= 4) { + return '~F' . $v; + } else { + throw new BCGParseException('code128', 'Bad ~F. You must provide a number from 1 to 4.'); + } + } else { + throw new BCGParseException('code128', 'Bad ~F. You must provide a number from 1 to 4.'); + } + } else { + throw new BCGParseException('code128', 'Wrong code after the ~.'); + } + } else { + throw new BCGParseException('code128', 'Wrong code after the ~.'); + } + } else { + throw new BCGParseException('code128', 'There is no ~ at this location.'); + } + } + + /** + * Gets the "dotted" sequence for the $text based on the $currentMode. + * There is also a check if we use the special tilde ~ + * + * @param string $text + * @param string $currentMode + * @return string + */ + private function getSequenceParsed($text, $currentMode) { + if ($this->tilde) { + $sequence = ''; + $previousPos = 0; + while (($pos = strpos($text, '~', $previousPos)) !== false) { + $tildeData = self::extractTilde($text, $pos); + + $simpleTilde = ($tildeData === '~~'); + if ($simpleTilde && $currentMode !== 'B') { + throw new BCGParseException('code128', 'The Table ' . $currentMode . ' doesn\'t contain the character ~.'); + } + + // At this point, we know we have ~Fx + if ($tildeData !== '~F1' && $currentMode === 'C') { + // The mode C doesn't support ~F2, ~F3, ~F4 + throw new BCGParseException('code128', 'The Table C doesn\'t contain the function ' . $tildeData . '.'); + } + + $length = $pos - $previousPos; + if ($currentMode === 'C') { + if ($length % 2 === 1) { + throw new BCGParseException('code128', 'The text "' . $text . '" must have an even number of character to be encoded in Table C.'); + } + } + + $sequence .= str_repeat('.', $length); + $sequence .= '.'; + $sequence .= (!$simpleTilde) ? 'F' : ''; + $previousPos = $pos + strlen($tildeData); + } + + // Flushing + $length = strlen($text) - $previousPos; + if ($currentMode === 'C') { + if ($length % 2 === 1) { + throw new BCGParseException('code128', 'The text "' . $text . '" must have an even number of character to be encoded in Table C.'); + } + } + + $sequence .= str_repeat('.', $length); + + return $sequence; + } else { + return str_repeat('.', strlen($text)); + } + } + + /** + * Parses the text and returns the appropriate sequence for the Table A. + * + * @param string $text + * @param string $currentMode + * @return string + */ + private function setParseA($text, &$currentMode) { + $tmp = preg_quote($this->keysA, '/'); + + // If we accept the ~ for special character, we must allow it. + if ($this->tilde) { + $tmp .= '~'; + } + + $match = array(); + if (preg_match('/[^' . $tmp . ']/', $text, $match) === 1) { + // We found something not allowed + throw new BCGParseException('code128', 'The text "' . $text . '" can\'t be parsed with the Table A. The character "' . $match[0] . '" is not allowed.'); + } else { + $latch = ($currentMode === 'A') ? '' : '0'; + $currentMode = 'A'; + + return $latch . $this->getSequenceParsed($text, $currentMode); + } + } + + /** + * Parses the text and returns the appropriate sequence for the Table B. + * + * @param string $text + * @param string $currentMode + * @return string + */ + private function setParseB($text, &$currentMode) { + $tmp = preg_quote($this->keysB, '/'); + + $match = array(); + if (preg_match('/[^' . $tmp . ']/', $text, $match) === 1) { + // We found something not allowed + throw new BCGParseException('code128', 'The text "' . $text . '" can\'t be parsed with the Table B. The character "' . $match[0] . '" is not allowed.'); + } else { + $latch = ($currentMode === 'B') ? '' : '1'; + $currentMode = 'B'; + + return $latch . $this->getSequenceParsed($text, $currentMode); + } + } + + /** + * Parses the text and returns the appropriate sequence for the Table C. + * + * @param string $text + * @param string $currentMode + * @return string + */ + private function setParseC($text, &$currentMode) { + $tmp = preg_quote($this->keysC, '/'); + + // If we accept the ~ for special character, we must allow it. + if ($this->tilde) { + $tmp .= '~F'; + } + + $match = array(); + if (preg_match('/[^' . $tmp . ']/', $text, $match) === 1) { + // We found something not allowed + throw new BCGParseException('code128', 'The text "' . $text . '" can\'t be parsed with the Table C. The character "' . $match[0] . '" is not allowed.'); + } else { + $latch = ($currentMode === 'C') ? '' : '2'; + $currentMode = 'C'; + + return $latch . $this->getSequenceParsed($text, $currentMode); + } + } + + /** + * Depending on the $text, it will return the correct + * sequence to encode the text. + * + * @param string $text + * @param string $starting_text + * @return string + */ + private function getSequence($text, &$starting_text) { + $e = 10000; + $latLen = array( + array(0, 1, 1), + array(1, 0, 1), + array(1, 1, 0) + ); + $shftLen = array( + array($e, 1, $e), + array(1, $e, $e), + array($e, $e, $e) + ); + $charSiz = array(2, 2, 1); + + $startA = $e; + $startB = $e; + $startC = $e; + if ($starting_text === 'A') { $startA = 0; } + if ($starting_text === 'B') { $startB = 0; } + if ($starting_text === 'C') { $startC = 0; } + + $curLen = array($startA, $startB, $startC); + $curSeq = array(null, null, null); + + $nextNumber = false; + + $x = 0; + $xLen = strlen($text); + for ($x = 0; $x < $xLen; $x++) { + $input = $text[$x]; + + // 1. + for ($i = 0; $i < 3; $i++) { + for ($j = 0; $j < 3; $j++) { + if (($curLen[$i] + $latLen[$i][$j]) < $curLen[$j]) { + $curLen[$j] = $curLen[$i] + $latLen[$i][$j]; + $curSeq[$j] = $curSeq[$i] . $j; + } + } + } + + // 2. + $nxtLen = array($e, $e, $e); + $nxtSeq = array(); + + // 3. + $flag = false; + $posArray = array(); + + // Special case, we do have a tilde and we process them + if ($this->tilde && $input === '~') { + $tildeData = self::extractTilde($text, $x); + + if ($tildeData === '~~') { + // We simply skip a tilde + $posArray[] = 1; + $x++; + } elseif (substr($tildeData, 0, 2) === '~F') { + $v = intval($tildeData[2]); + $posArray[] = 0; + $posArray[] = 1; + if ($v === 1) { + $posArray[] = 2; + } + + $x += 2; + $flag = true; + } + } else { + $pos = strpos($this->keysA, $input); + if ($pos !== false) { + $posArray[] = 0; + } + + $pos = strpos($this->keysB, $input); + if ($pos !== false) { + $posArray[] = 1; + } + + // Do we have the next char a number?? OR a ~F1 + $pos = strpos($this->keysC, $input); + if ($nextNumber || ($pos !== false && isset($text[$x + 1]) && strpos($this->keysC, $text[$x + 1]) !== false)) { + $nextNumber = !$nextNumber; + $posArray[] = 2; + } + } + + $c = count($posArray); + for ($i = 0; $i < $c; $i++) { + if (($curLen[$posArray[$i]] + $charSiz[$posArray[$i]]) < $nxtLen[$posArray[$i]]) { + $nxtLen[$posArray[$i]] = $curLen[$posArray[$i]] + $charSiz[$posArray[$i]]; + $nxtSeq[$posArray[$i]] = $curSeq[$posArray[$i]] . '.'; + } + + for ($j = 0; $j < 2; $j++) { + if ($j === $posArray[$i]) { continue; } + if (($curLen[$j] + $shftLen[$j][$posArray[$i]] + $charSiz[$posArray[$i]]) < $nxtLen[$j]) { + $nxtLen[$j] = $curLen[$j] + $shftLen[$j][$posArray[$i]] + $charSiz[$posArray[$i]]; + $nxtSeq[$j] = $curSeq[$j] . chr($posArray[$i] + 65) . '.'; + } + } + } + + if ($c === 0) { + // We found an unsuported character + throw new BCGParseException('code128', 'Character ' . $input . ' not supported.'); + } + + if ($flag) { + for ($i = 0; $i < 5; $i++) { + if (isset($nxtSeq[$i])) { + $nxtSeq[$i] .= 'F'; + } + } + } + + // 4. + for ($i = 0; $i < 3; $i++) { + $curLen[$i] = $nxtLen[$i]; + if (isset($nxtSeq[$i])) { + $curSeq[$i] = $nxtSeq[$i]; + } + } + } + + // Every curLen under $e is possible but we take the smallest + $m = $e; + $k = -1; + for ($i = 0; $i < 3; $i++) { + if ($curLen[$i] < $m) { + $k = $i; + $m = $curLen[$i]; + } + } + + if ($k === -1) { + return ''; + } + + return $curSeq[$k]; + } + + /** + * Depending on the sequence $seq given (returned from getSequence()), + * this method will return the code stream in an array. Each char will be a + * string of bit based on the Code 128. + * + * Each letter from the sequence represents bits. + * + * 0 to 2 are latches + * A to B are Shift + Letter + * . is a char in the current encoding + * + * @param string $text + * @param string $seq + * @return string[][] + */ + private function createBinaryStream($text, $seq) { + $c = strlen($seq); + + $data = array(); // code stream + $indcheck = array(); // index for checksum + + $currentEncoding = 0; + if ($this->starting_text === 'A') { + $currentEncoding = 0; + $indcheck[] = self::KEY_STARTA; + $this->lastTable = 'A'; + } elseif ($this->starting_text === 'B') { + $currentEncoding = 1; + $indcheck[] = self::KEY_STARTB; + $this->lastTable = 'B'; + } elseif ($this->starting_text === 'C') { + $currentEncoding = 2; + $indcheck[] = self::KEY_STARTC; + $this->lastTable = 'C'; + } + + $data[] = $this->code[103 + $currentEncoding]; + + $temporaryEncoding = -1; + for ($i = 0, $counter = 0; $i < $c; $i++) { + $input = $seq[$i]; + $inputI = intval($input); + if ($input === '.') { + $this->encodeChar($data, $currentEncoding, $seq, $text, $i, $counter, $indcheck); + if ($temporaryEncoding !== -1) { + $currentEncoding = $temporaryEncoding; + $temporaryEncoding = -1; + } + } elseif ($input >= 'A' && $input <= 'B') { + // We shift + $encoding = ord($input) - 65; + $shift = $this->shift[$currentEncoding][$encoding]; + $indcheck[] = $shift; + $data[] = $this->code[$shift]; + if ($temporaryEncoding === -1) { + $temporaryEncoding = $currentEncoding; + } + + $currentEncoding = $encoding; + } elseif ($inputI >= 0 && $inputI < 3) { + $temporaryEncoding = -1; + + // We latch + $latch = $this->latch[$currentEncoding][$inputI]; + if ($latch !== null) { + $indcheck[] = $latch; + $this->lastTable = chr(65 + $inputI); + $data[] = $this->code[$latch]; + $currentEncoding = $inputI; + } + } + } + + return array($indcheck, $data); + } + + /** + * Encodes characters, base on its encoding and sequence + * + * @param int[] $data + * @param int $encoding + * @param string $seq + * @param string $text + * @param int $i + * @param int $counter + * @param int[] $indcheck + */ + private function encodeChar(&$data, $encoding, $seq, $text, &$i, &$counter, &$indcheck) { + if (isset($seq[$i + 1]) && $seq[$i + 1] === 'F') { + // We have a flag !! + if ($text[$counter + 1] === 'F') { + $number = $text[$counter + 2]; + $fnc = $this->fnc[$encoding][$number - 1]; + $indcheck[] = $fnc; + $data[] = $this->code[$fnc]; + + // Skip F + number + $counter += 2; + } else { + // Not supposed + } + + $i++; + } else { + if ($encoding === 2) { + // We take 2 numbers in the same time + $code = (int)substr($text, $counter, 2); + $indcheck[] = $code; + $data[] = $this->code[$code]; + $counter++; + $i++; + } else { + $keys = ($encoding === 0) ? $this->keysA : $this->keysB; + $pos = strpos($keys, $text[$counter]); + $indcheck[] = $pos; + $data[] = $this->code[$pos]; + } + } + + $counter++; + } + + /** + * Saves data into the classes. + * + * This method will save data, calculate real column number + * (if -1 was selected), the real error level (if -1 was + * selected)... It will add Padding to the end and generate + * the error codes. + * + * @param array $data + */ + private function setData($data) { + $this->indcheck = $data[0]; + $this->data = $data[1]; + $this->calculateChecksum(); + $this->data[] = $this->code[$this->checksumValue]; + $this->data[] = $this->code[self::KEY_STOP]; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGcode39.barcode.php b/niucloud/core/core/util/barcode/class/BCGcode39.barcode.php new file mode 100644 index 00000000..11e37124 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGcode39.barcode.php @@ -0,0 +1,193 @@ +starting = $this->ending = 43; + $this->keys = 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', '-', '.', ' ', '$', '/', '+', '%', '*'); + $this->code = array( // 0 added to add an extra space + '0001101000', /* 0 */ + '1001000010', /* 1 */ + '0011000010', /* 2 */ + '1011000000', /* 3 */ + '0001100010', /* 4 */ + '1001100000', /* 5 */ + '0011100000', /* 6 */ + '0001001010', /* 7 */ + '1001001000', /* 8 */ + '0011001000', /* 9 */ + '1000010010', /* A */ + '0010010010', /* B */ + '1010010000', /* C */ + '0000110010', /* D */ + '1000110000', /* E */ + '0010110000', /* F */ + '0000011010', /* G */ + '1000011000', /* H */ + '0010011000', /* I */ + '0000111000', /* J */ + '1000000110', /* K */ + '0010000110', /* L */ + '1010000100', /* M */ + '0000100110', /* N */ + '1000100100', /* O */ + '0010100100', /* P */ + '0000001110', /* Q */ + '1000001100', /* R */ + '0010001100', /* S */ + '0000101100', /* T */ + '1100000010', /* U */ + '0110000010', /* V */ + '1110000000', /* W */ + '0100100010', /* X */ + '1100100000', /* Y */ + '0110100000', /* Z */ + '0100001010', /* - */ + '1100001000', /* . */ + '0110001000', /* */ + '0101010000', /* $ */ + '0101000100', /* / */ + '0100010100', /* + */ + '0001010100', /* % */ + '0100101000' /* * */ + ); + + $this->setChecksum(false); + } + + /** + * Sets if we display the checksum. + * + * @param bool $checksum + */ + public function setChecksum($checksum) { + $this->checksum = (bool)$checksum; + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + parent::parse(strtoupper($text)); // Only Capital Letters are Allowed + } + + /** + * Draws the Barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting * + $this->drawChar($im, $this->code[$this->starting], true); + + // Chars + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i]), true); + } + + // Checksum (rarely used) + if ($this->checksum === true) { + $this->calculateChecksum(); + $this->drawChar($im, $this->code[$this->checksumValue % 43], true); + } + + // Ending * + $this->drawChar($im, $this->code[$this->ending], true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a Barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textlength = 13 * strlen($this->text); + $startlength = 13; + $checksumlength = 0; + if ($this->checksum === true) { + $checksumlength = 13; + } + + $endlength = 13; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('code39', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('code39', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + if (strpos($this->text, '*') !== false) { + throw new BCGParseException('code39', 'The character \'*\' is not allowed.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->checksumValue += $this->findIndex($this->text[$i]); + } + + $this->checksumValue = $this->checksumValue % 43; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGcode39extended.barcode.php b/niucloud/core/core/util/barcode/class/BCGcode39extended.barcode.php new file mode 100644 index 00000000..fca6f1a2 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGcode39extended.barcode.php @@ -0,0 +1,208 @@ +keys[self::EXTENDED_1] = '($)'; + $this->keys[self::EXTENDED_2] = '(/)'; + $this->keys[self::EXTENDED_3] = '(+)'; + $this->keys[self::EXTENDED_4] = '(%)'; + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + $this->text = $text; + + $data = array(); + $indcheck = array(); + + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $pos = array_search($this->text[$i], $this->keys); + if ($pos === false) { + // Search in extended? + $extended = self::getExtendedVersion($this->text[$i]); + if ($extended === false) { + throw new BCGParseException('code39extended', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } else { + $extc = strlen($extended); + for ($j = 0; $j < $extc; $j++) { + $v = $extended[$j]; + if ($v === '$') { + $indcheck[] = self::EXTENDED_1; + $data[] = $this->code[self::EXTENDED_1]; + } elseif ($v === '%') { + $indcheck[] = self::EXTENDED_2; + $data[] = $this->code[self::EXTENDED_2]; + } elseif ($v === '/') { + $indcheck[] = self::EXTENDED_3; + $data[] = $this->code[self::EXTENDED_3]; + } elseif ($v === '+') { + $indcheck[] = self::EXTENDED_4; + $data[] = $this->code[self::EXTENDED_4]; + } else { + $pos2 = array_search($v, $this->keys); + $indcheck[] = $pos2; + $data[] = $this->code[$pos2]; + } + } + } + } else { + $indcheck[] = $pos; + $data[] = $this->code[$pos]; + } + } + + $this->setData(array($indcheck, $data)); + $this->addDefaultLabel(); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting * + $this->drawChar($im, $this->code[$this->starting], true); + $c = count($this->data); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->data[$i], true); + } + + // Checksum (rarely used) + if ($this->checksum === true) { + $this->drawChar($im, $this->code[$this->checksumValue % 43], true); + } + + // Ending * + $this->drawChar($im, $this->code[$this->ending], true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textlength = 13 * count($this->data); + $startlength = 13; + $checksumlength = 0; + if ($this->checksum === true) { + $checksumlength = 13; + } + + $endlength = 13; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return BCGBarcode1D::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = count($this->data); + if ($c === 0) { + throw new BCGParseException('code39extended', 'No data has been entered.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + $this->checksumValue = 0; + $c = count($this->indcheck); + for ($i = 0; $i < $c; $i++) { + $this->checksumValue += $this->indcheck[$i]; + } + + $this->checksumValue = $this->checksumValue % 43; + } + + /** + * Saves data into the classes. + * + * This method will save data, calculate real column number + * (if -1 was selected), the real error level (if -1 was + * selected)... It will add Padding to the end and generate + * the error codes. + * + * @param array $data + */ + private function setData($data) { + $this->indcheck = $data[0]; + $this->data = $data[1]; + $this->calculateChecksum(); + } + + /** + * Returns the extended reprensentation of the character. + * + * @param string $char + * @return string + */ + private static function getExtendedVersion($char) { + $o = ord($char); + if ($o === 0) { + return '%U'; + } elseif ($o >= 1 && $o <= 26) { + return '$' . chr($o + 64); + } elseif (($o >= 33 && $o <= 44) || $o === 47 || $o === 48) { + return '/' . chr($o + 32); + } elseif ($o >= 97 && $o <= 122) { + return '+' . chr($o - 32); + } elseif ($o >= 27 && $o <= 31) { + return '%' . chr($o + 38); + } elseif ($o >= 59 && $o <= 63) { + return '%' . chr($o + 11); + } elseif ($o >= 91 && $o <= 95) { + return '%' . chr($o - 16); + } elseif ($o >= 123 && $o <= 127) { + return '%' . chr($o - 43); + } elseif ($o === 64) { + return '%V'; + } elseif ($o === 96) { + return '%W'; + } elseif ($o > 127) { + return false; + } else { + return $char; + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGcode93.barcode.php b/niucloud/core/core/util/barcode/class/BCGcode93.barcode.php new file mode 100644 index 00000000..480e2c8f --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGcode93.barcode.php @@ -0,0 +1,301 @@ +starting = $this->ending = 47; /* * */ + $this->keys = 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', '-', '.', ' ', '$', '/', '+', '%', '($)', '(%)', '(/)', '(+)', '(*)'); + $this->code = array( + '020001', /* 0 */ + '000102', /* 1 */ + '000201', /* 2 */ + '000300', /* 3 */ + '010002', /* 4 */ + '010101', /* 5 */ + '010200', /* 6 */ + '000003', /* 7 */ + '020100', /* 8 */ + '030000', /* 9 */ + '100002', /* A */ + '100101', /* B */ + '100200', /* C */ + '110001', /* D */ + '110100', /* E */ + '120000', /* F */ + '001002', /* G */ + '001101', /* H */ + '001200', /* I */ + '011001', /* J */ + '021000', /* K */ + '000012', /* L */ + '000111', /* M */ + '000210', /* N */ + '010011', /* O */ + '020010', /* P */ + '101001', /* Q */ + '101100', /* R */ + '100011', /* S */ + '100110', /* T */ + '110010', /* U */ + '111000', /* V */ + '001011', /* W */ + '001110', /* X */ + '011010', /* Y */ + '012000', /* Z */ + '010020', /* - */ + '200001', /* . */ + '200100', /* */ + '210000', /* $ */ + '001020', /* / */ + '002010', /* + */ + '100020', /* % */ + '010110', /*($)*/ + '201000', /*(%)*/ + '200010', /*(/)*/ + '011100', /*(+)*/ + '000030' /*(*)*/ + ); + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + $this->text = $text; + + $data = array(); + $indcheck = array(); + + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $pos = array_search($this->text[$i], $this->keys); + if ($pos === false) { + // Search in extended? + $extended = self::getExtendedVersion($this->text[$i]); + if ($extended === false) { + throw new BCGParseException('code93', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } else { + $extc = strlen($extended); + for ($j = 0; $j < $extc; $j++) { + $v = $extended[$j]; + if ($v === '$') { + $indcheck[] = self::EXTENDED_1; + $data[] = $this->code[self::EXTENDED_1]; + } elseif ($v === '%') { + $indcheck[] = self::EXTENDED_2; + $data[] = $this->code[self::EXTENDED_2]; + } elseif ($v === '/') { + $indcheck[] = self::EXTENDED_3; + $data[] = $this->code[self::EXTENDED_3]; + } elseif ($v === '+') { + $indcheck[] = self::EXTENDED_4; + $data[] = $this->code[self::EXTENDED_4]; + } else { + $pos2 = array_search($v, $this->keys); + $indcheck[] = $pos2; + $data[] = $this->code[$pos2]; + } + } + } + } else { + $indcheck[] = $pos; + $data[] = $this->code[$pos]; + } + } + + $this->setData(array($indcheck, $data)); + $this->addDefaultLabel(); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting * + $this->drawChar($im, $this->code[$this->starting], true); + $c = count($this->data); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->data[$i], true); + } + + // Checksum + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->code[$this->checksumValue[$i]], true); + } + + // Ending * + $this->drawChar($im, $this->code[$this->ending], true); + + // Draw a Final Bar + $this->drawChar($im, '0', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 9; + $textlength = 9 * count($this->data); + $checksumlength = 2 * 9; + $endlength = 9 + 1; // + final bar + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = count($this->data); + if ($c === 0) { + throw new BCGParseException('code93', 'No data has been entered.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Checksum + // First CheckSUM "C" + // The "C" checksum character is the modulo 47 remainder of the sum of the weighted + // value of the data characters. The weighting value starts at "1" for the right-most + // data character, 2 for the second to last, 3 for the third-to-last, and so on up to 20. + // After 20, the sequence wraps around back to 1. + + // Second CheckSUM "K" + // Same as CheckSUM "C" but we count the CheckSum "C" at the end + // After 15, the sequence wraps around back to 1. + $sequence_multiplier = array(20, 15); + $this->checksumValue = array(); + $indcheck = $this->indcheck; + for ($z = 0; $z < 2; $z++) { + $checksum = 0; + for ($i = count($indcheck), $j = 0; $i > 0; $i--, $j++) { + $multiplier = $i % $sequence_multiplier[$z]; + if ($multiplier === 0) { + $multiplier = $sequence_multiplier[$z]; + } + + $checksum += $indcheck[$j] * $multiplier; + } + + $this->checksumValue[$z] = $checksum % 47; + $indcheck[] = $this->checksumValue[$z]; + } + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + $ret = ''; + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $ret .= $this->keys[$this->checksumValue[$i]]; + } + + return $ret; + } + + return false; + } + + /** + * Saves data into the classes. + * + * This method will save data, calculate real column number + * (if -1 was selected), the real error level (if -1 was + * selected)... It will add Padding to the end and generate + * the error codes. + * + * @param array $data + */ + private function setData($data) { + $this->indcheck = $data[0]; + $this->data = $data[1]; + $this->calculateChecksum(); + } + + /** + * Returns the extended reprensentation of the character. + * + * @param string $char + * @return string + */ + private static function getExtendedVersion($char) { + $o = ord($char); + if ($o === 0) { + return '%U'; + } elseif ($o >= 1 && $o <= 26) { + return '$' . chr($o + 64); + } elseif (($o >= 33 && $o <= 44) || $o === 47 || $o === 48) { + return '/' . chr($o + 32); + } elseif ($o >= 97 && $o <= 122) { + return '+' . chr($o - 32); + } elseif ($o >= 27 && $o <= 31) { + return '%' . chr($o + 38); + } elseif ($o >= 59 && $o <= 63) { + return '%' . chr($o + 11); + } elseif ($o >= 91 && $o <= 95) { + return '%' . chr($o - 16); + } elseif ($o >= 123 && $o <= 127) { + return '%' . chr($o - 43); + } elseif ($o === 64) { + return '%V'; + } elseif ($o === 96) { + return '%W'; + } elseif ($o > 127) { + return false; + } else { + return $char; + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGean13.barcode.php b/niucloud/core/core/util/barcode/class/BCGean13.barcode.php new file mode 100644 index 00000000..5289183e --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGean13.barcode.php @@ -0,0 +1,322 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + + // Left-Hand Odd Parity starting with a space + // Left-Hand Even Parity is the inverse (0=0012) starting with a space + // Right-Hand is the same of Left-Hand starting with a bar + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + + // Parity, 0=Odd, 1=Even for manufacturer code. Depending on 1st System Digit + $this->codeParity = array( + array(0, 0, 0, 0, 0), /* 0 */ + array(0, 1, 0, 1, 1), /* 1 */ + array(0, 1, 1, 0, 1), /* 2 */ + array(0, 1, 1, 1, 0), /* 3 */ + array(1, 0, 0, 1, 1), /* 4 */ + array(1, 1, 0, 0, 1), /* 5 */ + array(1, 1, 1, 0, 0), /* 6 */ + array(1, 0, 1, 0, 1), /* 7 */ + array(1, 0, 1, 1, 0), /* 8 */ + array(1, 1, 0, 1, 0) /* 9 */ + ); + + $this->alignDefaultLabel(true); + } + + public function alignDefaultLabel($align) { + $this->alignLabel = (bool)$align; + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $this->drawBars($im); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + + if ($this->isDefaultEanLabelEnabled()) { + $dimension = $this->labelCenter1->getDimension(); + $this->drawExtendedBars($im, $dimension[1] - 2); + } + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 3; + $centerlength = 5; + $textlength = 12 * 7; + $endlength = 3; + + $w += $startlength + $centerlength + $textlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $this->processChecksum(); + $label = $this->getLabel(); + $font = $this->font; + + $this->labelLeft = new BCGLabel(substr($label, 0, 1), $font, BCGLabel::POSITION_LEFT, BCGLabel::ALIGN_BOTTOM); + $this->labelLeft->setSpacing(4 * $this->scale); + + $this->labelCenter1 = new BCGLabel(substr($label, 1, 6), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelCenter1Dimension = $this->labelCenter1->getDimension(); + $this->labelCenter1->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 2); + + $this->labelCenter2 = new BCGLabel(substr($label, 7, 5) . $this->keys[$this->checksumValue], $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $this->labelCenter2->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 48); + + if ($this->alignLabel) { + $labelDimension = $this->labelCenter1->getDimension(); + $this->labelLeft->setOffset($labelDimension[1]); + } else { + $labelDimension = $this->labelLeft->getDimension(); + $this->labelLeft->setOffset($labelDimension[1] / 2); + } + + $this->addLabel($this->labelLeft); + $this->addLabel($this->labelCenter1); + $this->addLabel($this->labelCenter2); + } + } + + /** + * Checks if the default ean label is enabled. + * + * @return bool + */ + protected function isDefaultEanLabelEnabled() { + $label = $this->getLabel(); + $font = $this->font; + return $label !== null && $label !== '' && $font !== null && $this->defaultLabel !== null; + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('ean13', 'No data has been entered.'); + } + + $this->checkCharsAllowed(); + $this->checkCorrectLength(); + + parent::validate(); + } + + /** + * Check chars allowed. + */ + protected function checkCharsAllowed() { + // Checking if all chars are allowed + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('ean13', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + } + + /** + * Check correct length. + */ + protected function checkCorrectLength() { + // If we have 13 chars, just flush the last one without throwing anything + $c = strlen($this->text); + if ($c === 13) { + $this->text = substr($this->text, 0, 12); + } elseif ($c !== 12) { + throw new BCGParseException('ean13', 'Must contain 12 digits, the 13th digit is automatically added.'); + } + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $odd = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 1; + $odd = true; + } + + if (!isset($this->keys[$this->text[$i - 1]])) { + return; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Draws the bars + * + * @param resource $im + */ + protected function drawBars($im) { + // Checksum + $this->calculateChecksum(); + $temp_text = $this->text . $this->keys[$this->checksumValue]; + + // Starting Code + $this->drawChar($im, '000', true); + + // Draw Second Code + $this->drawChar($im, $this->findCode($temp_text[1]), false); + + // Draw Manufacturer Code + for ($i = 0; $i < 5; $i++) { + $this->drawChar($im, self::inverse($this->findCode($temp_text[$i + 2]), $this->codeParity[(int)$temp_text[0]][$i]), false); + } + + // Draw Center Guard Bar + $this->drawChar($im, '00000', false); + + // Draw Product Code + for ($i = 7; $i < 13; $i++) { + $this->drawChar($im, $this->findCode($temp_text[$i]), true); + } + + // Draw Right Guard Bar + $this->drawChar($im, '000', true); + } + + /** + * Draws the extended bars on the image. + * + * @param resource $im + * @param int $plus + */ + protected function drawExtendedBars($im, $plus) { + $rememberX = $this->positionX; + $rememberH = $this->thickness; + + // We increase the bars + $this->thickness = $this->thickness + intval($plus / $this->scale); + $this->positionX = 0; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Center Guard Bar + $this->positionX += 44; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Last Bars + $this->positionX += 44; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + $this->positionX = $rememberX; + $this->thickness = $rememberH; + } + + /** + * Inverses the string when the $inverse parameter is equal to 1. + * + * @param string $text + * @param int $inverse + * @return string + */ + private static function inverse($text, $inverse = 1) { + if ($inverse === 1) { + $text = strrev($text); + } + + return $text; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGean8.barcode.php b/niucloud/core/core/util/barcode/class/BCGean8.barcode.php new file mode 100644 index 00000000..b89eb77b --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGean8.barcode.php @@ -0,0 +1,244 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + + // Left-Hand Odd Parity starting with a space + // Right-Hand is the same of Left-Hand starting with a bar + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Checksum + $this->calculateChecksum(); + $temp_text = $this->text . $this->keys[$this->checksumValue]; + + // Starting Code + $this->drawChar($im, '000', true); + + // Draw First 4 Chars (Left-Hand) + for ($i = 0; $i < 4; $i++) { + $this->drawChar($im, $this->findCode($temp_text[$i]), false); + } + + // Draw Center Guard Bar + $this->drawChar($im, '00000', false); + + // Draw Last 4 Chars (Right-Hand) + for ($i = 4; $i < 8; $i++) { + $this->drawChar($im, $this->findCode($temp_text[$i]), true); + } + + // Draw Right Guard Bar + $this->drawChar($im, '000', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + + if ($this->isDefaultEanLabelEnabled()) { + $dimension = $this->labelRight->getDimension(); + $this->drawExtendedBars($im, $dimension[1] - 2); + } + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 3; + $centerlength = 5; + $textlength = 8 * 7; + $endlength = 3; + + $w += $startlength + $centerlength + $textlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $this->processChecksum(); + $label = $this->getLabel(); + $font = $this->font; + + $this->labelLeft = new BCGLabel(substr($label, 0, 4), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelLeftDimension = $this->labelLeft->getDimension(); + $this->labelLeft->setOffset(($this->scale * 30 - $labelLeftDimension[0]) / 2 + $this->scale * 2); + + $this->labelRight = new BCGLabel(substr($label, 4, 3) . $this->keys[$this->checksumValue], $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelRightDimension = $this->labelRight->getDimension(); + $this->labelRight->setOffset(($this->scale * 30 - $labelRightDimension[0]) / 2 + $this->scale * 34); + + $this->addLabel($this->labelLeft); + $this->addLabel($this->labelRight); + } + } + + /** + * Checks if the default ean label is enabled. + * + * @return bool + */ + protected function isDefaultEanLabelEnabled() { + $label = $this->getLabel(); + $font = $this->font; + return $label !== null && $label !== '' && $font !== null && $this->defaultLabel !== null; + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('ean8', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('ean8', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // If we have 8 chars just flush the last one + if ($c === 8) { + $this->text = substr($this->text, 0, 7); + } elseif ($c !== 7) { + throw new BCGParseException('ean8', 'Must contain 7 digits, the 8th digit is automatically added.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $odd = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 1; + $odd = true; + } + + if (!isset($this->keys[$this->text[$i - 1]])) { + return; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Draws the extended bars on the image. + * + * @param resource $im + * @param int $plus + */ + private function drawExtendedBars($im, $plus) { + $rememberX = $this->positionX; + $rememberH = $this->thickness; + + // We increase the bars + $this->thickness = $this->thickness + intval($plus / $this->scale); + $this->positionX = 0; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Center Guard Bar + $this->positionX += 30; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Last Bars + $this->positionX += 30; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + $this->positionX = $rememberX; + $this->thickness = $rememberH; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGgs1128.barcode.php b/niucloud/core/core/util/barcode/class/BCGgs1128.barcode.php new file mode 100644 index 00000000..0393f245 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGgs1128.barcode.php @@ -0,0 +1,679 @@ +identifiersAi = array( + '00' => array(self::NUMERIC, 18, 18, true), + '01' => array(self::NUMERIC, 14, 14, true), + '02' => array(self::NUMERIC, 14, 14, true), + '10' => array(self::ALPHA_NUMERIC, 1, 20, false), + '11' => array(self::DATE_YYMMDD, 6, 6, false), + '12' => array(self::DATE_YYMMDD, 6, 6, false), + '13' => array(self::DATE_YYMMDD, 6, 6, false), + '15' => array(self::DATE_YYMMDD, 6, 6, false), + '17' => array(self::DATE_YYMMDD, 6, 6, false), + '20' => array(self::NUMERIC, 2, 2, false), + '21' => array(self::ALPHA_NUMERIC, 1, 20, false), + '240' => array(self::ALPHA_NUMERIC, 1, 30, false), + '241' => array(self::ALPHA_NUMERIC, 1, 30, false), + '250' => array(self::ALPHA_NUMERIC, 1, 30, false), + '251' => array(self::ALPHA_NUMERIC, 1, 30, false), + '253' => array(self::NUMERIC, 14, 30, false), + '30' => array(self::NUMERIC, 1, 8, false), + '310y' => array(self::NUMERIC, 6, 6, false), + '311y' => array(self::NUMERIC, 6, 6, false), + '312y' => array(self::NUMERIC, 6, 6, false), + '313y' => array(self::NUMERIC, 6, 6, false), + '314y' => array(self::NUMERIC, 6, 6, false), + '315y' => array(self::NUMERIC, 6, 6, false), + '316y' => array(self::NUMERIC, 6, 6, false), + '320y' => array(self::NUMERIC, 6, 6, false), + '321y' => array(self::NUMERIC, 6, 6, false), + '322y' => array(self::NUMERIC, 6, 6, false), + '323y' => array(self::NUMERIC, 6, 6, false), + '324y' => array(self::NUMERIC, 6, 6, false), + '325y' => array(self::NUMERIC, 6, 6, false), + '326y' => array(self::NUMERIC, 6, 6, false), + '327y' => array(self::NUMERIC, 6, 6, false), + '328y' => array(self::NUMERIC, 6, 6, false), + '329y' => array(self::NUMERIC, 6, 6, false), + '330y' => array(self::NUMERIC, 6, 6, false), + '331y' => array(self::NUMERIC, 6, 6, false), + '332y' => array(self::NUMERIC, 6, 6, false), + '333y' => array(self::NUMERIC, 6, 6, false), + '334y' => array(self::NUMERIC, 6, 6, false), + '335y' => array(self::NUMERIC, 6, 6, false), + '336y' => array(self::NUMERIC, 6, 6, false), + '337y' => array(self::NUMERIC, 6, 6, false), + '340y' => array(self::NUMERIC, 6, 6, false), + '341y' => array(self::NUMERIC, 6, 6, false), + '342y' => array(self::NUMERIC, 6, 6, false), + '343y' => array(self::NUMERIC, 6, 6, false), + '344y' => array(self::NUMERIC, 6, 6, false), + '345y' => array(self::NUMERIC, 6, 6, false), + '346y' => array(self::NUMERIC, 6, 6, false), + '347y' => array(self::NUMERIC, 6, 6, false), + '348y' => array(self::NUMERIC, 6, 6, false), + '349y' => array(self::NUMERIC, 6, 6, false), + '350y' => array(self::NUMERIC, 6, 6, false), + '351y' => array(self::NUMERIC, 6, 6, false), + '352y' => array(self::NUMERIC, 6, 6, false), + '353y' => array(self::NUMERIC, 6, 6, false), + '354y' => array(self::NUMERIC, 6, 6, false), + '355y' => array(self::NUMERIC, 6, 6, false), + '356y' => array(self::NUMERIC, 6, 6, false), + '357y' => array(self::NUMERIC, 6, 6, false), + '360y' => array(self::NUMERIC, 6, 6, false), + '361y' => array(self::NUMERIC, 6, 6, false), + '362y' => array(self::NUMERIC, 6, 6, false), + '363y' => array(self::NUMERIC, 6, 6, false), + '364y' => array(self::NUMERIC, 6, 6, false), + '365y' => array(self::NUMERIC, 6, 6, false), + '366y' => array(self::NUMERIC, 6, 6, false), + '367y' => array(self::NUMERIC, 6, 6, false), + '368y' => array(self::NUMERIC, 6, 6, false), + '369y' => array(self::NUMERIC, 6, 6, false), + '37' => array(self::NUMERIC, 1, 8, false), + '390y' => array(self::NUMERIC, 1, 15, false), + '391y' => array(self::NUMERIC, 4, 18, false), + '392y' => array(self::NUMERIC, 1, 15, false), + '393y' => array(self::NUMERIC, 4, 18, false), + '400' => array(self::ALPHA_NUMERIC, 1, 30, false), + '401' => array(self::ALPHA_NUMERIC, 1, 30, false), + '402' => array(self::NUMERIC, 17, 17, false), + '403' => array(self::ALPHA_NUMERIC, 1, 30, false), + '410' => array(self::NUMERIC, 13, 13, true), + '411' => array(self::NUMERIC, 13, 13, true), + '412' => array(self::NUMERIC, 13, 13, true), + '413' => array(self::NUMERIC, 13, 13, true), + '414' => array(self::NUMERIC, 13, 13, true), + '415' => array(self::NUMERIC, 13, 13, true), + '420' => array(self::ALPHA_NUMERIC, 1, 20, false), + '421' => array(self::ALPHA_NUMERIC, 4, 12, false), + '422' => array(self::NUMERIC, 3, 3, false), + '8001' => array(self::NUMERIC, 14, 14, false), + '8002' => array(self::ALPHA_NUMERIC, 1, 20, false), + '8003' => array(self::ALPHA_NUMERIC, 15, 30, false), + '8004' => array(self::ALPHA_NUMERIC, 1, 30, false), + '8005' => array(self::NUMERIC, 6, 6, false), + '8006' => array(self::NUMERIC, 18, 18, false), + '8007' => array(self::ALPHA_NUMERIC, 1, 30, false), + '8018' => array(self::NUMERIC, 18, 18, false), + '8020' => array(self::ALPHA_NUMERIC, 1, 25, false), + '8100' => array(self::NUMERIC, 6, 6, false), + '8101' => array(self::NUMERIC, 10, 10, false), + '8102' => array(self::NUMERIC, 2, 2, false), + '90' => array(self::ALPHA_NUMERIC, 1, 30, false), + '91' => array(self::ALPHA_NUMERIC, 1, 30, false), + '92' => array(self::ALPHA_NUMERIC, 1, 30, false), + '93' => array(self::ALPHA_NUMERIC, 1, 30, false), + '94' => array(self::ALPHA_NUMERIC, 1, 30, false), + '95' => array(self::ALPHA_NUMERIC, 1, 30, false), + '96' => array(self::ALPHA_NUMERIC, 1, 30, false), + '97' => array(self::ALPHA_NUMERIC, 1, 30, false), + '98' => array(self::ALPHA_NUMERIC, 1, 30, false), + '99' => array(self::ALPHA_NUMERIC, 1, 30, false) + ); + + $this->setStrictMode(true); + $this->setTilde(true); + $this->setAllowsUnknownIdentifier(false); + $this->setNoLengthLimit(false); + } + + /** + * Gets the content checksum for an identifier. + * Do not pass the identifier code. + * + * @param string $content + * @return int + */ + public static function getAiContentChecksum($content) { + return self::calculateChecksumMod10($content); + } + + /** + * Enables or disables the strict mode. + * + * @param bool $strictMode + */ + public function setStrictMode($strictMode) { + $this->strictMode = $strictMode; + } + + /** + * Gets if the strict mode is activated. + * + * @return bool + */ + public function getStrictMode() { + return $this->strictMode; + } + + /** + * Allows unknown identifiers. + * + * @param bool $allow + */ + public function setAllowsUnknownIdentifier($allow) { + $this->allowsUnknownIdentifier = (bool)$allow; + } + + /** + * Gets if unkmown identifiers are allowed. + * + * @return bool + */ + public function getAllowsUnknownIdentifier() { + return $this->allowsUnknownIdentifier; + } + + /** + * Removes the limit of 48 characters. + * + * @param bool $noLengthLimit + */ + public function setNoLengthLimit($noLengthLimit) { + $this->noLengthLimit = (bool)$noLengthLimit; + } + + /** + * Gets if the limit of 48 characters is removed. + * + * @return bool + */ + public function getNoLengthLimit() { + return $this->noLengthLimit; + } + + /** + * Parses Text. + * + * @param string $text + */ + public function parse($text) { + parent::parse($this->parseGs1128($text)); + } + + /** + * Formats data for gs1-128. + * + * @return string + */ + private function formatGs1128() { + $formatedText = '~F1'; + $formatedLabel = ''; + $c = count($this->identifiersId); + + for ($i = 0; $i < $c; $i++) { + if ($i > 0) { + $formatedLabel .= ' '; + } + + if ($this->identifiersId[$i] !== null) { + $formatedLabel .= '(' . $this->identifiersId[$i] . ')'; + } + + $formatedText .= $this->identifiersId[$i]; + + $formatedLabel .= $this->identifiersContent[$i]; + $formatedText .= $this->identifiersContent[$i]; + + if (isset($this->identifiersAi[$this->identifiersId[$i]])) { + $ai_data = $this->identifiersAi[$this->identifiersId[$i]]; + } elseif (isset($this->identifiersId[$i][3])) { + $identifierWithVar = substr($this->identifiersId[$i], 0, -1) . 'y'; + $ai_data = isset($this->identifiersAi[$identifierWithVar]) ? $this->identifiersAi[$identifierWithVar] : null; + } else { + $ai_data = null; + } + + /* We'll check if we need to add a ~F1 () char */ + /* If we use the legacy mode, we always add a ~F1 () char between AIs */ + if ($ai_data !== null) { + if ((strlen($this->identifiersContent[$i]) < $ai_data[self::MAXLENGTH] && ($i + 1) !== $c) || (!$this->strictMode && ($i + 1) !== $c)) { + $formatedText .= '~F1'; + } + } elseif ($this->allowsUnknownIdentifier && $this->identifiersId[$i] === null && ($i + 1) !== $c) { + /* If this id is unknown, we add a ~F1 () char */ + $formatedText .= '~F1'; + } + } + + if ($this->noLengthLimit === false && (strlen(str_replace('~F1', chr(29), $formatedText)) - 1) > self::MAX_GS1128_CHARS) { + throw new BCGParseException('gs1128', 'The barcode can\'t contain more than ' . self::MAX_GS1128_CHARS . ' characters.'); + } + + $this->label = $formatedLabel; + return $formatedText; + } + + /** + * Parses the text to gs1-128. + * + * @param mixed $text + * @return mixed + */ + private function parseGs1128($text) { + /* We format correctly what the user gives */ + if (is_array($text)) { + $formatArray = array(); + foreach ($text as $content) { + if (is_array($content)) { /* double array */ + if (count($content) === 2) { + if (is_array($content[self::ID]) || is_array($content[self::CONTENT])) { + throw new BCGParseException('gs1128', 'Double arrays can\'t contain arrays.'); + } else { + $formatArray[] = '(' . $content[self::ID] . ')' . $content[self::CONTENT]; + } + } else { + throw new BCGParseException('gs1128', 'Double arrays must contain 2 values.'); + } + } else { /* simple array */ + $formatArray[] = $content; + } + } + + unset($text); + $text = $formatArray; + } else { /* string */ + $text = array($text); + } + + $textCount = count($text); + for ($cmpt = 0; $cmpt < $textCount; $cmpt++) { + /* We parse the content of the array */ + if (!$this->parseContent($text[$cmpt])) { + return; + } + } + + return $this->formatGs1128(); + } + + /** + * Splits the id and the content for each application identifiers (AIs). + * + * @param string $text + * @param int $cmpt + * @return bool + */ + private function parseContent($text) { + /* $yAlreadySet has 3 states: */ + /* null: There is no variable in the ID; true: the variable is already set; false: the variable is not set yet; */ + $content = null; + $yAlreadySet = null; + $realNameId = null; + $separatorsFound = 0; + $checksumAdded = 0; + $decimalPointRemoved = 0; + $toParse = str_replace('~F1', chr(29), $text); + $nbCharToParse = strlen($toParse); + $nbCharId = 0; + $isFormated = $toParse[0] === '(' ? true : false; + $maxCharId = $isFormated ? self::MAX_ID_FORMATED : self::MAX_ID_NOT_FORMATED; + $id = strtolower(substr($toParse, 0, min($maxCharId, $nbCharToParse))); + $id = $isFormated ? $this->findIdFormated($id, $yAlreadySet, $realNameId) : $this->findIdNotFormated($id, $yAlreadySet, $realNameId); + + if ($id === false) { + if ($this->allowsUnknownIdentifier === false) { + return false; + } + + $id = null; + $nbCharId = 0; + $content = $toParse; + } else { + $nbCharId = strlen($id) + ($isFormated ? 2 : 0); + $n = min($this->identifiersAi[$realNameId][self::MAXLENGTH], $nbCharToParse); + $content = substr($toParse, $nbCharId, $n); + } + + if ($id !== null) { + /* If we have an AI with an "y" var, we check if there is a decimal point in the next *MAXLENGTH* characters */ + /* if there is one, we take an extra character */ + if ($yAlreadySet !== null) { + if (strpos($content, '.') !== false || strpos($content, ',') !== false) { + $n++; + if ($n <= $nbCharToParse) { + /* We take an extra char */ + $content = substr($toParse, $nbCharId, $n); + } + } + } + } + + /* We check for separator */ + $separator = strpos($content, chr(29)); + if ($separator !== false) { + $content = substr($content, 0, $separator); + $separatorsFound++; + } + + if ($id !== null) { + /* We check the conformity */ + if (!$this->checkConformity($content, $id, $realNameId)) { + return false; + } + + /* We check the checksum */ + if (!$this->checkChecksum($content, $id, $realNameId, $checksumAdded)) { + return false; + } + + /* We check the vars */ + if (!$this->checkVars($content, $id, $yAlreadySet, $decimalPointRemoved)) { + return false; + } + } + + $this->identifiersId[] = $id; + $this->identifiersContent[] = $content; + + $nbCharLastContent = (((strlen($content) + $nbCharId) - $checksumAdded) + $decimalPointRemoved) + $separatorsFound; + if ($nbCharToParse - $nbCharLastContent > 0) { + /* If there is more than one content in this array, we parse again */ + $otherContent = substr($toParse, $nbCharLastContent, $nbCharToParse); + $nbCharOtherContent = strlen($otherContent); + + if ($otherContent[0] === chr(29)) { + $otherContent = substr($otherContent, 1); + $nbCharOtherContent--; + } + + if ($nbCharOtherContent > 0) { + $text = $otherContent; + return $this->parseContent($text); + } + } + + return true; + } + + /** + * Checks if an id exists. + * + * @param string $id + * @param bool $yAlreadySet + * @param string $realNameId + * @return bool + */ + private function idExists($id, &$yAlreadySet, &$realNameId) { + $yFound = isset($id[3]) && $id[3] === 'y'; + $idVarAdded = substr($id, 0, -1) . 'y'; + + if (isset($this->identifiersAi[$id])) { + if ($yFound) { + $yAlreadySet = false; + } + + $realNameId = $id; + return true; + } elseif (!$yFound && isset($this->identifiersAi[$idVarAdded])) { + /* if the id don't exist, we try to find this id with "y" at the last char */ + $yAlreadySet = true; + $realNameId = $idVarAdded; + return true; + } + + return false; + } + + /** + * Finds ID with formated content. + * + * @param string $id + * @param bool $yAlreadySet + * @param string $realNameId + * @return mixed + */ + private function findIdFormated($id, &$yAlreadySet, &$realNameId) { + $pos = strpos($id, ')'); + if ($pos === false) { + throw new BCGParseException('gs1128', 'Identifiers must have no more than 4 characters.'); + } else { + if ($pos < 3) { + throw new BCGParseException('gs1128', 'Identifiers must have at least 2 characters.'); + } + + $id = substr($id, 1, $pos - 1); + if ($this->idExists($id, $yAlreadySet, $realNameId)) { + return $id; + } + + if ($this->allowsUnknownIdentifier === false) { + throw new BCGParseException('gs1128', 'The identifier ' . $id . ' doesn\'t exist.'); + } + + return false; + } + } + + /** + * Finds ID with non-formated content. + * + * @param string $id + * @param bool $yAlreadySet + * @param string $realNameId + * @return mixed + */ + private function findIdNotFormated($id, &$yAlreadySet, &$realNameId) { + $tofind = $id; + + while (strlen($tofind) >= 2) { + if ($this->idExists($tofind, $yAlreadySet, $realNameId)) { + return $tofind; + } else { + $tofind = substr($tofind, 0, -1); + } + } + + if ($this->allowsUnknownIdentifier === false) { + throw new BCGParseException('gs1128', 'Error in formatting, can\'t find an identifier.'); + } + + return false; + } + + /** + * Checks confirmity of the content. + * + * @param string $content + * @param string $id + * @param string $realNameId + * @return bool + */ + private function checkConformity(&$content, $id, $realNameId) { + switch ($this->identifiersAi[$realNameId][self::KIND_OF_DATA]) { + case self::NUMERIC: + $content = str_replace(',', '.', $content); + if (!preg_match("/^[0-9.]+$/", $content)) { + throw new BCGParseException('gs1128', 'The value of "' . $id . '" must be numerical.'); + } + + break; + case self::DATE_YYMMDD: + $valid_date = true; + if (preg_match("/^[0-9]{6}$/", $content)) { + $year = substr($content, 0, 2); + $month = substr($content, 2, 2); + $day = substr($content, 4, 2); + + /* day can be 00 if we only need month and year */ + if (intval($month) < 1 || intval($month) > 12 || intval($day) < 0 || intval($day) > 31) { + $valid_date = false; + } + } else { + $valid_date = false; + } + + if (!$valid_date) { + throw new BCGParseException('gs1128', 'The value of "' . $id . '" must be in YYMMDD format.'); + } + + break; + } + + // We check the length of the content + $nbCharContent = strlen($content); + $checksumChar = 0; + $minlengthContent = $this->identifiersAi[$realNameId][self::MINLENGTH]; + $maxlengthContent = $this->identifiersAi[$realNameId][self::MAXLENGTH]; + + if ($this->identifiersAi[$realNameId][self::CHECKSUM]) { + $checksumChar++; + } + + if ($nbCharContent < ($minlengthContent - $checksumChar)) { + if ($minlengthContent === $maxlengthContent) { + throw new BCGParseException('gs1128', 'The value of "' . $id . '" must contain ' . $minlengthContent . ' character(s).'); + } else { + throw new BCGParseException('gs1128', 'The value of "' . $id . '" must contain between ' . $minlengthContent . ' and ' . $maxlengthContent . ' character(s).'); + } + } + + return true; + } + + /** + * Verifies the checksum. + * + * @param string $content + * @param string $id + * @param int $realNameId + * @param int $checksumAdded + * @return bool + */ + private function checkChecksum(&$content, $id, $realNameId, &$checksumAdded) { + if ($this->identifiersAi[$realNameId][self::CHECKSUM]) { + $nbCharContent = strlen($content); + $minlengthContent = $this->identifiersAi[$realNameId][self::MINLENGTH]; + if ($nbCharContent === ($minlengthContent - 1)) { + /* we need to calculate the checksum */ + $content .= self::getAiContentChecksum($content); + $checksumAdded++; + } elseif ($nbCharContent === $minlengthContent) { + /* we need to check the checksum */ + $checksum = self::getAiContentChecksum(substr($content, 0, -1)); + if (intval($content[$nbCharContent - 1]) !== $checksum) { + throw new BCGParseException('gs1128', 'The checksum of "(' . $id . ') ' . $content . '" must be: ' . $checksum); + } + } + } + + return true; + } + + /** + * Checks vars "y". + * + * @param string $content + * @param string $id + * @param bool $yAlreadySet + * @param int $decimalPointRemoved + * @return bool + */ + private function checkVars(&$content, &$id, $yAlreadySet, &$decimalPointRemoved) { + $nbCharContent = strlen($content); + /* We check for "y" var in AI */ + if ($yAlreadySet) { + /* We'll check if we have a decimal point */ + if (strpos($content, '.') !== false) { + throw new BCGParseException('gs1128', 'If you do not use any "y" variable, you have to insert a whole number.'); + } + } elseif ($yAlreadySet !== null) { + /* We need to replace the "y" var with the position of the decimal point */ + $pos = strpos($content, '.'); + if ($pos === false) { + $pos = $nbCharContent - 1; + } + + $id = str_replace('y', $nbCharContent - ($pos + 1), strtolower($id)); + $content = str_replace('.', '', $content); + $decimalPointRemoved++; + } + + return true; + } + + /** + * Checksum Mod10. + * + * @param int $content + * @return int + */ + private static function calculateChecksumMod10($content) { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $odd = true; + $checksumValue = 0; + $c = strlen($content); + + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 1; + $odd = true; + } + + $checksumValue += ($content[$i - 1] * $multiplier); + } + + return (10 - $checksumValue % 10) % 10; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGi25.barcode.php b/niucloud/core/core/util/barcode/class/BCGi25.barcode.php new file mode 100644 index 00000000..d4ee00c6 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGi25.barcode.php @@ -0,0 +1,203 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '00110', /* 0 */ + '10001', /* 1 */ + '01001', /* 2 */ + '11000', /* 3 */ + '00101', /* 4 */ + '10100', /* 5 */ + '01100', /* 6 */ + '00011', /* 7 */ + '10010', /* 8 */ + '01010' /* 9 */ + ); + + $this->setChecksum(false); + $this->setRatio(2); + } + + /** + * Sets the checksum. + * + * @param bool $checksum + */ + public function setChecksum($checksum) { + $this->checksum = (bool)$checksum; + } + + /** + * Sets the ratio of the black bar compared to the white bars. + * + * @param int $ratio + */ + public function setRatio($ratio) { + $this->ratio = $ratio; + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $temp_text = $this->text; + + // Checksum + if ($this->checksum === true) { + $this->calculateChecksum(); + $temp_text .= $this->keys[$this->checksumValue]; + } + + // Starting Code + $this->drawChar($im, '0000', true); + + // Chars + $c = strlen($temp_text); + for ($i = 0; $i < $c; $i += 2) { + $temp_bar = ''; + $c2 = strlen($this->findCode($temp_text[$i])); + for ($j = 0; $j < $c2; $j++) { + $temp_bar .= substr($this->findCode($temp_text[$i]), $j, 1); + $temp_bar .= substr($this->findCode($temp_text[$i + 1]), $j, 1); + } + + $this->drawChar($im, $this->changeBars($temp_bar), true); + } + + // Ending Code + $this->drawChar($im, $this->changeBars('100'), true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textlength = (3 + ($this->ratio + 1) * 2) * strlen($this->text); + $startlength = 4; + $checksumlength = 0; + if ($this->checksum === true) { + $checksumlength = (3 + ($this->ratio + 1) * 2); + } + + $endlength = 2 + ($this->ratio + 1); + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('i25', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('i25', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must be even + if ($c % 2 !== 0 && $this->checksum === false) { + throw new BCGParseException('i25', 'i25 must contain an even amount of digits if checksum is false.'); + } elseif ($c % 2 === 0 && $this->checksum === true) { + throw new BCGParseException('i25', 'i25 must contain an odd amount of digits if checksum is true.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "even" position, + // and assign odd/even to each character moving from right to left + // Even Position = 3, Odd Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $even = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($even === true) { + $multiplier = 3; + $even = false; + } else { + $multiplier = 1; + $even = true; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Changes the size of the bars based on the ratio + * + * @param string $in + * @return string + */ + private function changeBars($in) { + if ($this->ratio > 1) { + $c = strlen($in); + for ($i = 0; $i < $c; $i++) { + $in[$i] = $in[$i] === '1' ? $this->ratio : $in[$i]; + } + } + + return $in; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGintelligentmail.barcode.php b/niucloud/core/core/util/barcode/class/BCGintelligentmail.barcode.php new file mode 100644 index 00000000..cb2a5f3c --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGintelligentmail.barcode.php @@ -0,0 +1,649 @@ +setQuietZone(true); + $this->setThickness(9); + } + + /** + * Gets the Quiet zone. + * + * @return bool + */ + public function getQuietZone() { + return $this->quietZone; + } + + /** + * Sets the Quiet zone. + * + * @param bool $quietZone + */ + public function setQuietZone($quietZone) { + $this->quietZone = (bool)$quietZone; + } + + /** + * Sets the tracking code. + * + * @param int $barcodeIdentifier 2-digit number. 2nd digit must be 0-4 + * @param int $serviceTypeIdentifier 3 digits + * @param int $mailerIdentifier 6 or 9 digits + * @param int $serialNumber 9 (if mailerId is 6) or 6 digits (if mailerId is 9) + */ + public function setTrackingCode($barcodeIdentifier, $serviceTypeIdentifier, $mailerIdentifier, $serialNumber) { + $barcodeIdentifier = (string)(int)$barcodeIdentifier; + $serviceTypeIdentifier = (int)$serviceTypeIdentifier; + $mailerIdentifier = (int)$mailerIdentifier; + $serialNumber = (string)(int)$serialNumber; + + $barcodeIdentifier = str_pad($barcodeIdentifier, 2, '0', STR_PAD_LEFT); + + if (strlen($barcodeIdentifier) !== 2) { + throw new BCGArgumentException('Barcode Identifier must contain 2 digits.', 'barcodeIdentifier'); + } + + $barcodeIdentifierSecondNumber = $barcodeIdentifier[1]; + if ($barcodeIdentifierSecondNumber !== '0' && $barcodeIdentifierSecondNumber !== '1' && $barcodeIdentifierSecondNumber !== '2' && $barcodeIdentifierSecondNumber !== '3' && $barcodeIdentifierSecondNumber !== '4') { + throw new BCGArgumentException('Barcode Identifier second digit must be a number between 0 and 4.', 'barcodeIdentifier'); + } + + if ($serviceTypeIdentifier < 0 || $serviceTypeIdentifier > 999) { + throw new BCGArgumentException('Service Type Identifier must be between 0 and 999.', 'serviceTypeIdentifier'); + } + + $mailerIdentifierLength = 6; + if ($mailerIdentifier > 899999) { + $mailerIdentifierLength = 9; + } + + if ($mailerIdentifierLength === 9 && strlen($serialNumber) > 6) { + throw new BCGArgumentException('If the Serial Number has more than 6 digits, the Mailer Identifier must be lower than 900000.', 'mailerIdentifier'); + } + + if ($mailerIdentifierLength === 9) { + if ($mailerIdentifierLength < 0 || $mailerIdentifier > 999999999) { + throw new BCGArgumentException('Mailer Identifier must be between 0 and 999999999.', 'mailerIdentifier'); + } + } + + $this->barcodeIdentifier = $barcodeIdentifier; + $this->serviceTypeIdentifier = str_pad($serviceTypeIdentifier, 3, '0', STR_PAD_LEFT); + $this->mailerIdentifier = str_pad($mailerIdentifier, $mailerIdentifierLength, '0', STR_PAD_LEFT); + $this->serialNumber = str_pad((int)$serialNumber, $mailerIdentifierLength === 6 ? 9 : 6, '0', STR_PAD_LEFT); + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + parent::parse($text); + + $number = self::executeStep1($this->text, $this->barcodeIdentifier, $this->serviceTypeIdentifier, $this->mailerIdentifier, $this->serialNumber); + $crc = self::executeStep2($number); + $codewords = self::executeStep3($number); + $codewords = self::executeStep4($codewords, $crc); + $characters = self::executeStep5($codewords, $crc); + $this->data = self::executeStep6($characters); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + if ($this->quietZone) { + $this->positionX += 9; + } + + $c = strlen($this->data); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->data[$i]); + } + + $this->drawText($im, 0, 0, $this->positionX, $this->thickness + ($this->quietZone ? 4 : 0)); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $w += 65 * 3; + $h += $this->thickness; + + // We remove the white on the right + $w -= 1.56; + + if ($this->quietZone) { + $w += 18; + $h += 4; + } + + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + // Tracking must have been entered + if ($this->barcodeIdentifier === null || $this->serviceTypeIdentifier === null || $this->mailerIdentifier === null || $this->serialNumber === null) { + throw new BCGParseException('intelligentmail', 'The tracking code must be set before calling the parse method.'); + } + + // Checking if all chars are allowed + $match = array(); + if (preg_match('/[^0-9]/', $this->text, $match)) { + throw new BCGParseException('intelligentmail', 'The character \'' . $match[0] . '\' is not allowed.'); + } + + // Must contain 0, 5, 9 or 11 chars + $c = strlen($this->text); + if ($c !== 0 && $c !== 5 && $c !== 9 && $c !== 11) { + throw new BCGParseException('intelligentmail', 'Must contain 0, 5, 9, or 11 characters.'); + } + + parent::validate(); + } + + /** + * Overloaded method for drawing special barcode. + * + * @param resource $im + * @param string $code + * @param boolean $startBar + */ + protected function drawChar($im, $code, $startBar = true) { + $y1 = 0; + $y2 = 0; + switch ($code) { + case 'A': + $y1 = 0; + $y2 = $this->thickness - ($this->thickness / 2.5); + break; + case 'D': + $y1 = 3.096; + $y2 = $this->thickness - 1; + break; + case 'F': + $y1 = 0; + $y2 = $this->thickness - 1; + break; + case 'T': + $y1 = 3.096; + $y2 = $this->thickness - ($this->thickness / 2.5); + break; + } + + if ($this->quietZone) { + $y1 += 2; + $y2 += 2; + } + + $this->drawFilledRectangle($im, $this->positionX, $y1, $this->positionX + 0.44, $y2, BCGBarcode::COLOR_FG); + $this->positionX += 3; + } + + /** + * Executes Step 1: Conversion of Data Fields into Binary Data + * + * @param string $text + * @param string $barcodeIdentifier + * @param string $serviceTypeIdentifier + * @param string $mailerIdentifier + * @param string $serialNumber + * @return string BCNumber + */ + private static function executeStep1($text, $barcodeIdentifier, $serviceTypeIdentifier, $mailerIdentifier, $serialNumber) { + $number = self::conversionRoutingCode($text); + $number = self::conversionTrackingCode($number, $barcodeIdentifier, $serviceTypeIdentifier, $mailerIdentifier, $serialNumber); + + return $number; + } + + /** + * Executes Step 2: Generation of 11-Bit CRC on Binary Data + * + * @param $number BCNumber + * @return int + */ + private static function executeStep2($number) { + $byteArray = str_pad(self::bcdecuc($number), 13, chr(0), STR_PAD_LEFT); + + $generatorPolynomial = 0x0f35; + $frameCheckSequence = 0x07ff; + $data = 0; + $byteIndex = 0; + $bit = 0; + + $data = (ord($byteArray[$byteIndex]) << 5) & 0xffff; + for ($bit = 2; $bit < 8; $bit++) { + if (($frameCheckSequence ^ $data) & 0x400) { + $frameCheckSequence = ($frameCheckSequence << 1) ^ $generatorPolynomial; + } else { + $frameCheckSequence = ($frameCheckSequence << 1); + } + + $frameCheckSequence &= 0x7ff; + $data <<= 1; + $data &= 0xffff; + } + + for ($byteIndex = 1; $byteIndex < 13; $byteIndex++) { + $data = (ord($byteArray[$byteIndex]) << 3) & 0xffff; + for ($bit = 0; $bit < 8; $bit++) { + if (($frameCheckSequence ^ $data) & 0x0400) { + $frameCheckSequence = ($frameCheckSequence << 1) ^ $generatorPolynomial; + } else { + $frameCheckSequence = ($frameCheckSequence << 1); + } + + $frameCheckSequence &= 0x7ff; + $data <<= 1; + $data &= 0xffff; + } + } + + return $frameCheckSequence; + } + + /** + * Executes Step 3: Conversion from Binary Data to Codewords + * + * @param string $number BCNumber + * @return int[] + */ + private static function executeStep3($number) { + $codewords = array(); + $codewords[9] = (int)bcmod($number, '636'); + $number = bcdiv($number, '636', 0); + + for ($i = 8; $i >= 0; $i--) { + $codewords[$i] = (int)bcmod($number, '1365'); + $number = bcdiv($number, '1365', 0); + } + + return $codewords; + } + + /** + * Executes Step 4: Inserting Additional Information into Codewords + * + * @param int[] $codewords + * @param int $crc + * @return int[] + */ + private static function executeStep4($codewords, $crc) { + $codewords[9] *= 2; + if ($crc & 0x400) { + $codewords[0] += 659; + } + + return $codewords; + } + + /** + * Executes Step 5: Conversion from Codewords to Characters + * + * @param int[] $codewords + * @param int $crc + * @return int[] + */ + private static function executeStep5($codewords, $crc) { + $characters = array(); + for ($i = 0; $i < 10; $i++) { + if ($codewords[$i] <= 1286) { + $characters[$i] = self::$characterTable1[$codewords[$i]]; + } else { + $characters[$i] = self::$characterTable2[$codewords[$i] - 1287]; + } + } + + for ($i = 0; $i < 10; $i++) { + $mask = 1 << $i; + if ($crc & $mask) { + $characters[$i] ^= 0x1fff; + } + } + + return $characters; + } + + /** + * Executes Step 6: Conversion from Characters to the Intelligent Mail Barcode + * + * @param int[] $characters + * @return string + */ + private static function executeStep6($characters) { + $bars = ''; + for ($i = 0; $i < 65; $i++) { + $barPosition = self::$barPositions[$i]; + $descender = $barPosition[0]; + $ascender = $barPosition[1]; + $extenderDescender = !!($characters[$descender[0]] & (1 << $descender[1])); + $extenderAscender = !!($characters[$ascender[0]] & (1 << $ascender[1])); + + if ($extenderDescender && $extenderAscender) { + $bars .= 'F'; + } elseif ($extenderDescender) { + $bars .= 'D'; + } elseif ($extenderAscender) { + $bars .= 'A'; + } else { + $bars .= 'T'; + } + } + + return $bars; + } + + /** + * Converts the routing code zipcode. + * + * @param string $zipcode + * @return string BCNumber + */ + private static function conversionRoutingCode($zipcode) { + $number = $zipcode; + switch (strlen($zipcode)) { + case 11: + $number = bcadd($number, '1000000000', 0); + case 9: + $number = bcadd($number, '100000', 0); + case 5: + $number = bcadd($number, '1', 0); + default: + return $number; + } + } + + /** + * Converts the tracking code number. + * + * @param string $number BCNumber + * @param string $barcodeIdentifier + * @param string $serviceTypeIdentifier + * @param string $mailerIdentifier + * @param string $serialNumber + * @return string BCNumber + */ + private static function conversionTrackingCode($number, $barcodeIdentifier, $serviceTypeIdentifier, $mailerIdentifier, $serialNumber) { + $number = bcmul($number, 10, 0); + $number = bcadd($number, $barcodeIdentifier[0], 0); + $number = bcmul($number, 5, 0); + $number = bcadd($number, $barcodeIdentifier[1], 0); + + $temp = $serviceTypeIdentifier . $mailerIdentifier . $serialNumber; + for ($i = 0; $i < 18; $i++) { + $number = bcmul($number, 10, 0); + $number = bcadd($number, $temp[$i], 0); + } + + return $number; + } + + /** + * Transforms a BCNumber into unsigned char*. + * + * @param string $dec BCNumber + * @param string + */ + private static function bcdecuc($dec) { + $last = bcmod($dec, 256); + $remain = bcdiv(bcsub($dec, $last), 256, 0); + + if ($remain == 0) { + return pack('C', $last); + } else { + return self::bcdecuc($remain) . pack('C', $last); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGisbn.barcode.php b/niucloud/core/core/util/barcode/class/BCGisbn.barcode.php new file mode 100644 index 00000000..867cb0f7 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGisbn.barcode.php @@ -0,0 +1,164 @@ +setGS1($gs1); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $isbn = $this->createISBNText(); + $font = $this->font; + + $topLabel = new BCGLabel($isbn, $font, BCGLabel::POSITION_TOP, BCGLabel::ALIGN_CENTER); + + $this->addLabel($topLabel); + } + + parent::addDefaultLabel(); + } + + /** + * Sets the first numbers of the barcode. + * - GS1_AUTO: Adds 978 before the code + * - GS1_PREFIX978: Adds 978 before the code + * - GS1_PREFIX979: Adds 979 before the code + * + * @param int $gs1 + */ + public function setGS1($gs1) { + $gs1 = (int)$gs1; + if ($gs1 !== self::GS1_AUTO && $gs1 !== self::GS1_PREFIX978 && $gs1 !== self::GS1_PREFIX979) { + throw new BCGArgumentException('The GS1 argument must be BCGisbn::GS1_AUTO, BCGisbn::GS1_PREFIX978, or BCGisbn::GS1_PREFIX979', 'gs1'); + } + + $this->gs1 = $gs1; + } + + /** + * Check chars allowed. + */ + protected function checkCharsAllowed() { + $c = strlen($this->text); + + // Special case, if we have 10 digits, the last one can be X + if ($c === 10) { + if (array_search($this->text[9], $this->keys) === false && $this->text[9] !== 'X') { + throw new BCGParseException('isbn', 'The character \'' . $this->text[9] . '\' is not allowed.'); + } + + // Drop the last char + $this->text = substr($this->text, 0, 9); + } + + return parent::checkCharsAllowed(); + } + + /** + * Check correct length. + */ + protected function checkCorrectLength() { + $c = strlen($this->text); + + // If we have 13 chars just flush the last one + if ($c === 13) { + $this->text = substr($this->text, 0, 12); + } elseif ($c === 9 || $c === 10) { + if ($c === 10) { + // Before dropping it, we check if it's legal + if (array_search($this->text[9], $this->keys) === false && $this->text[9] !== 'X') { + throw new BCGParseException('isbn', 'The character \'' . $this->text[9] . '\' is not allowed.'); + } + + $this->text = substr($this->text, 0, 9); + } + + if ($this->gs1 === self::GS1_AUTO || $this->gs1 === self::GS1_PREFIX978) { + $this->text = '978' . $this->text; + } elseif ($this->gs1 === self::GS1_PREFIX979) { + $this->text = '979' . $this->text; + } + } elseif ($c !== 12) { + throw new BCGParseException('isbn', 'The code parsed must be 9, 10, 12, or 13 digits long.'); + } + } + + /** + * Creates the ISBN text. + * + * @return string + */ + private function createISBNText() { + $isbn = ''; + if (!empty($this->text)) { + // We try to create the ISBN Text... the hyphen really depends the ISBN agency. + // We just put one before the checksum and one after the GS1 if present. + $c = strlen($this->text); + if ($c === 12 || $c === 13) { + // If we have 13 characters now, just transform it temporarily to find the checksum... + // Further in the code we take care of that anyway. + $lastCharacter = ''; + if ($c === 13) { + $lastCharacter = $this->text[12]; + $this->text = substr($this->text, 0, 12); + } + + $checksum = $this->processChecksum(); + $isbn = 'ISBN ' . substr($this->text, 0, 3) . '-' . substr($this->text, 3, 9) . '-' . $checksum; + + // Put the last character back + if ($c === 13) { + $this->text .= $lastCharacter; + } + } elseif ($c === 9 || $c === 10) { + $checksum = 0; + for ($i = 10; $i >= 2; $i--) { + $checksum += $this->text[10 - $i] * $i; + } + + $checksum = 11 - $checksum % 11; + if ($checksum === 10) { + $checksum = 'X'; // Changing type + } + + $isbn = 'ISBN ' . substr($this->text, 0, 9) . '-' . $checksum; + } + } + + return $isbn; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGmsi.barcode.php b/niucloud/core/core/util/barcode/class/BCGmsi.barcode.php new file mode 100644 index 00000000..a322d829 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGmsi.barcode.php @@ -0,0 +1,184 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '01010101', /* 0 */ + '01010110', /* 1 */ + '01011001', /* 2 */ + '01011010', /* 3 */ + '01100101', /* 4 */ + '01100110', /* 5 */ + '01101001', /* 6 */ + '01101010', /* 7 */ + '10010101', /* 8 */ + '10010110' /* 9 */ + ); + + $this->setChecksum(0); + } + + /** + * Sets how many checksums we display. 0 to 2. + * + * @param int $checksum + */ + public function setChecksum($checksum) { + $checksum = intval($checksum); + if ($checksum < 0 && $checksum > 2) { + throw new BCGArgumentException('The checksum must be between 0 and 2 included.', 'checksum'); + } + + $this->checksum = $checksum; + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Checksum + $this->calculateChecksum(); + + // Starting Code + $this->drawChar($im, '10', true); + + // Chars + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i]), true); + } + + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->checksumValue[$i]), true); + } + + // Ending Code + $this->drawChar($im, '010', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textlength = 12 * strlen($this->text); + $startlength = 3; + $checksumlength = $this->checksum * 12; + $endlength = 4; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('msi', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('msi', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Forming a new number + // If the original number is even, we take all even position + // If the original number is odd, we take all odd position + // 123456 = 246 + // 12345 = 135 + // Multiply by 2 + // Add up all the digit in the result (270 : 2+7+0) + // Add up other digit not used. + // 10 - (? Modulo 10). If result = 10, change to 0 + $last_text = $this->text; + $this->checksumValue = array(); + for ($i = 0; $i < $this->checksum; $i++) { + $new_text = ''; + $new_number = 0; + $c = strlen($last_text); + if ($c % 2 === 0) { // Even + $starting = 1; + } else { + $starting = 0; + } + + for ($j = $starting; $j < $c; $j += 2) { + $new_text .= $last_text[$j]; + } + + $new_text = strval(intval($new_text) * 2); + $c2 = strlen($new_text); + for ($j = 0; $j < $c2; $j++) { + $new_number += intval($new_text[$j]); + } + + for ($j = ($starting === 0) ? 1 : 0; $j < $c; $j += 2) { + $new_number += intval($last_text[$j]); + } + + $new_number = (10 - $new_number % 10) % 10; + $this->checksumValue[] = $new_number; + $last_text .= $new_number; + } + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + $ret = ''; + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $ret .= $this->keys[$this->checksumValue[$i]]; + } + + return $ret; + } + + return false; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGothercode.barcode.php b/niucloud/core/core/util/barcode/class/BCGothercode.barcode.php new file mode 100644 index 00000000..a9ae2eda --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGothercode.barcode.php @@ -0,0 +1,88 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $this->drawChar($im, $this->text, true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Gets the label. + * If the label was set to BCGBarcode1D::AUTO_LABEL, the label will display the value from the text parsed. + * + * @return string + */ + public function getLabel() { + $label = $this->label; + if ($this->label === BCGBarcode1D::AUTO_LABEL) { + $label = ''; + } + + return $label; + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $array = str_split($this->text, 1); + $textlength = array_sum($array) + count($array); + + $w += $textlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('othercode', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('othercode', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + parent::validate(); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGpostnet.barcode.php b/niucloud/core/core/util/barcode/class/BCGpostnet.barcode.php new file mode 100644 index 00000000..1988b084 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGpostnet.barcode.php @@ -0,0 +1,138 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '11000', /* 0 */ + '00011', /* 1 */ + '00101', /* 2 */ + '00110', /* 3 */ + '01001', /* 4 */ + '01010', /* 5 */ + '01100', /* 6 */ + '10001', /* 7 */ + '10010', /* 8 */ + '10100' /* 9 */ + ); + + $this->setThickness(9); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Checksum + $checksum = 0; + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $checksum += intval($this->text[$i]); + } + + $checksum = 10 - ($checksum % 10); + + // Starting Code + $this->drawChar($im, '1'); + + // Code + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i])); + } + + // Checksum + $this->drawChar($im, $this->findCode($checksum)); + + // Ending Code + $this->drawChar($im, '1'); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $c = strlen($this->text); + $startlength = 3; + $textlength = $c * 5 * 3; + $checksumlength = 5 * 3; + $endlength = 3; + + // We remove the white on the right + $removelength = -1.56; + + $w += $startlength + $textlength + $checksumlength + $endlength + $removelength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('postnet', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('postnet', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must contain 5, 9 or 11 chars + if ($c !== 5 && $c !== 9 && $c !== 11) { + throw new BCGParseException('postnet', 'Must contain 5, 9, or 11 characters.'); + } + + parent::validate(); + } + + /** + * Overloaded method for drawing special barcode. + * + * @param resource $im + * @param string $code + * @param boolean $startBar + */ + protected function drawChar($im, $code, $startBar = true) { + $c = strlen($code); + for ($i = 0; $i < $c; $i++) { + if ($code[$i] === '0') { + $posY = $this->thickness - ($this->thickness / 2.5); + } else { + $posY = 0; + } + + $this->drawFilledRectangle($im, $this->positionX, $posY, $this->positionX + 0.44, $this->thickness - 1, BCGBarcode::COLOR_FG); + $this->positionX += 3; + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGs25.barcode.php b/niucloud/core/core/util/barcode/class/BCGs25.barcode.php new file mode 100644 index 00000000..3312b2cd --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGs25.barcode.php @@ -0,0 +1,170 @@ + 1/3 or 1/2 for the big bar + * + *-------------------------------------------------------------------- + * Copyright (C) Jean-Sebastien Goupil + * http://www.barcodephp.com + */ +include_once('BCGParseException.php'); +include_once('BCGBarcode1D.php'); + +class BCGs25 extends BCGBarcode1D { + private $checksum; + + /** + * Constructor. + */ + public function __construct() { + parent::__construct(); + + $this->keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '0000202000', /* 0 */ + '2000000020', /* 1 */ + '0020000020', /* 2 */ + '2020000000', /* 3 */ + '0000200020', /* 4 */ + '2000200000', /* 5 */ + '0020200000', /* 6 */ + '0000002020', /* 7 */ + '2000002000', /* 8 */ + '0020002000' /* 9 */ + ); + + $this->setChecksum(false); + } + + /** + * Sets if we display the checksum. + * + * @param bool $checksum + */ + public function setChecksum($checksum) { + $this->checksum = (bool)$checksum; + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $temp_text = $this->text; + + // Checksum + if ($this->checksum === true) { + $this->calculateChecksum(); + $temp_text .= $this->keys[$this->checksumValue]; + } + + // Starting Code + $this->drawChar($im, '101000', true); + + // Chars + $c = strlen($temp_text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($temp_text[$i]), true); + } + + // Ending Code + $this->drawChar($im, '10001', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $c = strlen($this->text); + $startlength = 8; + $textlength = $c * 14; + $checksumlength = 0; + if ($c % 2 !== 0) { + $checksumlength = 14; + } + + $endlength = 7; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('s25', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('s25', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must be even + if ($c % 2 !== 0 && $this->checksum === false) { + throw new BCGParseException('s25', 's25 must contain an even amount of digits if checksum is false.'); + } elseif ($c % 2 === 0 && $this->checksum === true) { + throw new BCGParseException('s25', 's25 must contain an odd amount of digits if checksum is true.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "even" position, + // and assign odd/even to each character moving from right to left + // Even Position = 3, Odd Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $even = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($even === true) { + $multiplier = 3; + $even = false; + } else { + $multiplier = 1; + $even = true; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGupca.barcode.php b/niucloud/core/core/util/barcode/class/BCGupca.barcode.php new file mode 100644 index 00000000..37794331 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGupca.barcode.php @@ -0,0 +1,146 @@ +text = '0' . $this->text; // We will remove it at the end... don't worry + + parent::draw($im); + + // We remove the 0 in front, as we said :) + $this->text = substr($this->text, 1); + } + + /** + * Draws the extended bars on the image. + * + * @param resource $im + * @param int $plus + */ + protected function drawExtendedBars($im, $plus) { + $temp_text = $this->text . $this->keys[$this->checksumValue]; + $rememberX = $this->positionX; + $rememberH = $this->thickness; + + // We increase the bars + // First 2 Bars + $this->thickness = $this->thickness + intval($plus / $this->scale); + $this->positionX = 0; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Attemping to increase the 2 following bars + $this->positionX += 1; + $temp_value = $this->findCode($temp_text[1]); + $this->drawChar($im, $temp_value, false); + + // Center Guard Bar + $this->positionX += 36; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Attemping to increase the 2 last bars + $this->positionX += 37; + $temp_value = $this->findCode($temp_text[12]); + $this->drawChar($im, $temp_value, true); + + // Completly last bars + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + $this->positionX = $rememberX; + $this->thickness = $rememberH; + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $this->processChecksum(); + $label = $this->getLabel(); + $font = $this->font; + + $this->labelLeft = new BCGLabel(substr($label, 0, 1), $font, BCGLabel::POSITION_LEFT, BCGLabel::ALIGN_BOTTOM); + $this->labelLeft->setSpacing(4 * $this->scale); + + $this->labelCenter1 = new BCGLabel(substr($label, 1, 5), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelCenter1Dimension = $this->labelCenter1->getDimension(); + $this->labelCenter1->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 6); + + $this->labelCenter2 = new BCGLabel(substr($label, 6, 5), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $this->labelCenter2->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 45); + + $this->labelRight = new BCGLabel($this->keys[$this->checksumValue], $font, BCGLabel::POSITION_RIGHT, BCGLabel::ALIGN_BOTTOM); + $this->labelRight->setSpacing(4 * $this->scale); + + if ($this->alignLabel) { + $labelDimension = $this->labelCenter1->getDimension(); + $this->labelLeft->setOffset($labelDimension[1]); + $this->labelRight->setOffset($labelDimension[1]); + } else { + $labelDimension = $this->labelLeft->getDimension(); + $this->labelLeft->setOffset($labelDimension[1] / 2); + $labelDimension = $this->labelLeft->getDimension(); + $this->labelRight->setOffset($labelDimension[1] / 2); + } + + $this->addLabel($this->labelLeft); + $this->addLabel($this->labelCenter1); + $this->addLabel($this->labelCenter2); + $this->addLabel($this->labelRight); + } + } + + /** + * Check correct length. + */ + protected function checkCorrectLength() { + // If we have 12 chars, just flush the last one without throwing anything + $c = strlen($this->text); + if ($c === 12) { + $this->text = substr($this->text, 0, 11); + } elseif ($c !== 11) { + throw new BCGParseException('upca', 'Must contain 11 digits, the 12th digit is automatically added.'); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGupce.barcode.php b/niucloud/core/core/util/barcode/class/BCGupce.barcode.php new file mode 100644 index 00000000..5b349289 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGupce.barcode.php @@ -0,0 +1,336 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + + // Odd Parity starting with a space + // Even Parity is the inverse (0=0012) starting with a space + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + + // Parity, 0=Odd, 1=Even for manufacturer code. Depending on 1st System Digit and Checksum + $this->codeParity = array( + array( + array(1, 1, 1, 0, 0, 0), /* 0,0 */ + array(1, 1, 0, 1, 0, 0), /* 0,1 */ + array(1, 1, 0, 0, 1, 0), /* 0,2 */ + array(1, 1, 0, 0, 0, 1), /* 0,3 */ + array(1, 0, 1, 1, 0, 0), /* 0,4 */ + array(1, 0, 0, 1, 1, 0), /* 0,5 */ + array(1, 0, 0, 0, 1, 1), /* 0,6 */ + array(1, 0, 1, 0, 1, 0), /* 0,7 */ + array(1, 0, 1, 0, 0, 1), /* 0,8 */ + array(1, 0, 0, 1, 0, 1) /* 0,9 */ + ), + array( + array(0, 0, 0, 1, 1, 1), /* 0,0 */ + array(0, 0, 1, 0, 1, 1), /* 0,1 */ + array(0, 0, 1, 1, 0, 1), /* 0,2 */ + array(0, 0, 1, 1, 1, 0), /* 0,3 */ + array(0, 1, 0, 0, 1, 1), /* 0,4 */ + array(0, 1, 1, 0, 0, 1), /* 0,5 */ + array(0, 1, 1, 1, 0, 0), /* 0,6 */ + array(0, 1, 0, 1, 0, 1), /* 0,7 */ + array(0, 1, 0, 1, 1, 0), /* 0,8 */ + array(0, 1, 1, 0, 1, 0) /* 0,9 */ + ) + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $this->calculateChecksum(); + + // Starting Code + $this->drawChar($im, '000', true); + $c = strlen($this->upce); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, self::inverse($this->findCode($this->upce[$i]), $this->codeParity[intval($this->text[0])][$this->checksumValue][$i]), false); + } + + // Draw Center Guard Bar + $this->drawChar($im, '00000', false); + + // Draw Right Bar + $this->drawChar($im, '0', true); + $this->text = $this->text[0] . $this->upce; + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + + if ($this->isDefaultEanLabelEnabled()) { + $dimension = $this->labelCenter->getDimension(); + $this->drawExtendedBars($im, $dimension[1] - 2); + } + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 3; + $centerlength = 5; + $textlength = 6 * 7; + $endlength = 1; + + $w += $startlength + $centerlength + $textlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $this->processChecksum(); + $font = $this->font; + + $this->labelLeft = new BCGLabel(substr($this->text, 0, 1), $font, BCGLabel::POSITION_LEFT, BCGLabel::ALIGN_BOTTOM); + $labelLeftDimension = $this->labelLeft->getDimension(); + $this->labelLeft->setSpacing(8); + $this->labelLeft->setOffset($labelLeftDimension[1] / 2); + + $this->labelCenter = new BCGLabel($this->upce, $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelCenterDimension = $this->labelCenter->getDimension(); + $this->labelCenter->setOffset(($this->scale * 46 - $labelCenterDimension[0]) / 2 + $this->scale * 2); + + $this->labelRight = new BCGLabel($this->keys[$this->checksumValue], $font, BCGLabel::POSITION_RIGHT, BCGLabel::ALIGN_BOTTOM); + $labelRightDimension = $this->labelRight->getDimension(); + $this->labelRight->setSpacing(8); + $this->labelRight->setOffset($labelRightDimension[1] / 2); + + $this->addLabel($this->labelLeft); + $this->addLabel($this->labelCenter); + $this->addLabel($this->labelRight); + } + } + + /** + * Checks if the default ean label is enabled. + * + * @return bool + */ + protected function isDefaultEanLabelEnabled() { + $label = $this->getLabel(); + $font = $this->font; + return $label !== null && $label !== '' && $font !== null && $this->defaultLabel !== null; + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('upce', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('upce', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must contain 11 chars + // Must contain 6 chars (if starting with upce directly) + // First Chars must be 0 or 1 + if ($c !== 11 && $c !== 6) { + throw new BCGParseException('upce', 'You must provide a UPC-A (11 characters) or a UPC-E (6 characters).'); + } elseif ($this->text[0] !== '0' && $this->text[0] !== '1' && $c !== 6) { + throw new BCGParseException('upce', 'UPC-A must start with 0 or 1 to be converted to UPC-E.'); + } + + // Convert part + $this->upce = ''; + if ($c !== 6) { + // Checking if UPC-A is convertible + $temp1 = substr($this->text, 3, 3); + if ($temp1 === '000' || $temp1 === '100' || $temp1 === '200') { // manufacturer code ends with 100, 200 or 300 + if (substr($this->text, 6, 2) === '00') { // Product must start with 00 + $this->upce = substr($this->text, 1, 2) . substr($this->text, 8, 3) . substr($this->text, 3, 1); + } + } elseif (substr($this->text, 4, 2) === '00') { // manufacturer code ends with 00 + if (substr($this->text, 6, 3) === '000') { // Product must start with 000 + $this->upce = substr($this->text, 1, 3) . substr($this->text, 9, 2) . '3'; + } + } elseif (substr($this->text, 5, 1) === '0') { // manufacturer code ends with 0 + if (substr($this->text, 6, 4) === '0000') { // Product must start with 0000 + $this->upce = substr($this->text, 1, 4) . substr($this->text, 10, 1) . '4'; + } + } else { // No zero leading at manufacturer code + $temp2 = intval(substr($this->text, 10, 1)); + if (substr($this->text, 6, 4) === '0000' && $temp2 >= 5 && $temp2 <= 9) { // Product must start with 0000 and must end by 5, 6, 7, 8 or 9 + $this->upce = substr($this->text, 1, 5) . substr($this->text, 10, 1); + } + } + } else { + $this->upce = $this->text; + } + + if ($this->upce === '') { + throw new BCGParseException('upce', 'Your UPC-A can\'t be converted to UPC-E.'); + } + + if ($c === 6) { + $upca = ''; + + // We convert UPC-E to UPC-A to find the checksum + if ($this->text[5] === '0' || $this->text[5] === '1' || $this->text[5] === '2') { + $upca = substr($this->text, 0, 2) . $this->text[5] . '0000' . substr($this->text, 2, 3); + } elseif ($this->text[5] === '3') { + $upca = substr($this->text, 0, 3) . '00000' . substr($this->text, 3, 2); + } elseif ($this->text[5] === '4') { + $upca = substr($this->text, 0, 4) . '00000' . $this->text[4]; + } else { + $upca = substr($this->text, 0, 5) . '0000' . $this->text[5]; + } + + $this->text = '0' . $upca; + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $odd = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 1; + $odd = true; + } + + if (!isset($this->keys[$this->text[$i - 1]])) { + return; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Draws the extended bars on the image. + * + * @param resource $im + * @param int $plus + */ + protected function drawExtendedBars($im, $plus) { + $rememberX = $this->positionX; + $rememberH = $this->thickness; + + // We increase the bars + $this->thickness = $this->thickness + intval($plus / $this->scale); + $this->positionX = 0; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Last Bars + $this->positionX += 46; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + $this->positionX = $rememberX; + $this->thickness = $rememberH; + } + + /** + * Inverses the string when the $inverse parameter is equal to 1. + * + * @param string $text + * @param int $inverse + * @return string + */ + private static function inverse($text, $inverse = 1) { + if ($inverse === 1) { + $text = strrev($text); + } + + return $text; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGupcext2.barcode.php b/niucloud/core/core/util/barcode/class/BCGupcext2.barcode.php new file mode 100644 index 00000000..4399e0e6 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGupcext2.barcode.php @@ -0,0 +1,138 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + + // Parity, 0=Odd, 1=Even. Depending on ?%4 + $this->codeParity = array( + array(0, 0), /* 0 */ + array(0, 1), /* 1 */ + array(1, 0), /* 2 */ + array(1, 1) /* 3 */ + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting Code + $this->drawChar($im, '001', true); + + // Code + for ($i = 0; $i < 2; $i++) { + $this->drawChar($im, self::inverse($this->findCode($this->text[$i]), $this->codeParity[intval($this->text) % 4][$i]), false); + if ($i === 0) { + $this->drawChar($im, '00', false); // Inter-char + } + } + + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 4; + $textlength = 2 * 7; + $intercharlength = 2; + + $w += $startlength + $textlength + $intercharlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + parent::addDefaultLabel(); + + if ($this->defaultLabel !== null) { + $this->defaultLabel->setPosition(BCGLabel::POSITION_TOP); + } + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('upcext2', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('upcext2', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must contain 2 digits + if ($c !== 2) { + throw new BCGParseException('upcext2', 'Must contain 2 digits.'); + } + + parent::validate(); + } + + /** + * Inverses the string when the $inverse parameter is equal to 1. + * + * @param string $text + * @param int $inverse + * @return string + */ + private static function inverse($text, $inverse = 1) { + if ($inverse === 1) { + $text = strrev($text); + } + + return $text; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/BCGupcext5.barcode.php b/niucloud/core/core/util/barcode/class/BCGupcext5.barcode.php new file mode 100644 index 00000000..cea96609 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/BCGupcext5.barcode.php @@ -0,0 +1,200 @@ + No suggested Retail Price + * If 99991 -> Book Complimentary (normally free) + * If 90001 to 98999 -> Internal Purpose of Publisher + * If 99990 -> Used by the National Association of College Stores to mark used books + * If 0xxxx -> Price Expressed in British Pounds (xx.xx) + * If 5xxxx -> Price Expressed in U.S. dollars (US$xx.xx) + * + *-------------------------------------------------------------------- + * Copyright (C) Jean-Sebastien Goupil + * http://www.barcodephp.com + */ +include_once('BCGParseException.php'); +include_once('BCGBarcode1D.php'); +include_once('BCGLabel.php'); + +class BCGupcext5 extends BCGBarcode1D { + protected $codeParity = array(); + + /** + * Constructor. + */ + public function __construct() { + parent::__construct(); + + $this->keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + + // Parity, 0=Odd, 1=Even. Depending Checksum + $this->codeParity = array( + array(1, 1, 0, 0, 0), /* 0 */ + array(1, 0, 1, 0, 0), /* 1 */ + array(1, 0, 0, 1, 0), /* 2 */ + array(1, 0, 0, 0, 1), /* 3 */ + array(0, 1, 1, 0, 0), /* 4 */ + array(0, 0, 1, 1, 0), /* 5 */ + array(0, 0, 0, 1, 1), /* 6 */ + array(0, 1, 0, 1, 0), /* 7 */ + array(0, 1, 0, 0, 1), /* 8 */ + array(0, 0, 1, 0, 1) /* 9 */ + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Checksum + $this->calculateChecksum(); + + // Starting Code + $this->drawChar($im, '001', true); + + // Code + for ($i = 0; $i < 5; $i++) { + $this->drawChar($im, self::inverse($this->findCode($this->text[$i]), $this->codeParity[$this->checksumValue][$i]), false); + if ($i < 4) { + $this->drawChar($im, '00', false); // Inter-char + } + } + + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 4; + $textlength = 5 * 7; + $intercharlength = 2 * 4; + + $w += $startlength + $textlength + $intercharlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + parent::addDefaultLabel(); + + if ($this->defaultLabel !== null) { + $this->defaultLabel->setPosition(BCGLabel::POSITION_TOP); + } + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('upcext5', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('upcext5', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must contain 5 digits + if ($c !== 5) { + throw new BCGParseException('upcext5', 'Must contain 5 digits.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 9 + // Multiply it by the number + // Add all of that and do ?mod10 + $odd = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 9; + $odd = true; + } + + if (!isset($this->keys[$this->text[$i - 1]])) { + return; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = $this->checksumValue % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Inverses the string when the $inverse parameter is equal to 1. + * + * @param string $text + * @param int $inverse + * @return string + */ + private static function inverse($text, $inverse = 1) { + if ($inverse === 1) { + $text = strrev($text); + } + + return $text; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/JoinDraw.php b/niucloud/core/core/util/barcode/class/JoinDraw.php new file mode 100644 index 00000000..2d3c35fa --- /dev/null +++ b/niucloud/core/core/util/barcode/class/JoinDraw.php @@ -0,0 +1,194 @@ +image1 = $image1->get_im(); + } else { + $this->image1 = $image1; + } + if ($image2 instanceof BCGDrawing) { + $this->image2 = $image2->get_im(); + } else { + $this->image2 = $image2; + } + + $this->background = $background; + $this->space = (int)$space; + $this->position = (int)$position; + $this->alignment = (int)$alignment; + + $this->createIm(); + } + + /** + * Destroys the image. + */ + public function __destruct() { + imagedestroy($this->im); + } + + /** + * Finds the position where the barcode should be aligned. + * + * @param int $size1 + * @param int $size2 + * @param int $ailgnment + * @return int + */ + private function findPosition($size1, $size2, $alignment) { + $rsize1 = max($size1, $size2); + $rsize2 = min($size1, $size2); + + if ($alignment === self::ALIGN_LEFT) { // Or TOP + return 0; + } elseif ($alignment === self::ALIGN_CENTER) { + return $rsize1 / 2 - $rsize2 / 2; + } else { // RIGHT or TOP + return $rsize1 - $rsize2; + } + } + + /** + * Change the alignments. + * + * @param int $alignment + * @return int + */ + private function changeAlignment($alignment) { + if ($alignment === 0) { + return 1; + } elseif ($alignment === 1) { + return 0; + } else { + return 2; + } + } + + /** + * Creates the image. + */ + private function createIm() { + $w1 = imagesx($this->image1); + $w2 = imagesx($this->image2); + $h1 = imagesy($this->image1); + $h2 = imagesy($this->image2); + + if ($this->position === self::POSITION_LEFT || $this->position === self::POSITION_RIGHT) { + $w = $w1 + $w2 + $this->space; + $h = max($h1, $h2); + } else { + $w = max($w1, $w2); + $h = $h1 + $h2 + $this->space; + } + + $this->im = imagecreatetruecolor($w, $h); + imagefill($this->im, 0, 0, $this->background->allocate($this->im)); + + // We start defining position of images + if ($this->position === self::POSITION_TOP) { + if ($w1 > $w2) { + $posX1 = 0; + $posX2 = $this->findPosition($w1, $w2, $this->alignment); + } else { + $a = $this->changeAlignment($this->alignment); + $posX1 = $this->findPosition($w1, $w2, $a); + $posX2 = 0; + } + + $posY2 = 0; + $posY1 = $h2 + $this->space; + } elseif ($this->position === self::POSITION_LEFT) { + if ($w1 > $w2) { + $posY1 = 0; + $posY2 = $this->findPosition($h1, $h2, $this->alignment); + } else { + $a = $this->changeAlignment($this->alignment); + $posY2 = 0; + $posY1 = $this->findPosition($h1, $h2, $a); + } + + $posX2 = 0; + $posX1 = $w2 + $this->space; + } elseif ($this->position === self::POSITION_BOTTOM) { + if ($w1 > $w2) { + $posX2 = $this->findPosition($w1, $w2, $this->alignment); + $posX1 = 0; + } else { + $a = $this->changeAlignment($this->alignment); + $posX2 = 0; + $posX1 = $this->findPosition($w1, $w2, $a); + } + + $posY1 = 0; + $posY2 = $h1 + $this->space; + } else { // defaults to RIGHT + if ($w1 > $w2) { + $posY2 = $this->findPosition($h1, $h2, $this->alignment); + $posY1 = 0; + } else { + $a = $this->changeAlignment($this->alignment); + $posY2 = 0; + $posY1 = $this->findPosition($h1, $h2, $a); + } + + $posX1 = 0; + $posX2 = $w1 + $this->space; + } + + imagecopy($this->im, $this->image1, $posX1, $posY1, 0, 0, $w1, $h1); + imagecopy($this->im, $this->image2, $posX2, $posY2, 0, 0, $w2, $h2); + } + + /** + * Returns the new $im created. + * + * @return resource + */ + public function get_im() { + return $this->im; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/drawer/BCGDraw.php b/niucloud/core/core/util/barcode/class/drawer/BCGDraw.php new file mode 100644 index 00000000..2082b5da --- /dev/null +++ b/niucloud/core/core/util/barcode/class/drawer/BCGDraw.php @@ -0,0 +1,38 @@ +im = $im; + } + + /** + * Sets the filename. + * + * @param string $filename + */ + public function setFilename($filename) { + $this->filename = $filename; + } + + /** + * Method needed to draw the image based on its specification (JPG, GIF, etc.). + */ + abstract public function draw(); +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/drawer/BCGDrawJPG.php b/niucloud/core/core/util/barcode/class/drawer/BCGDrawJPG.php new file mode 100644 index 00000000..2e2c9398 --- /dev/null +++ b/niucloud/core/core/util/barcode/class/drawer/BCGDrawJPG.php @@ -0,0 +1,102 @@ +dpi = max(1, $dpi); + } else { + $this->dpi = null; + } + } + + /** + * Sets the quality of the JPG. + * + * @param int $quality + */ + public function setQuality($quality) { + $this->quality = $quality; + } + + /** + * Draws the JPG on the screen or in a file. + */ + public function draw() { + ob_start(); + imagejpeg($this->im, null, $this->quality); + $bin = ob_get_contents(); + ob_end_clean(); + + $this->setInternalProperties($bin); + + if (empty($this->filename)) { + echo $bin; + } else { + file_put_contents($this->filename, $bin); + } + } + + private function setInternalProperties(&$bin) { + $this->internalSetDPI($bin); + $this->internalSetC($bin); + } + + private function internalSetDPI(&$bin) { + if ($this->dpi !== null) { + $bin = substr_replace($bin, pack("Cnn", 0x01, $this->dpi, $this->dpi), 13, 5); + } + } + + private function internalSetC(&$bin) { + if(strcmp(substr($bin, 0, 4), pack('H*', 'FFD8FFE0')) === 0) { + $offset = 4 + (ord($bin[4]) << 8 | ord($bin[5])); + $firstPart = substr($bin, 0, $offset); + $secondPart = substr($bin, $offset); + $cr = pack('H*', 'FFFE004447656E657261746564207769746820426172636F64652047656E657261746F7220666F722050485020687474703A2F2F7777772E626172636F64657068702E636F6D'); + $bin = $firstPart; + $bin .= $cr; + $bin .= $secondPart; + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/core/util/barcode/class/drawer/BCGDrawPNG.php b/niucloud/core/core/util/barcode/class/drawer/BCGDrawPNG.php new file mode 100644 index 00000000..5b65a3aa --- /dev/null +++ b/niucloud/core/core/util/barcode/class/drawer/BCGDrawPNG.php @@ -0,0 +1,202 @@ +dpi = max(1, $dpi); + } else { + $this->dpi = null; + } + } + + /** + * Draws the PNG on the screen or in a file. + */ + public function draw() { + ob_start(); + imagepng($this->im); + $bin = ob_get_contents(); + ob_end_clean(); + + $this->setInternalProperties($bin); + + if (empty($this->filename)) { + echo $bin; + } else { + file_put_contents($this->filename, $bin); + } + } + + private function setInternalProperties(&$bin) { + // Scan all the ChunkType + if (strcmp(substr($bin, 0, 8), pack('H*', '89504E470D0A1A0A')) === 0) { + $chunks = $this->detectChunks($bin); + + $this->internalSetDPI($bin, $chunks); + $this->internalSetC($bin, $chunks); + } + } + + private function detectChunks($bin) { + $data = substr($bin, 8); + $chunks = array(); + $c = strlen($data); + + $offset = 0; + while ($offset < $c) { + $packed = unpack('Nsize/a4chunk', $data); + $size = $packed['size']; + $chunk = $packed['chunk']; + + $chunks[] = array('offset' => $offset + 8, 'size' => $size, 'chunk' => $chunk); + $jump = $size + 12; + $offset += $jump; + $data = substr($data, $jump); + } + + return $chunks; + } + + private function internalSetDPI(&$bin, &$chunks) { + if ($this->dpi !== null) { + $meters = (int)($this->dpi * 39.37007874); + + $found = -1; + $c = count($chunks); + for($i = 0; $i < $c; $i++) { + // We already have a pHYs + if($chunks[$i]['chunk'] === 'pHYs') { + $found = $i; + break; + } + } + + $data = 'pHYs' . pack('NNC', $meters, $meters, 0x01); + $crc = self::crc($data, 13); + $cr = pack('Na13N', 9, $data, $crc); + + // We didn't have a pHYs + if($found == -1) { + // Don't do anything if we have a bad PNG + if($c >= 2 && $chunks[0]['chunk'] === 'IHDR') { + array_splice($chunks, 1, 0, array(array('offset' => 33, 'size' => 9, 'chunk' => 'pHYs'))); + + // Push the data + for($i = 2; $i < $c; $i++) { + $chunks[$i]['offset'] += 21; + } + + $firstPart = substr($bin, 0, 33); + $secondPart = substr($bin, 33); + $bin = $firstPart; + $bin .= $cr; + $bin .= $secondPart; + } + } else { + $bin = substr_replace($bin, $cr, $chunks[$i]['offset'], 21); + } + } + } + + private function internalSetC(&$bin, &$chunks) { + if (count($chunks) >= 2 && $chunks[0]['chunk'] === 'IHDR') { + $firstPart = substr($bin, 0, 33); + $secondPart = substr($bin, 33); + $cr = pack('H*', '0000004C74455874436F707972696768740047656E657261746564207769746820426172636F64652047656E657261746F7220666F722050485020687474703A2F2F7777772E626172636F64657068702E636F6D597F70B8'); + $bin = $firstPart; + $bin .= $cr; + $bin .= $secondPart; + } + + // Chunks is dirty!! But we are done. + } + + private static $crc_table = array(); + private static $crc_table_computed = false; + + private static function make_crc_table() { + for ($n = 0; $n < 256; $n++) { + $c = $n; + for ($k = 0; $k < 8; $k++) { + if (($c & 1) == 1) { + $c = 0xedb88320 ^ (self::SHR($c, 1)); + } else { + $c = self::SHR($c, 1); + } + } + self::$crc_table[$n] = $c; + } + + self::$crc_table_computed = true; + } + + private static function SHR($x, $n) { + $mask = 0x40000000; + + if ($x < 0) { + $x &= 0x7FFFFFFF; + $mask = $mask >> ($n - 1); + return ($x >> $n) | $mask; + } + + return (int)$x >> (int)$n; + } + + private static function update_crc($crc, $buf, $len) { + $c = $crc; + + if (!self::$crc_table_computed) { + self::make_crc_table(); + } + + for ($n = 0; $n < $len; $n++) { + $c = self::$crc_table[($c ^ ord($buf[$n])) & 0xff] ^ (self::SHR($c, 8)); + } + + return $c; + } + + private static function crc($data, $len) { + return self::update_crc(-1, $data, $len) ^ -1; + } +} +?> diff --git a/niucloud/core/core/util/barcode/font/Arial.ttf b/niucloud/core/core/util/barcode/font/Arial.ttf new file mode 100644 index 00000000..886789b8 Binary files /dev/null and b/niucloud/core/core/util/barcode/font/Arial.ttf differ diff --git a/niucloud/core/core/util/niucloud/BaseNiucloudClient.php b/niucloud/core/core/util/niucloud/BaseNiucloudClient.php new file mode 100644 index 00000000..22355d98 --- /dev/null +++ b/niucloud/core/core/util/niucloud/BaseNiucloudClient.php @@ -0,0 +1,309 @@ +code = $code; + $this->secret = $secret; + }else{ + $auth_config = (new CoreNiucloudConfigService())->getNiucloudConfig(); + if($auth_config['auth_code'] || $auth_config['auth_secret']){ + $this->code = $auth_config['auth_code']; + $this->secret = $auth_config['auth_secret']; + }else{ + $this->code = config('niucloud.auth.code'); + $this->secret = config('niucloud.auth.secret'); + } + } + $this->access_token = $this->getAccessToken(); + $this->request = request(); + $this->developer_token = (new ConfigService())->getDeveloperToken()['token'] ?? ''; + } + + /** + * @param string $url + * @param array $data + * @return array|Response|object|ResponseInterface + * @throws GuzzleException + */ + public function httpPost(string $url, array $data = []) + { + return $this->request($url, 'POST', [ + 'form_params' => $data, + ]); + } + + /** + * @param string $url + * @param string $method + * @param array $options + * @param bool $returnRaw + * + * @return ResponseInterface + * @throws GuzzleException + */ + public function request(string $url, string $method = 'GET', array $options = [], bool $returnRaw = false) + { + if (empty($this->middlewares)) { + $this->registerHttpMiddlewares(); + } + $response = $this->toRequest($url, $method, $options); + return $response; + } + + /** + * Register Guzzle middlewares. + */ + protected function registerHttpMiddlewares() + { + // retry + $this->pushMiddleware($this->retryMiddleware(), 'retry'); + //header + $this->pushMiddleware($this->headerMiddleware(), 'header'); + // access token + $this->pushMiddleware($this->accessTokenMiddleware(), 'access_token'); + } + + /** + * @return callable + */ + protected function retryMiddleware() + { + return Middleware::retry( + function ( + $retries, + RequestInterface $request, + ResponseInterface $response = null + ) { + // Limit the number of retries to 2 重试次数,默认 1,指定当 http 请求失败时重试的次数。 + if ($retries < config('niucloud.http.max_retries', 1) && $response && $body = $response->getBody()) { + // Retry on server errors + $response = json_decode($body, true); + if (isset($response['code'])) { + if ($response['code'] != 1) { + if (in_array(abs($response['code']), [401], true)) { + $this->clearAccessToken(); + $this->refreshAccessToken(); + } else { + throw new NiucloudException($response['msg']); + } + } + return true; + } + } + return false; + }, + function () { + //重试延迟间隔(单位:ms),默认 500 + return abs(config('niucloud.http.retry_delay', 500)); + } + ); + } + + /** + * 表头属性 + * @return Closure + */ + public function headerMiddleware(){ + $developer_token = $this->developer_token; + + return function (callable $handler) use ($developer_token) { + return function (RequestInterface $request, array $options) use ($handler, $developer_token) { + $domain = request()->domain(true); + $domain = str_replace('http://', '', $domain); + $domain = str_replace('https://', '', $domain); + $request = $request->withHeader('Referer', $domain); + $request = $request->withHeader('developer-token', $developer_token); + $options['verify'] = config('niucloud.http.verify', true); + return $handler($request, $options); + }; + }; + } + + + /** + * @param string $url + * @param array $query + * @return array|object|Response|ResponseInterface + * @throws GuzzleException + */ + public function httpGet(string $url, array $query = []) + { + return $this->request($url, 'GET', [ + 'query' => $query, + ]); + } + + /** + * @return Closure + */ + protected function accessTokenMiddleware() + { + return function (callable $handler) { + return function (RequestInterface $request, array $options) use ($handler) { + if ($this->access_token) { + $request = $this->applyToRequest($request, $options); + } + return $handler($request, $options); + }; + }; + } + + /** + * @param RequestInterface $request + * @param array $requestOptions + * @return RequestInterface + */ + public function applyToRequest(RequestInterface $request, array $requestOptions = []): RequestInterface + { + return $request->withHeader($this->access_token_key, $this->access_token); + } + + /** + * @param string $url + * @param array $data + * @param array $query + * @return array|Response|object|ResponseInterface + * @throws GuzzleException + */ + public function httpPostJson(string $url, array $data = [], array $query = []) + { + return $this->request($url, 'POST', ['query' => $query, 'json' => $data]); + } + + /** + * @param string $url + * @param array $files + * @param array $form + * @param array $query + * @return array|Response|object|ResponseInterface + * @throws GuzzleException + */ + public function httpUpload(string $url, array $files = [], array $form = [], array $query = []) + { + $multipart = []; + $headers = []; + + if (isset($form['filename'])) { + $headers = [ + 'Content-Disposition' => 'form-data; name="media"; filename="' . $form['filename'] . '"' + ]; + } + + foreach ($files as $name => $path) { + $multipart[] = [ + 'name' => $name, + 'contents' => fopen($path, 'r'), + 'headers' => $headers + ]; + } + + foreach ($form as $name => $contents) { + $multipart[] = compact('name', 'contents'); + } + + return $this->request( + $url, + 'POST', + ['query' => $query, 'multipart' => $multipart, 'connect_timeout' => 30, 'timeout' => 30, 'read_timeout' => 30] + ); + } + + /** + * @param string $url + * @param string $method + * @param array $options + * @throws GuzzleException + */ + public function requestRaw(string $url, string $method = 'GET', array $options = []) + { + return Response::buildFromPsrResponse($this->request($url, $method, $options, true)); + } + + /** + * 下载文件 + * @param string $url + * @param array $query + * @param string $absolute_path + * @return string + * @throws GuzzleException + */ + public function download(string $url, array $query = [], string $absolute_path = '') + { + // 打开即将下载的本地文件,在该文件上打开一个流 + $resource = fopen($absolute_path, 'w'); + $res = $this->request($url, 'GET', ['sink' => $absolute_path, 'query' => $query]); + // 关闭一个已打开的文件指针 + fclose($resource); + return $absolute_path; + } + + public function getDomain($is_filter = true){ + $domain = request()->domain(true); + if($is_filter){ + $domain = str_replace('http://', '', $domain); + $domain = str_replace('https://', '', $domain); + } + return $domain; + } +} diff --git a/niucloud/core/core/util/niucloud/CloudService.php b/niucloud/core/core/util/niucloud/CloudService.php new file mode 100644 index 00000000..e9323cb5 --- /dev/null +++ b/niucloud/core/core/util/niucloud/CloudService.php @@ -0,0 +1,37 @@ +baseUri = 'http://' . gethostbyname('oss.niucloud.com') . ':8000/'; + } + + public function httpPost(string $url, array $options = []) { + return $this->toRequest($url, 'POST', $options); + } + + public function httpGet(string $url, array $options = []) { + return $this->toRequest($url, 'GET', $options); + } + + public function request(string $method, string $url, array $options = []) { + return (new Client(['base_uri' => $this->baseUri ]))->request($method, $url, $options); + } + + public function getUrl(string $url) { + return $this->baseUri . $url; + } +} diff --git a/niucloud/core/core/util/niucloud/http/AccessToken.php b/niucloud/core/core/util/niucloud/http/AccessToken.php new file mode 100644 index 00000000..c0315b3e --- /dev/null +++ b/niucloud/core/core/util/niucloud/http/AccessToken.php @@ -0,0 +1,73 @@ +access_token = ''; + Cache::delete($this->access_token_cache); + return $this; + } + /** + * 设置access_token + * @param $access_token + * @return $this + */ + public function setAccessToken($access_token) + { + $this->access_token = $access_token; + Cache::set($this->access_token_cache, $access_token, 7200); + return $this; + } + /** + * @return mixed + */ + public function getAccessToken() + { + if (empty($this->access_token)) { + $this->access_token = Cache::get($this->access_token_cache, ''); + } + return $this->access_token; + } + + /** + * 刷新access_token + * @return void + * @throws GuzzleException + */ + public function refreshAccessToken() + { + $access_token_info = $this->httpGet('auth', ['code' => $this->code, 'secret' => $this->secret, 'token' => $this->createToken(), 'product_key' => self::PRODUCT, 'redirect_uri' => $this->getDomain(false)]); + if (isset($access_token_info['code']) && $access_token_info['code'] != 1) throw new NiucloudException($access_token_info['msg']); + $this->setAccessToken($access_token_info['data']['token']); + } + +} diff --git a/niucloud/core/core/util/niucloud/http/HasHttpRequests.php b/niucloud/core/core/util/niucloud/http/HasHttpRequests.php new file mode 100644 index 00000000..e10925e3 --- /dev/null +++ b/niucloud/core/core/util/niucloud/http/HasHttpRequests.php @@ -0,0 +1,183 @@ + [ + CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4, + ], + ]; + /** + * @var ClientInterface + */ + protected $httpClient; + /** + * @var array + */ + protected array $middlewares = []; + /** + * @var HandlerStack + */ + protected $handlerStack; + + /** + * @param array $defaults + * @return void + */ + public static function setDefaultOptions(array $defaults = []) + { + self::$defaults = $defaults; + } + + /** + * @return array + */ + public static function getDefaultOptions(): array + { + return self::$defaults; + } + + /** + * @param callable $middleware + * @param string|null $name + * @return $this + */ + public function pushMiddleware(callable $middleware, string $name = null) + { + if (!is_null($name)) { + $this->middlewares[$name] = $middleware; + } else { + $this->middlewares[] = $middleware; + } + + return $this; + } + + /** + * @return array + */ + public function getMiddlewares(): array + { + return $this->middlewares; + } + + /** + * @param $url + * @param string $method + * @param array $options + * @return ResponseInterface + * @throws GuzzleException + */ + public function toRequest($url, string $method = 'GET', array $options = []) + { + $method = strtoupper($method); + + $options = array_merge(self::$defaults, $options, ['handler' => $this->getHandlerStack()]); + + $options = $this->fixJsonIssue($options); + + if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) { + $options['base_uri'] = $this->baseUri; + } + $options['connect_timeout'] = config('niucloud.http.connect_timeout', 3); + $response = $this->getHttpClient()->request($method, $url, $options); + $response->getBody()->rewind(); + return json_decode($response->getBody()->getContents(), true); + } + + /** + * @return HandlerStack + */ + public function getHandlerStack(): HandlerStack + { + if ($this->handlerStack) { + return $this->handlerStack; + } + + $this->handlerStack = HandlerStack::create($this->getGuzzleHandler()); + + foreach ($this->middlewares as $name => $middleware) { + $this->handlerStack->push($middleware, $name); + } + + return $this->handlerStack; + } + + /** + * @param HandlerStack $handlerStack + * + * @return $this + */ + public function setHandlerStack(HandlerStack $handlerStack) + { + $this->handlerStack = $handlerStack; + + return $this; + } + + /** + * @return callable + */ + protected function getGuzzleHandler() + { + return choose_handler(); + } + + /** + * @param array $options + * @return array + */ + protected function fixJsonIssue(array $options): array + { + if (isset($options['json']) && is_array($options['json'])) { + $options['headers'] = array_merge($options['headers'] ?? [], ['Content-Type' => 'application/json']); + + if (empty($options['json'])) { + $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_FORCE_OBJECT); + } else { + $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_UNESCAPED_UNICODE); + } + + unset($options['json']); + } + + return $options; + } + + /** + * @return ClientInterface + */ + public function getHttpClient(): ClientInterface + { + if (!($this->httpClient instanceof ClientInterface)) { + $this->httpClient = new Client(['handler' => HandlerStack::create($this->getGuzzleHandler())]); + } + + return $this->httpClient; + } + + /** + * @param ClientInterface $httpClient + * @return $this + */ + public function setHttpClient(ClientInterface $httpClient) + { + $this->httpClient = $httpClient; + + return $this; + } +} diff --git a/niucloud/core/core/util/niucloud/http/Response.php b/niucloud/core/core/util/niucloud/http/Response.php new file mode 100644 index 00000000..81e1182c --- /dev/null +++ b/niucloud/core/core/util/niucloud/http/Response.php @@ -0,0 +1,95 @@ +getStatusCode(), + $response->getHeaders(), + $response->getBody(), + $response->getProtocolVersion(), + $response->getReasonPhrase() + ); + } + + /** + * @return object + */ + public function toObject() + { + return json_decode($this->toJson()); + } + + /** + * Build to json. + * + * @return string + */ + public function toJson() + { + return json_encode($this->toArray()); + } + + /** + * Build to array. + * + * @return array + */ + public function toArray() + { + $content = $this->removeControlCharacters($this->getBodyContents()); + + if (false !== stripos($this->getHeaderLine('Content-Type'), 'xml') || 0 === stripos($content, 'getBody()->rewind(); + $contents = $this->getBody()->getContents(); + $this->getBody()->rewind(); + + return $contents; + } + + /** + * @return string + */ + public function __toString() + { + return $this->getBodyContents(); + } +} diff --git a/niucloud/core/core/util/niucloud/http/Token.php b/niucloud/core/core/util/niucloud/http/Token.php new file mode 100644 index 00000000..bb06d51c --- /dev/null +++ b/niucloud/core/core/util/niucloud/http/Token.php @@ -0,0 +1,81 @@ +request->get('signature') !== $this->signature([ + $this->getToken(), + $this->request->get('timestamp'), + $this->request->get('nonce'), + ])) { + throw new NiucloudException('Invalid request signature.'); + } + return true; + } + + /** + * 生成临时证书 + * @param array $params + * @return string + */ + protected function signature(array $params) + { + sort($params, SORT_STRING); + + return sha1(implode($params)); + } + + /** + * 获取TOKEN + * @return void + */ + public function getToken(){ + return Cache::get($this->token_cache, ''); + } + + /** + * 新创建一个token(todo 临时) + * @return void + */ + public function createToken(){ + //根据code和secret生成token + $token = md5(serialize( + [ + 'timestamp' => time(), + 'code' => $this->code, + 'secret' => $this->secret, + 'nonce' => mt_rand(0, 100) + ] + )); + $this->clearToken(); + Cache::set($this->token_cache, $token, 3600); + return $token; + } + + /** + * @return $this + */ + public function clearToken() + { + $this->access_token = ''; + Cache::delete($this->token_cache); + return $this; + } +} diff --git a/niucloud/core/core/util/niucloud/support/XML.php b/niucloud/core/core/util/niucloud/support/XML.php new file mode 100644 index 00000000..d0485bea --- /dev/null +++ b/niucloud/core/core/util/niucloud/support/XML.php @@ -0,0 +1,155 @@ + $value) { + $res = self::normalize($value); + if (('@attributes' === $key) && ($key)) { + $result = $res; + } else { + $result[$key] = $res; + } + } + } else { + $result = $obj; + } + + return $result; + } + + /** + * Delete invalid characters in XML. + * + * @see https://www.w3.org/TR/2008/REC-xml-20081126/#charsets - XML charset range + * @see http://php.net/manual/en/regexp.reference.escape.php - escape in UTF-8 mode + * + * @param string $xml + * + * @return string + */ + public static function sanitize($xml) + { + return preg_replace('/[^\x{9}\x{A}\x{D}\x{20}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]+/u', '', $xml); + } + + /** + * XML encode. + * + * @param mixed $data + * @param string $root + * @param string $item + * @param string $attr + * @param string $id + * + * @return string + */ + public static function build( + $data, + $root = 'xml', + $item = 'item', + $attr = '', + $id = 'id' + ) + { + if (is_array($attr)) { + $_attr = []; + + foreach ($attr as $key => $value) { + $_attr[] = "{$key}=\"{$value}\""; + } + + $attr = implode(' ', $_attr); + } + + $attr = trim($attr); + $attr = empty($attr) ? '' : " {$attr}"; + $xml = "<{$root}{$attr}>"; + $xml .= self::data2Xml($data, $item, $id); + $xml .= ""; + + return $xml; + } + + /** + * Array to XML. + * + * @param array $data + * @param string $item + * @param string $id + * + * @return string + */ + protected static function data2Xml($data, $item = 'item', $id = 'id') + { + $xml = $attr = ''; + + foreach ($data as $key => $val) { + if (is_numeric($key)) { + $id && $attr = " {$id}=\"{$key}\""; + $key = $item; + } + + $xml .= "<{$key}{$attr}>"; + + if ((is_array($val) || is_object($val))) { + $xml .= self::data2Xml((array)$val, $item, $id); + } else { + $xml .= is_numeric($val) ? $val : self::cdata($val); + } + + $xml .= ""; + } + + return $xml; + } + + /** + * Build CDATA. + * + * @param string $string + * + * @return string + */ + public static function cdata($string) + { + return sprintf('', $string); + } +} diff --git a/niucloud/core/printer/sdk/yilianyun/config/YlyConfig.php b/niucloud/core/printer/sdk/yilianyun/config/YlyConfig.php new file mode 100644 index 00000000..cdf00b9e --- /dev/null +++ b/niucloud/core/printer/sdk/yilianyun/config/YlyConfig.php @@ -0,0 +1,68 @@ +clientId = $clientId; + $this->clientSecret = $clientSecret; + } + + public function getClientId() + { + return $this->clientId; + } + + + public function getClientSecret() + { + return $this->clientSecret; + } + + public function getRequestUrl() + { + return $this->requestUrl; + } + + public function setRequestUrl($requestUrl) + { + $this->requestUrl = $requestUrl; + } + + public function getLog() + { + return $this->log; + } + + public function setLog($log) + { + if (!method_exists($log, "info")) { + throw new InvalidArgumentException("logger need have method 'info(\$message)'"); + } + if (!method_exists($log, "error")) { + throw new InvalidArgumentException("logger need have method 'error(\$message)'"); + } + $this->log = $log; + } + +}