diff --git a/20170407223108_f4yeT.png b/20170407223108_f4yeT.png new file mode 100644 index 0000000..ed2b35f Binary files /dev/null and b/20170407223108_f4yeT.png differ diff --git a/22222.jpg b/22222.jpg new file mode 100644 index 0000000..d1bead3 Binary files /dev/null and b/22222.jpg differ diff --git a/3333.jpg b/3333.jpg new file mode 100644 index 0000000..7fde045 Binary files /dev/null and b/3333.jpg differ diff --git a/404.html b/404.html new file mode 100644 index 0000000..99ff94f --- /dev/null +++ b/404.html @@ -0,0 +1,26 @@ + + + + + + +404 + + + + +

404,您请求的文件不存在!

+ + diff --git a/README.md b/README.md index e4909cf..467015a 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,17 @@ -

OneIndex

+## 预览地址 +[pan.mxin.ltd](https://pan.mxin.ltd/) +必须设置伪静态 +支持cli 文件上传下载, +支持世纪互联国际版国内版,同济大学sharepoint +直接文件管理,移动删除,上传下载 预览, +执行php one.php 会提示用法, +多盘模式 +php one.php upload:file 本地文件 远程路径 驱动器 -> Onedrive Directory Index +其他说明 -## 功能 - -不占用服务器空间,不走服务器流量, - -直接列出 OneDrive 目录,文件直链下载。 - -## 伪静态 - -```nginx +1.nginx伪静态 +``` if (!-f $request_filename){ set $rule_0 1$rule_0; } @@ -22,10 +23,139 @@ rewrite ^/(.*)$ /index.php?/$1 last; } ``` -## 预览图 +# oneindex +OneDrive Directory Index + +## 功能: +不用服务器空间,不走服务器流量, + +直接列onedrive目录,文件直链下载。 + -![](http://file.layne666.cn/img/20191125233913.png) -![](http://file.layne666.cn/img/20200211210637.png) +## 创意整合 +1.极大简化安装步骤。 +2.一些样式美化修改。 +3.分页模式,加快页面预览速度。创意来自[oneindex-h](https://github.com/hang666/oneindex-h) +4.可后台自定义网站主标题,副标题。 +5.可后台自定义每页显示项目数量。 -![](http://file.layne666.cn/img/20200211210644.png) \ No newline at end of file +## 重新安装 +删除 oneindex/config 下的所有文件即可. + + +## change log: +20-06-18 代码有点乱,10.0版本后将重构. +20-06-17 管理员模式不使用缓存 +20-06-17 增加并发删除移动api +20-06-16 优化上传 +20-06-14 文件批量移动功能(debug) +20-06-13 文件批量删除(debug) +20-06-12 增加主题背景 +20-06-09 增加新建文件夹功能 +20-06-07 文件管理/删除/重命名 +20-06=07 修复md文件全屏 +20-06=07 修复加密文件夹无法验证密码 +20-06=06 增加重命名文件方法 +20-06=06 增加删除文件方法 +20-06=06 修复重建缓存 +20-06-05 cli 功能增加列表 删除文件创建文件夹 +20-06-05 修复cli上传模式并且支持多盘/sharepoint +20-06-05 修复多盘引起图床失效 +20-06-05 bug 重建缓存失效(文件过多导致炸了api,考虑是否弃用) +20-06-05 增加离线下载功能(开发中 +20—06-02: 添加侧边栏网盘导航 +20-06-01: 修复首页空白问题 +20-05-29: 增加sharepoint站点id自动获取工具,账户显示,空间显示. +20-05-24: 移除cli模式 +20-05-25: 完成自动配置 +20-05-24: 完成多盘配置 +20-05-21: 添加防盗链接 +20-05-20: 移除pdfjs +20-05-19: 静态资源cdn 使用jsdevil +18-03-29: 更新直链获取机制、缓存机制,避免频繁访问的token失效 +18-03-29: 解决非英文编码问题 +18-03-29: 添加onedrive共享的起始目录 功能 +18-03-29: 添加rewrite的配置文件 +18-03-29: 增加sqlite模式cache支持 +18-03-29: 添加缩略图功能 +18-03-29: 添加404判断 +18-03-31: 添加console +18-04-13: 修复特殊文件名无法下载问题 +18-04-13: 添加命令行上传功能 +18-04-16: 更新 2.0 beta +18-04-16: 更新展示界面 +18-04-16: 响应式,支持小屏设备 +18-04-16: 图片在线预览 +18-04-16: 视频在线播放 +18-04-16: 代码在线查看(js、css、html、sh、php、java、md等) +18-04-16: README.md 支持,解析各目录下(onedirive目录下) README.md 文件,在页面尾部展示。 +18-04-18: 音频在线播放 +18-04-18: HEAD.md 支持,在页面头部展示 +18-04-18: .password 文件夹加密 +18-05-06: 在线视频播放器替换成 Dplayer +18-05-06: 在线视频播放支持'mp4','webm','avi','mpg', 'mpeg', 'rm', 'rmvb', 'mov', 'wmv', 'mkv', 'asf' +18-06-01: 支持个人账号 +18-06-01: cli文件夹上传(单线程) +18-06-01: 管理后台(后台地址:?/admin 默认密码:oneindex) +18-06-01: 不同后缀展示设置 +18-06-01: 文件直接输出 +18-06-01: 文件上传管理(后台) +18-06-01: 增加index.html特性 +18-06-01: 图床功能 + +## 需求: +1、PHP空间,PHP 5.6+ 打开curl支持 +2、onedrive 账号 (个人、企业版或教育版/工作或学校帐户) +3、oneindex 程序 + +## 安装: +image + + +## 计划任务   +[可选]**推荐配置**,非必需。后台定时刷新缓存,可增加前台访问的速度   +``` +# 每小时刷新一次token +0 * * * * /具体路径/php /程序具体路径/one.php token:refresh + +# 每十分钟后台刷新一遍缓存 +*/10 * * * * /具体路径/php /程序具体路径/one.php cache:refresh +``` + +## 特殊文件实现功能   +` README.md `、`HEAD.md` 、 `.password`特殊文件使用 + +可以参考[https://github.com/0oVicero0/oneindex/tree/files](https://github.com/0oVicero0/oneindex/tree/files) + +**在文件夹底部添加说明:**   +>在onedrive的文件夹中添加` README.md `文件,使用markdown语法。 + +**在文件夹头部添加说明:**   +>在onedrive的文件夹中添加`HEAD.md` 文件,使用markdown语法。   + +**加密文件夹:**   +>在onedrive的文件夹中添加`.password`文件,填入密码,密码不能为空。   + +**直接输出网页:** +>在onedrive的文件夹中添加`index.html` 文件,程序会直接输出网页而不列目录。 +>配合 文件展示设置-直接输出 效果更佳 + +## 命令行功能   +仅能在php cli模式下运行 +**清除缓存:**   +``` +php one.php cache:clear +``` +**刷新缓存:**   +``` +php one.php cache:refresh +``` +**刷新令牌:**   +``` +php one.php token:refresh +``` +**上传文件:**   +``` +php one.php upload:file 本地文件 [onedrive文件] +``` diff --git a/build.php b/build.php new file mode 100644 index 0000000..a72b8ad --- /dev/null +++ b/build.php @@ -0,0 +1,30 @@ +startBuffering(); + +// 将后缀名相关的文件打包 +foreach ($exts as $ext) { + $phar->buildFromDirectory($dir, '/\.' . $ext . '$/'); +} + +// 把build.php本身摘除 +$phar->delete('build.php'); + +// 设置入口 +$phar->setStub(""); +$phar->stopBuffering(); + +// 打包完成 +echo "Finished {$file}\n"; + diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..a68757e --- /dev/null +++ b/composer.json @@ -0,0 +1,19 @@ +{ + "name": "jane/jane", + "require": { + "guzzlehttp/guzzle": "^6.5" + + }, + "autoload": { + + "psr-4": { + "jane\\": "lib" + + } + + + + + + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..ea8e7c1 --- /dev/null +++ b/composer.lock @@ -0,0 +1,572 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "af24c20e0c12b2e6afec89b777c9736a", + "packages": [ + { + "name": "guzzlehttp/guzzle", + "version": "6.5.5", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "9d4290de1cfd701f38099ef7e183b64b4b7b0c5e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/9d4290de1cfd701f38099ef7e183b64b4b7b0c5e", + "reference": "9d4290de1cfd701f38099ef7e183b64b4b7b0c5e", + "shasum": "", + "mirrors": [ + { + "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%", + "preferred": true + } + ] + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.0", + "guzzlehttp/psr7": "^1.6.1", + "php": ">=5.5", + "symfony/polyfill-intl-idn": "^1.17.0" + }, + "require-dev": { + "ext-curl": "*", + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0", + "psr/log": "^1.1" + }, + "suggest": { + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.5-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "rest", + "web service" + ], + "time": "2020-06-16T21:01:06+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "v1.3.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "shasum": "", + "mirrors": [ + { + "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%", + "preferred": true + } + ] + }, + "require": { + "php": ">=5.5.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "time": "2016-12-20T10:07:11+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "1.6.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "239400de7a173fe9901b9ac7c06497751f00727a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/239400de7a173fe9901b9ac7c06497751f00727a", + "reference": "239400de7a173fe9901b9ac7c06497751f00727a", + "shasum": "", + "mirrors": [ + { + "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%", + "preferred": true + } + ] + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0", + "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "ext-zlib": "*", + "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8" + }, + "suggest": { + "zendframework/zend-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.6-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Schultze", + "homepage": "https://github.com/Tobion" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "time": "2019-07-01T23:21:34+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "", + "mirrors": [ + { + "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%", + "preferred": true + } + ] + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "time": "2016-08-06T14:39:51+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "", + "mirrors": [ + { + "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%", + "preferred": true + } + ] + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "time": "2019-03-08T08:55:37+00:00" + }, + { + "name": "symfony/polyfill-intl-idn", + "version": "v1.17.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-idn.git", + "reference": "a57f8161502549a742a63c09f0a604997bf47027" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/a57f8161502549a742a63c09f0a604997bf47027", + "reference": "a57f8161502549a742a63c09f0a604997bf47027", + "shasum": "", + "mirrors": [ + { + "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%", + "preferred": true + } + ] + }, + "require": { + "php": ">=5.3.3", + "symfony/polyfill-mbstring": "^1.3", + "symfony/polyfill-php72": "^1.10" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.17-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Intl\\Idn\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Laurent Bassin", + "email": "laurent@bassin.info" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "idn", + "intl", + "polyfill", + "portable", + "shim" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-06-06T08:46:27+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.17.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "7110338d81ce1cbc3e273136e4574663627037a7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/7110338d81ce1cbc3e273136e4574663627037a7", + "reference": "7110338d81ce1cbc3e273136e4574663627037a7", + "shasum": "", + "mirrors": [ + { + "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%", + "preferred": true + } + ] + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.17-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-06-06T08:46:27+00:00" + }, + { + "name": "symfony/polyfill-php72", + "version": "v1.17.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php72.git", + "reference": "f048e612a3905f34931127360bdd2def19a5e582" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/f048e612a3905f34931127360bdd2def19a5e582", + "reference": "f048e612a3905f34931127360bdd2def19a5e582", + "shasum": "", + "mirrors": [ + { + "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%", + "preferred": true + } + ] + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.17-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php72\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-05-12T16:47:27+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [], + "plugin-api-version": "1.1.0" +} diff --git a/config/base.php b/config/base.php new file mode 100644 index 0000000..1c015e3 --- /dev/null +++ b/config/base.php @@ -0,0 +1,110 @@ + 'OneIndex', + 'title_name' => 'Index of /', + 'requrl' => '', + 'password' => 'oneindex', + 'drawer' => '
', + 'style' => 'nexmoe', + 'onedrive_root' => '', + 'cache_type' => 'filecache', + 'cache_expire_time' => 3600, + 'cache_refresh_time' => 600, + 'page_item' => 50, + 'root_path' => '', + 'show' => + array ( + 'stream' => + array ( + 0 => 'txt', + ), + 'image' => + array ( + 0 => 'bmp', + 1 => 'jpg', + 2 => 'jpeg', + 3 => 'png', + 4 => 'gif', + 5 => 'webp', + ), + 'video5' => + array ( + ), + 'video' => + array ( + 0 => 'mpg', + 1 => 'mpeg', + 2 => 'mov', + 3 => 'flv', + 4 => 'mp4', + 5 => 'webm', + 6 => 'mkv', + 7 => 'm3u8', + ), + 'video2' => + array ( + 0 => 'avi', + 1 => 'rm', + 2 => 'rmvb', + 3 => 'wmv', + 4 => 'asf', + 5 => 'ts', + ), + 'audio' => + array ( + 0 => 'ogg', + 1 => 'mp3', + 2 => 'wav', + 3 => 'flac', + 4 => 'aac', + 5 => 'm4a', + 6 => 'ape', + ), + 'code' => + array ( + 0 => 'html', + 1 => 'htm', + 2 => 'php', + 3 => 'css', + 4 => 'go', + 5 => 'java', + 6 => 'js', + 7 => 'json', + 8 => 'txt', + 9 => 'sh', + 10 => 'md', + ), + 'doc' => + array ( + 0 => 'csv', + 1 => 'doc', + 2 => 'docx', + 3 => 'odp', + 4 => 'ods', + 5 => 'odt', + 6 => 'pot', + 7 => 'potm', + 8 => 'potx', + 9 => 'pps', + 10 => 'ppsx', + 11 => 'ppsxm', + 12 => 'ppt', + 13 => 'pptm', + 14 => 'pptx', + 15 => 'rtf', + 16 => 'xls', + 17 => 'xlsx', + ), + ), + 'images' => + array ( + 'home' => false, + 'public' => false, + 'exts' => + array ( + 0 => 'jpg', + 1 => 'png', + 2 => 'gif', + 3 => 'bmp', + ), + ), +); \ No newline at end of file diff --git a/config/default.php b/config/default.php new file mode 100644 index 0000000..3408543 --- /dev/null +++ b/config/default.php @@ -0,0 +1,10 @@ + 'cn', + 'client_secret' => 'v4[Nq:4=rmFS78BwYi[@x3sGk-iY.U:S', + 'client_id' => '3447f073-eef3-4c60-bb68-113a86f2c39a', + 'redirect_uri' => 'https://coding.mxin.ltd/api/onedrive.html', + 'api' => 'https://microsoftgraph.chinacloudapi.cn/v1.0/me/drive/root', + 'api_url' => 'https://microsoftgraph.chinacloudapi.cn/v1.0', + 'oauth_url' => 'https://login.partner.microsoftonline.cn/common/oauth2/v2.0', + +); \ No newline at end of file diff --git a/config/test.php1 b/config/test.php1 new file mode 100644 index 0000000..0e45a6d --- /dev/null +++ b/config/test.php1 @@ -0,0 +1,12 @@ + 'cn', + 'client_secret' => 'v4[Nq:4=rmFS78BwYi[@x3sGk-iY.U:S', + 'client_id' => '3447f073-eef3-4c60-bb68-113a86f2c39a', + 'redirect_uri' => 'https://coding.mxin.ltd/api/onedrive.html', + 'api' => 'https://microsoftgraph.chinacloudapi.cn/v1.0/me/drive/root', + 'api_url' => 'https://microsoftgraph.chinacloudapi.cn/v1.0', + 'oauth_url' => 'https://login.partner.microsoftonline.cn/common/oauth2/v2.0', + 'refresh_token' => 'OAQABAAAAAABTYj0VqP05TZ6xV9yGkWlGKHLsrR0YRkRYPN1J2I-SvWORdxAFCCelKZJW0qvLMAYpcvASFkeR5A7C2w-b20aacrhiOvMX2Y9L1iPzjvoHe7aDrCTj52xzpaMf_3OI1Yamu6A1x82tcncRNczK6quVRaDPYZGZjYGUJ9JEjxXchDkbr5tJTAyvsvuvp2ZksMQU8CUOfT3SD7Rp-nVkK3PMT7nvZ6jyl3TpWmTHzbcqPx_4S1Y3Gi4jjeCanQQUmAJiu8ep2TFIFeEYFu6LZNAmlfbuEZ2A-ck0idMf_IUakTMPXq7-sxY2to0jgbMk510OEi1WvFVlzOvupdxxvwT9ZiBnjY5kUfmuXfz7737qCnQoTVcTSzIyQcBVoGKcomfJQHfRTrhn-MoyvuO_68KkGtp5acyi_IBmZq8qejT-gf-M66bl1kxj_XyzEj_LyqBt7lQNtUnlgZ9VxCuUixiKWSLH9DSEkT1yeHPtYMzS3wseqgIuY2QsaLjHWpxQ61eTd9lsFgMW9cstrhYoD8FZ3POb13Jq0x2sxn3RCBwLRz93I09FJu460iUV1vFs6JRSik8UXkQOpaAik4uobQdHt4tLmzxh3lFWQ6HTt9hBBCG23gNsPUo8peusfJSUEN2j2zMW9v8WA5AWoFteMZYD1hbiNDwhElUnc9kq-fwtJkJEk4DJgg40J814GOfF9k8v941sdN_SArtSuJvBrNaRuTH78oX3gPa9PnzyYY6Iv3FNgl0t8XBOlT7JHLr8YXa8B1Mw5pr7Bo7m48TFp37FGyFnURotO1FTqaf5jLnRGxDLyy4nXb4uocjtebCwCo4gAA', + 'expires_on' => 1590850482, + 'access_token' => 'eyJ0eXAiOiJKV1QiLCJub25jZSI6IjNfTlJUNTRpWVZVd2tnck1CMWM3Q0Y5VXNZcWF0dVgzREZoRTNZSXo0VmciLCJhbGciOiJSUzI1NiIsIng1dCI6Ilk5cTBEazE3VVpBbmRTdUhISDVmWVZJdmh6cyIsImtpZCI6Ilk5cTBEazE3VVpBbmRTdUhISDVmWVZJdmh6cyJ9.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTAwMDAtYzAwMC0wMDAwMDAwMDAwMDAiLCJpc3MiOiJodHRwczovL3N0cy5jaGluYWNsb3VkYXBpLmNuLzNiMWM4MWIxLWQxNTYtNGFmOS1iMTY5LWFlMDgxMjhjMDM5Ni8iLCJpYXQiOjE1OTA4NDY1ODMsIm5iZiI6MTU5MDg0NjU4MywiZXhwIjoxNTkwODUwNDgzLCJhY3IiOiIxIiwiYWlvIjoiQVNRQTIvOEhBQUFBeForcDYrdUpIVXk5UE1BRGsyUThyemcxZWVqMENLYlFxSmNzVTRoV1pLbz0iLCJhbXIiOlsicHdkIl0sImFwcF9kaXNwbGF5bmFtZSI6IjIxViBPZmZpY2UzNjUgYXBwIHNlcnZlciIsImFwcGlkIjoiMzQ0N2YwNzMtZWVmMy00YzYwLWJiNjgtMTEzYTg2ZjJjMzlhIiwiYXBwaWRhY3IiOiIxIiwiaXBhZGRyIjoiMjIyLjEzOC4yMjEuMTg5IiwibmFtZSI6ImxqeTE5OTMyMjciLCJvaWQiOiJhYjMyMTFjOS04ZmQxLTRiMzktOTYwOC0zMzFhYTZiMGJlMzIiLCJwbGF0ZiI6IjMiLCJwdWlkIjoiMTAwMzMyMzBDNTYzM0MwRCIsInNjcCI6IkZpbGVzLlJlYWRXcml0ZS5BbGwgRmlsZXMuUmVhZFdyaXRlLlNlbGVjdGVkIFNpdGVzLk1hbmFnZS5BbGwgU2l0ZXMuUmVhZFdyaXRlLkFsbCBwcm9maWxlIG9wZW5pZCBlbWFpbCIsInN1YiI6IndJNGEwVzB1RzdDMHFtaDZlaU9YcmtvcGVwblYxRlQwV3RQSF9sZUwyeDgiLCJ0aWQiOiIzYjFjODFiMS1kMTU2LTRhZjktYjE2OS1hZTA4MTI4YzAzOTYiLCJ1bmlxdWVfbmFtZSI6ImxqeTE5OTMyMjdAdmlwLnRnIiwidXBuIjoibGp5MTk5MzIyN0B2aXAudGciLCJ1dGkiOiJLWHVjQjVwckNVLV94N2cyQ3c0QUFBIiwidmVyIjoiMS4wIiwieG1zX3N0Ijp7InN1YiI6IkJLMlNCN1lnMkZ6dk10T2FtSXBscnp5TGs1R0k0WGhiMW41MXJnNG83MU0ifSwieG1zX3RjZHQiOjE0NTcxMTQ3Mzh9.vKOjDhNVslNHLWg1gqoXF0yEk9lOepm6E_q-LmqEUZzR2rnH3Gf1IJ5tlqUvPNxODxf_H93-vLZ2QGKt32wOl244fqGR8GEsXCQs9olgQhTNQDwPmWdgSpVl8MRocBbpkWA8bb_1rx0RJZJKLwd8qiramWchn1xVR63yOC-qnJUIH_OZk1TdhWurqP0aOF-50nLkar4Y_05z2GrWtZvXsRLV9F9cP0pldMuvE-FlKQWHcw98ih2aXJyhpPaNFM3RfMpLRvJ4NXGSdfYJO3Jx4P5A4DyHMWG-cd4MzL_hGzV5QyjEAFRDVgKHgRBFo0s61PYPPvpJyuF-D1RkGsVyBw', +); \ No newline at end of file diff --git "a/config/\345\210\253\344\272\272\347\232\204test.php" "b/config/\345\210\253\344\272\272\347\232\204test.php" new file mode 100644 index 0000000..a4c2a24 --- /dev/null +++ "b/config/\345\210\253\344\272\272\347\232\204test.php" @@ -0,0 +1,12 @@ + 'cn', + 'client_secret' => 'v4[Nq:4=rmFS78BwYi[@x3sGk-iY.U:S', + 'client_id' => '3447f073-eef3-4c60-bb68-113a86f2c39a', + 'redirect_uri' => 'https://coding.mxin.ltd/api/onedrive.html', + 'api' => 'https://microsoftgraph.chinacloudapi.cn/v1.0/me/drive/root', + 'api_url' => 'https://microsoftgraph.chinacloudapi.cn/v1.0', + 'oauth_url' => 'https://login.partner.microsoftonline.cn/common/oauth2/v2.0', + 'refresh_token' => 'OAQABAAAAAABTYj0VqP05TZ6xV9yGkWlGfgoquhwFiXN9V-XiLJ8BX3XUqA-uvT_MCqOHjF5nrtATiSNd27myTfktZ1MtaTCEksfEzULp2xdol6zsTnkiITqE6Xu_v1NSUU56dMq66rn3hyIPG5FqbpVGZV1cXt_4zkyFkn-9vEVnJG4hkA_nXjdC1S3s25xqu6G7cpHlIZszhAmI_5a2V88Y2-P-mIgeRt9FUW6fMUo2LIYHHdKVn7oKiqbW5dRMG6vA73FP4llcaGsY_iPoKr3Fa73RtxPtPHTcoYRJyAAPi3PZw71G7Phuhu5p_EcxIr0X7c0cJfc-fCDAvQBPTBwsN9-NnkjQcCeFUJcNo8mvPDJY4qmy8g7mLDUtoCWYH8FpFN_0fbtAW3fWOEDEcYoWnfqsjejJ9vexlv-4X_yLo_O7mX5LZhjBRX9YQeSN8xn2YEI4iDtN8F3wUnPVDJAIAcWjeKG8UzXHN7YC2n33ecK0SyRqj_GmXaXzfUM5DRwcZFsC-8XyCAjXVbmSb5w0jGdatVqlg8cI6qlHUGIry-o6E9N8jIw8aKg7E5V__t5jHg0mDK2CbD3uk0GTbPXfVX9rTSQaaiOSEt1fgeKY_TNaIk4-sVl2X7SWf9nl_lN6opEMu-CaBDitNKJ3VlGHU314MhJJJb5m-4ooy9bjHiE9mdbNN8xaIbU5ULIVsg6nbDrCYtSb5d0O7Aon97102QGl4Tl6OEwGMuEGYcjk5XaoG-_NfFG60ANlknofA_D63Dx4pZUqmVlR2p5SECcZ9El9NLbjXBKfNBKM8m5de3SNgkawiCOyuEsB4SshYKYuoVBprIMgAA', + 'access_token' => 'eyJ0eXAiOiJKV1QiLCJub25jZSI6InlaZ3M5R2FRSlE5cjFDWVlJVl9QRFF3WlRGMUFwMjBLTmxpakE3Smk5MHciLCJhbGciOiJSUzI1NiIsIng1dCI6Ilk5cTBEazE3VVpBbmRTdUhISDVmWVZJdmh6cyIsImtpZCI6Ilk5cTBEazE3VVpBbmRTdUhISDVmWVZJdmh6cyJ9.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTAwMDAtYzAwMC0wMDAwMDAwMDAwMDAiLCJpc3MiOiJodHRwczovL3N0cy5jaGluYWNsb3VkYXBpLmNuLzNiMWM4MWIxLWQxNTYtNGFmOS1iMTY5LWFlMDgxMjhjMDM5Ni8iLCJpYXQiOjE1OTA4NDU5ODEsIm5iZiI6MTU5MDg0NTk4MSwiZXhwIjoxNTkwODQ5ODgxLCJhY3IiOiIxIiwiYWlvIjoiWTJkZ1lMQS9rMWtiei9NN3dEZmxxbnk2Ny9GN0lXSGwvV2FybUxaOHRxbVkvTmxnUmkwQSIsImFtciI6WyJwd2QiXSwiYXBwX2Rpc3BsYXluYW1lIjoiMjFWIE9mZmljZTM2NSBhcHAgc2VydmVyIiwiYXBwaWQiOiIzNDQ3ZjA3My1lZWYzLTRjNjAtYmI2OC0xMTNhODZmMmMzOWEiLCJhcHBpZGFjciI6IjEiLCJpcGFkZHIiOiIxMTcuMTc5LjIxMy4xMDciLCJuYW1lIjoicWluZ2ppdXBhbiIsIm9pZCI6IjFhZGQxMWJkLTc3YWMtNGU5Ny04NTA1LTE2ZmNiMzQyMGFmZCIsInBsYXRmIjoiMSIsInB1aWQiOiIxMDAzMzIzMEM1Njk1QzhCIiwic2NwIjoiRmlsZXMuUmVhZFdyaXRlLkFsbCBGaWxlcy5SZWFkV3JpdGUuU2VsZWN0ZWQgU2l0ZXMuTWFuYWdlLkFsbCBTaXRlcy5SZWFkV3JpdGUuQWxsIHByb2ZpbGUgb3BlbmlkIGVtYWlsIiwic3ViIjoia3o1dTJtdFRPZHl1Z3FHc0J0YzV1MEFGNFZUWXVfaUdSQ2RYVHZFRnZRYyIsInRpZCI6IjNiMWM4MWIxLWQxNTYtNGFmOS1iMTY5LWFlMDgxMjhjMDM5NiIsInVuaXF1ZV9uYW1lIjoicWluZ2ppdXBhbkB2aXAudGciLCJ1cG4iOiJxaW5naml1cGFuQHZpcC50ZyIsInV0aSI6ImN4QkVPNDFkMzA2ci0xREN3d3NBQUEiLCJ2ZXIiOiIxLjAiLCJ4bXNfc3QiOnsic3ViIjoic3h5YkttWWtwSE44T09WRDh3Yy1FTHJYNmlaZnJpdFVSU18ta2NrcGplTSJ9LCJ4bXNfdGNkdCI6MTQ1NzExNDczOH0.X4dmMUhVLZQDwlIM82yeQ4g71TqbrHm2y-HASGT1MhQ7Yvyj-hjBq3FQJEvsmyyQcWpYttCs1Yxt0_WhJq-cVv7Za56NDpj_MZfcWzd94EaiUtjsVprQ5C94lTPuXnY27WXuvH8rGVuf0Sf8f0Fq1U6zKwWN6qfcCNGRpyP1dfeB3TeAuSC6c-FnmuHayjcFMtoRjmuyvntj7ufClnt_0csgroIqr3UJibhhH1NWtogscM_npPqkHdWax7bsyO0tbGUc8CVjmLMfNLu-JHljgAOUuGCZphfEKttOis2GFNIzOfGuZnYh-Bgy1I1ev-k4z8LeaDFPmo6qXrPlNmJ-LA', + 'expires_on' => 1590849881, +); \ No newline at end of file diff --git a/controller/AdminController.php b/controller/AdminController.php index 5f6222e..8784624 100644 --- a/controller/AdminController.php +++ b/controller/AdminController.php @@ -1,210 +1,140 @@ -'OneIndex', - 'password' => 'oneindex', - 'style'=>'nexmoe', - 'onedrive_root' =>'', - 'cache_type'=>'filecache', - 'cache_expire_time' => 3600, - 'cache_refresh_time' => 600, - 'root_path' => '', - 'show'=> array ( - 'stream'=>['txt'], - 'image' => ['bmp','jpg','jpeg','png','gif'], - 'video5'=>[], - 'video'=>['mp4','webm','mkv'], - 'video2'=>['avi','mpg', 'mpeg', 'rm', 'rmvb', 'mov', 'wmv', 'asf', 'ts', 'flv'], - 'audio'=>['ogg','mp3','wav'], - 'code'=>['html','htm','php', 'css', 'go','java','js','json','txt','sh','md'], - 'doc'=>['csv','doc','docx','odp','ods','odt','pot','potm','potx','pps','ppsx','ppsxm','ppt','pptm','pptx','rtf','xls','xlsx'] - ), - 'images'=>['home'=>false,'public'=>false, 'exts'=>['jpg','png','gif','bmp']] - ); - - function __construct(){ - } - - function login(){ - if(!empty($_POST['password']) && $_POST['password'] == config('password')){ - setcookie('admin', md5(config('password').config('refresh_token')) ); - return view::direct(get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).'?/admin/'); - } - return view::load('login')->with('title', '系统管理'); - } - - function logout(){ - setcookie('admin', '' ); - return view::direct(get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).'?/login'); - } - - function settings(){ - $message = false; - - if($_POST){ - - if ($this->cache_exists($_POST['cache_type'])) { - $message = '保存成功'; - config('cache_type', $_POST['cache_type']); - } else { - $message = '缓存类型不可用,请确认已经安装了该拓展。'; - config('cache_type', 'secache'); - } - - config('site_name', $_POST['site_name']); - config('style', $_POST['style']); - config('onedrive_root', get_absolute_path($_POST['onedrive_root'])); - config('onedrive_hide', $_POST['onedrive_hide']); - config('onedrive_hotlink', $_POST['onedrive_hotlink']); - config('cache_expire_time', intval($_POST['cache_expire_time'])); - $_POST['root_path'] = empty($_POST['root_path'])?'?':''; - config('root_path', $_POST['root_path']); - } - - $config = config('@base'); - - return view::load('settings')->with('config', $config)->with('message', $message); - } - - /** - * 判断缓存类型 - * - * @param string $cache_type 缓存类型 - * @return void - */ - function cache_exists($cache_type){ - // 需要判断环境的缓存类型 - $_cache_type = [ - 'redis', - 'memcache', - ]; - - if (in_array($cache_type, $_cache_type)) { - return class_exists(ucfirst($cache_type)); - } - - return true; - } - - function cache(){ - if(!is_null($_POST['clear'])){ - cache::clear(); - $message = "清除缓存成功"; - }elseif ( !is_null($_POST['refresh']) ){ - oneindex::refresh_cache(get_absolute_path(config('onedrive_root'))); - $message = "重建缓存成功"; - } - return view::load('cache')->with('message', $message); - } - - function images(){ - if($_POST){ - $config['home'] = empty($_POST['home'])?false:true; - $config['public'] = empty($_POST['public'])?false:true; - $config['exts'] = explode(" ", $_POST['exts']); - config('images@base',$config); - } - $config = config('images@base'); - return view::load('images')->with('config', $config);; - } - - - function show(){ - if(!empty($_POST) ){ - foreach($_POST as $n=>$ext){ - $show[$n] = explode(' ', $ext); - } - config('show', $show); - } - $names = [ - 'stream'=>'直接输出(<5M),走本服务器流量(stream)', - 'image' =>'图片(image)', - 'video'=>'Dplayer 视频(video)', - 'video2'=>'Dplayer DASH 视频(video2)/个人版账户不支持', - 'video5'=>'html5视频(video5)', - 'audio'=>'音频播放(audio)', - 'code'=>'文本/代码(code)', - 'doc'=>'文档(doc)' - ]; - $show = config('show'); - return view::load('show')->with('names', $names)->with('show', $show); - } - - function setpass(){ - if($_SERVER['REQUEST_METHOD'] == 'POST'){ - if($_POST['old_pass'] == config('password')){ - if($_POST['password'] == $_POST['password2']){ - config('password', $_POST['password']); - $message = "修改成功"; - }else{ - $message = "两次密码不一致,修改失败"; - } - }else{ - $message = "原密码错误,修改失败"; - } - } - return view::load('setpass')->with('message', $message); - } - - function install(){ - if(!empty($_GET['code'])){ - return $this->install_3(); - } - switch ( intval($_GET['step']) ){ - case 1: - return $this->install_1(); - case 2: - return $this->install_2(); - default: - return $this->install_0(); - } - } - - function install_0(){ - $check['php'] = version_compare(PHP_VERSION,'5.5.0','ge'); - $check['curl'] = function_exists('curl_init'); - $check['config'] = is_writable(ROOT.'config/'); - $check['cache'] = is_writable(ROOT.'cache/'); - - return view::load('install/install_0')->with('title','系统安装') - ->with('check', $check); - } - - function install_1(){ - if(!empty($_POST['client_secret']) && !empty($_POST['client_id']) && !empty($_POST['redirect_uri']) ){ - config('@base', self::$default_config); - config('client_secret',$_POST['client_secret']); - config('client_id',$_POST['client_id']); - config('redirect_uri',$_POST['redirect_uri']); - return view::direct('?step=2'); - } - if($_SERVER['HTTP_HOST'] == 'localhost'){ - $redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].get_absolute_path(dirname($_SERVER['PHP_SELF'])); - }else{ - // 非https,调用ju.tn中转 - $redirect_uri = 'https://pan.layne666.cn/'; - } - - $ru = "https://developer.microsoft.com/en-us/graph/quick-start?appID=_appId_&appName=_appName_&redirectUrl={$redirect_uri}&platform=option-php"; - $deepLink = "/quickstart/graphIO?publicClientSupport=false&appName=oneindex&redirectUrl={$redirect_uri}&allowImplicitFlow=false&ru=".urlencode($ru); - $app_url = "https://apps.dev.microsoft.com/?deepLink=".urlencode($deepLink); - return view::load('install/install_1')->with('title','系统安装') - ->with('redirect_uri', $redirect_uri) - ->with('app_url', $app_url); - } - - function install_2(){ - return view::load('install/install_2')->with('title','系统安装'); - } - - function install_3(){ - $data = onedrive::authorize($_GET['code']); - if(!empty($data['refresh_token'])){ - config('refresh_token',$data['refresh_token']); - config('@token', $data); - } - return view::load('install/install_3')->with('refresh_token',$data['refresh_token']); - - } +class AdminController +{ + public static $default_config = array( + 'site_name' => 'OneIndex', + 'title_name' => 'Index of /', + 'requrl'=> "", + 'password' => 'oneindex', + 'drawer' => '
', + 'style' => 'nexmoe', + 'onedrive_root' => '', + 'cache_type' => 'filecache', + 'cache_expire_time' => 3600, + 'cache_refresh_time' => 600, + 'page_item' => 50, + 'root_path' => '', + 'show' => array( + 'stream' => ['txt'], + 'image' => ['bmp', 'jpg', 'jpeg', 'png', 'gif', 'webp'], + 'video5' => [], + 'video' => ['mpg', 'mpeg', 'mov', 'flv', 'mp4', 'webm', 'mkv', 'm3u8'], + 'video2' => ['avi', 'rm', 'rmvb', 'wmv', 'asf', 'ts'], + 'audio' => ['ogg', 'mp3', 'wav', 'flac', 'aac', 'm4a', 'ape'], + 'code' => ['html', 'htm', 'php', 'css', 'go', 'java', 'js', 'json', 'txt', 'sh', 'md'], + 'doc' => ['csv', 'doc', 'docx', 'odp', 'ods', 'odt', 'pot', 'potm', 'potx', 'pps', 'ppsx', 'ppsxm', 'ppt', 'pptm', 'pptx', 'rtf', 'xls', 'xlsx'], + ), + 'images' => ['home' => false, 'public' => false, 'exts' => ['jpg', 'png', 'gif', 'bmp']], + ); + + public function __construct() + { + } + + public function login() + { + if (!empty($_POST['password']) && $_POST['password'] == config('password')) { + setcookie('admin',config('password')); + + return view::direct(get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).'?/admin/'); + } + header('Location:/login.php'); + return view::load('login')->with('title', '系统管理'); + } + + public function logout() + { + setcookie('admin', ''); + + return view::direct(get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).'?/login'); + } + + public function settings() + { + if ($_POST) { + config('site_name', $_POST['site_name']); + config('title_name', $_POST['title_name']); + config('drawer', $_POST['drawer']); + config('style', $_POST['style']); + config('main_domain', $_POST['main_domain']); + config('proxy_domain', $_POST['proxy_domain']); + config('onedrive_root', get_absolute_path($_POST['onedrive_root'])); + + config('onedrive_hide', $_POST['onedrive_hide']); + + config('cache_type', $_POST['cache_type']); + config('cache_expire_time', intval($_POST['cache_expire_time'])); + config('page_item', intval($_POST['page_item'])); + + $_POST['root_path'] = empty($_POST['root_path']) ? '?' : ''; + config('root_path', $_POST['root_path']); + } + $config = config('@base'); + + return view::load('settings')->with('config', $config); + } + + public function cache() + { + require(ROOT."del.php"); + return view::load('cache')->with('message', $message); + } + + public function images() + { + if ($_POST) { + $config['home'] = empty($_POST['home']) ? false : true; + $config['public'] = empty($_POST['public']) ? false : true; + $config['exts'] = explode(' ', $_POST['exts']); + config('images@base', $config); + } + $config = config('images@base'); + + return view::load('images')->with('config', $config); + } + + public function show() + { + if (!empty($_POST)) { + foreach ($_POST as $n => $ext) { + $show[$n] = explode(' ', $ext); + } + config('show', $show); + } + $names = [ + 'stream' => '直接输出(<5M),走本服务器流量(stream)', + 'image' => '图片(image)', + 'video' => 'Dplayer 视频(video)', + 'video2' => 'Dplayer DASH 视频(video2)/个人版账户不支持', + 'video5' => 'html5视频(video5)', + 'audio' => '音频播放(audio)', + 'code' => '文本/代码(code)', + 'doc' => '文档(doc)', + ]; + $show = config('show'); + + return view::load('show')->with('names', $names)->with('show', $show); + } + + public function setpass() + { + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + if ($_POST['old_pass'] == config('password')) { + if ($_POST['password'] == $_POST['password2']) { + config('password', $_POST['password']); + $message = '修改成功'; + } else { + $message = '两次密码不一致,修改失败'; + } + } else { + $message = '原密码错误,修改失败'; + } + } + + return view::load('setpass')->with('message', $message); + } + + } diff --git a/controller/ApiController.php b/controller/ApiController.php new file mode 100644 index 0000000..b07ce57 --- /dev/null +++ b/controller/ApiController.php @@ -0,0 +1,52 @@ +$驱动器=$varrr["1"] ; + array_splice($varrr,0, 1); + unset($varrr['0']); + $请求路径 = implode("/", $varrr); + $this->$请求路径= str_replace("?".$_SERVER["QUERY_STRING"],"",$请求路径); + if ($驱动器==""){ + $this->$请求路径="default"; + } + $me= ROOT.'config/'.$this->$驱动器.'.php'; + + if (file_exists($me)) { + $this->$配置文件 = include ($me); } + + } + + function put(){ + $filename= $_GET['upbigfilename']; + $path=$this->$请求路径.$filename; + $path = onedrive::urlencode($path); + $path = empty($path)?'/':":/{$path}:/"; + $token= $this->$配置文件["access_token"]; + $request['headers'] = "Authorization: bearer {$token}".PHP_EOL."Content-Type: application/json".PHP_EOL; + $request['url']= $this->$配置文件["api"].$path."createUploadSession"; + $request['post_data'] = '{"item": {"@microsoft.graph.conflictBehavior": "rename"}}'; + $resp = fetch::post($request); + $data = json_decode($resp->content, true); + if($resp->http_code == 409){ + return false; + } + + echo $resp->content; + } + function delete(){ + + echo "删除"; + } + function rename() + {} + + function creat() + {} + function PROPFIND(){ + + } +} \ No newline at end of file diff --git a/controller/ImagesController.php b/controller/ImagesController.php index e085f29..2db76ff 100644 --- a/controller/ImagesController.php +++ b/controller/ImagesController.php @@ -1,6 +1,10 @@ is_image($_FILES["file"]) ){ - //$filename = $_FILES["file"]['name']; - $filename = $this->generateRandomString(10).'.'.substr(strrchr($_FILES["file"]['name'], '.'), 1); $content = file_get_contents( $_FILES["file"]['tmp_name']); - $remotepath = 'images/'.date('Y/m/d/'); - $remotefile = $remotepath.$filename; + + $remotepath = 'images/'.$this->generateRandomString(10).'/'; + $remotefile = $remotepath.$_FILES["file"]['name']; $result = onedrive::upload(config('onedrive_root').$remotefile, $content); if($result){ + + $var=explode("/",$_SERVER["REQUEST_URI"]); +$驱动器=$var["1"]; + $root = get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).config('root_path'); $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://'; - $url = $_SERVER['HTTP_HOST'].$root.'/'.$remotepath.rawurldecode($filename).((config('root_path') == '?')?'&s':'?s'); + $url = $_SERVER['HTTP_HOST'].'/'.$驱动器.$root.'/'.$remotefile.((config('root_path') == '?')?'&s':'?s'); $url = $http_type.str_replace('//','/', $url); view::direct($url); } @@ -36,7 +43,7 @@ function is_image($file){ if(!in_array($ext,$config['exts'])){ return false; } - if($file['size'] > 10485760 || $file['size'] == 0){ + if($file['size'] > 104857600000000000 || $file['size'] == 0){ return false; } diff --git a/controller/IndexController.php b/controller/IndexController.php index 048b68f..903c62b 100644 --- a/controller/IndexController.php +++ b/controller/IndexController.php @@ -5,37 +5,271 @@ class IndexController{ private $path; private $items; private $time; - + static $驱动器; + static $请求路径; function __construct(){ - //获取路径和文件名 - $paths = explode('/', rawurldecode($_GET['path'])); + + + +$varrr=explode("/",$_SERVER["REQUEST_URI"]); +$驱动器=$varrr["1"] ;array_splice($varrr,0, 1);unset($varrr['0']); $请求路径 = implode("/", $varrr);$请求路径= str_replace("?".$_SERVER["QUERY_STRING"],"",$请求路径); $url=$请求路径; + if ($驱动器==""){ + $驱动器="default"; + } + self::$驱动器=$驱动器; + self::$请求路径=$请求路径; + +define('CACHE_PATH', ROOT.'cache/'.$驱动器."/");if(!file_exists (CACHE_PATH)){ mkdir(CACHE_PATH); } + cache::$type = empty( config('cache_type') )?'secache':config('cache_type'); + +if (file_exists(ROOT.'config/'.$驱动器.'.php')) { + $配置文件 = include (ROOT.'config/'.$驱动器.'.php'); } + else + if (!file_exists(ROOT.'config/base.php') or !file_exists(ROOT.'config/default.php') ) { + header('Location: /install.php');} + + ///////////////////////////////////初始化配置文件start////////////////////////////////////// + if($配置文件["drivestype"]=="cn"){ + + onedrive::$api_url = "https://microsoftgraph.chinacloudapi.cn/v1.0"; + onedrive::$oauth_url = "https://login.partner.microsoftonline.cn/common/oauth2/v2.0"; + }else{ + onedrive::$api_url = "https://graph.microsoft.com/v1.0"; + onedrive::$oauth_url = "https://login.microsoftonline.com/common/oauth2/v2.0"; + } + onedrive::$client_id = $配置文件["client_id"]; + onedrive::$client_secret =$配置文件["client_secret"]; + onedrive::$redirect_uri = $配置文件["redirect_uri"]; + //onedrive::$api_url = $配置文件["api_url"]; + // onedrive::$oauth_url = $配置文件["oauth_url"]; + onedrive::$typeurl=$配置文件["api"] ; + onedrive::$access_token=access_token($配置文件,$驱动器); + if(!is_login()){ + if($配置文件["share"]=="false"){ + echo "管理员可见";exit; + }} + //global $当前目录id; +// $当前目录id=onedrive::pathtoid($配置文件["access_token"],$请求路径); +if($_GET["this"]=="path") +{ + + echo $当前目录id=onedrive::pathtoid($配置文件["access_token"],$请求路径); + exit; + + +} +////////////文件管理//////////////////////////// +if($_GET["filemanger"]=="move") +{ + + $id=($_GET["id"]); + $id=str_replace("\"","",$id); + $id=str_replace("[","",$id); + $id=str_replace("]","",$id); + + $ids=explode(",",$id); + var_dump($ids); + $newid=$_GET["newid"]; + onedrive::批量移动($ids,$newid); + + + exit; + + + +} +if($_GET["downid"]) +{ + onedrive::downloadbyid($_GET["downid"]) ; + exit; + +} +//新建文件夹 +if($_GET["create_folder"]) +{ + onedrive::create_folder( $请求路径,$_GET["create_folder"]); + exit; +} +//删 +if($_GET["delitem"]) +{$ss=$_GET["delitem"]; + var_dump($ss);exit; + onedrive::delete($_GET["delitem"]); + exit; +} +//改 + +if($_GET["rename"]){ + onedrive::rename($_GET["rename"],$_GET["name"]); + exit; +} +//上传 +// var_dump($_SERVER["REQUEST_URI"]); +// echo $_GET["action"]; +if ($_GET["action"]=="upbigfile") +{ + $filename= $_GET['upbigfilename']; + $path=$请求路径.$filename; + $path = onedrive::urlencode($path); + $path = empty($path)?'/':":/{$path}:/"; + $token=$配置文件["access_token"]; + $request['headers'] = "Authorization: bearer {$token}".PHP_EOL."Content-Type: application/json".PHP_EOL; + $request['url']= $配置文件["api"].$path."createUploadSession"; + $request['post_data'] = '{"item": {"@microsoft.graph.conflictBehavior": "rename"}}'; + $resp = fetch::post($request); + $data = json_decode($resp->content, true); + if($resp->http_code == 409){ + return false; + } + + echo $resp->content; + + exit; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + //分页页数 + $this->z_page = 100; + + + + + $paths = explode('/', rawurldecode($请求路径)); + + if(substr($_SERVER['REQUEST_URI'], -1) != '/'){ $this->name = array_pop($paths); } - $this->url_path = get_absolute_path(join('/', $paths)); - $this->path = get_absolute_path(config('onedrive_root').$this->url_path); + + preg_match_all("(\.page\-([0-9]*)/$)",get_absolute_path(join('/', $paths)),$mat); + if(empty($mat[1][0])){ + $this->page = 1; + } else { + $this->page = $mat[1][0]; + + } + $this->page=$_GET["page"]??"1"; + $this->url_path = preg_replace("(\.page\-[0-9]*/$)","",get_absolute_path(join('/', $paths))); + + $this->path = get_absolute_path(config('onedrive_root').$this->url_path); //获取文件夹下所有元素 $this->items = $this->items($this->path); } - + + + function index(){ + + + + + //验证缓存是否异常 + $this->checkcache(); + //是否404 $this->is404(); $this->is_password(); - - header("Expires:-1"); - header("Cache-Control:no_cache"); - header("Pragma:no-cache"); + + //header("Expires:-1"); + // header("Cache-Control:no_cache"); + // header("Pragma:no-cache"); if(!empty($this->name)){//file return $this->file(); }else{//dir return $this->dir(); } + + + } + + function checkcache(){ + if(file_exists(ROOT."config/".self::$驱动器.".php")){ + if ($this->path=="/"){ + if($this->items==NUll){ + echo " "; + if (function_exists('opcache_reset')) { + opcache_reset(); + } + // oneindex::refresh_cache(self::$请求路径); + // header("refresh: 1"); + echo' + + + '; + exit; + } + + } +}else{ + http_response_code(404); + view::load('404')->show(); + die(); +} + + + } //判断是否加密 function is_password(){ if(empty($this->items['.password'])){ @@ -44,7 +278,7 @@ function is_password(){ $this->items['.password']['path'] = get_absolute_path($this->path).'.password'; } - $password = $this->get_content($this->items['.password']); + $password = $this->get_content2($this->items['.password']); list($password) = explode("\n",$password); $password = trim($password); unset($this->items['.password']); @@ -57,7 +291,8 @@ function is_password(){ } function password($password){ - if(!empty($_POST['password']) && strcmp($password, $_POST['password']) === 0){ + if(!empty($_REQUEST['password']) && strcmp($password, $_REQUEST['password']) === 0){ + setcookie(md5($this->path), $_POST['password']); return true; } @@ -69,14 +304,22 @@ function password($password){ //文件 function file(){ $item = $this->items[$this->name]; - if ($item['folder']) {//是文件夹 + if ($item['folder']) {//是文件 + + + + $url = $_SERVER['REQUEST_URI'].'/'; }elseif(!is_null($_GET['t']) ){//缩略图 $url = $this->thumbnail($item); - }elseif($_SERVER['REQUEST_METHOD'] == 'POST' || !is_null($_GET['s']) ){ + }elseif($_SERVER['REQUEST_METHOD'] == 'POST' || !is_null($_GET['s']) ){ return $this->show($item); }else{//返回下载链接 - $url = $item['downloadUrl']; + if (config('proxy_domain') != ""){ + $url = str_replace(config('main_domain'),config('proxy_domain'),$item['downloadUrl']); + }else { + $url = $item['downloadUrl']; + } } header('Location: '.$url); } @@ -98,7 +341,7 @@ function dir(){ if($this->items['README.md']){ $this->items['README.md']['path'] = get_absolute_path($this->path).'README.md'; - $readme = $this->get_content($this->items['README.md']); + $readme = $this->get_content2($this->items['README.md']); $Parsedown = new Parsedown(); $readme = $Parsedown->text($readme); //不在列表中展示 @@ -107,19 +350,27 @@ function dir(){ if($this->items['HEAD.md']){ $this->items['HEAD.md']['path'] = get_absolute_path($this->path).'HEAD.md'; - $head = $this->get_content($this->items['HEAD.md']); + $head = $this->get_content2($this->items['HEAD.md']); $Parsedown = new Parsedown(); $head = $Parsedown->text($head); //不在列表中展示 unset($this->items['HEAD.md']); } - return view::load('list')->with('title', 'index of '. urldecode($this->url_path)) + + $this->totalpage = ceil(count($this->items) / $this->z_page); + + if($this->page*$this->z_page >= count($this->items)) + $this->page = $this->totalpage; + + return view::load('list')->with('title', config('title_name')) ->with('navs', $navs) - ->with('path',join("/", array_map("rawurlencode", explode("/", $this->url_path))) ) + ->with('path',join("/", array_map("rawurlencode", explode("/", $this->url_path)))) ->with('root', $root) - ->with('items', $this->items) + ->with('items', array_slice($this->items,$this->z_page*($this->page-1),$this->z_page)) ->with('head',$head) - ->with('readme',$readme); + ->with('readme',$readme) + ->with('page',$this->page) + ->with('totalpage',$this->totalpage)->with('驱动器',self::$驱动器)->with('请求路径',self::$请求路径); } function show($item){ @@ -137,7 +388,10 @@ function show($item){ $show = config('show'); foreach($show as $n=>$exts){ - if(in_array($ext,$exts)){ + if ($ext == 'pdf'){ + return view::load('show/pdf')->with($data); + } + elseif(in_array($ext,$exts)){ return view::load('show/'.$n)->with($data); } } @@ -182,17 +436,51 @@ function navs(){ return $navs; } - static function get_content($item){ + + + + + + + + static function get_content2($item){ + $content = cache::get('content_'.$item['path'], function() use ($item){ + $resp = fetch::get($item['downloadUrl']); + if($resp->http_code == 200){ + return $resp->content; + } + }, config('cache_expire_time') ); + return $content; + } + + + + +static function get_content($item){ $content = cache::get('content_'.$item['path'], function() use ($item){ + + $resp = fetch::get($item['downloadUrl']); if($resp->http_code == 200){ + return ' +'; return $resp->content; } }, config('cache_expire_time') ); return $content; } - //时候404 + + //404 function is404(){ if(!empty($this->items[$this->name]) || (empty($this->name) && is_array($this->items)) ){ return false; diff --git a/controller/IndexController.php.bak b/controller/IndexController.php.bak new file mode 100644 index 0000000..93a1192 --- /dev/null +++ b/controller/IndexController.php.bak @@ -0,0 +1,249 @@ +name = array_pop($paths); + } + $this->url_path = get_absolute_path(join('/', $paths)); + $this->path = get_absolute_path(config('onedrive_root').$this->url_path); + //获取文件夹下所有元素 + $this->items = $this->items($this->path); + } + + + function islogin(){ + + + + + if (!isset($_COOKIE['username'])) { + exit(""); +} + } + function index(){ + //是否404 + + $this->is404(); + // $this->islogin(); + + $this->is_password(); + + header("Expires:-1"); + header("Cache-Control:no_cache"); + header("Pragma:no-cache"); + + if(!empty($this->name)){//file + return $this->file(); + }else{//dir + return $this->dir(); + } + } + + //判断是否加密 + function is_password(){ + if(empty($this->items['.password'])){ + return false; + }else{ + $this->items['.password']['path'] = get_absolute_path($this->path).'.password'; + } + + $password = $this->get_content($this->items['.password']); + list($password) = explode("\n",$password); + $password = trim($password); + unset($this->items['.password']); + if(!empty($password) && strcmp($password, $_COOKIE[md5($this->path)]) === 0){ + return true; + } + + $this->password($password); + + } + + function password($password){ + if(!empty($_POST['password']) && strcmp($password, $_POST['password']) === 0){ + setcookie(md5($this->path), $_POST['password']); + return true; + } + $navs = $this->navs(); + echo view::load('password')->with('navs',$navs); + exit(); + } + + + function file(){ + + $item = $this->items[$this->name]; + if ($item['folder']) {//是文件夹 + $url = $_SERVER['REQUEST_URI'].'/'; + }elseif(!is_null($_GET['t']) ){//缩略图 + $url = $this->thumbnail($item); + }elseif($_SERVER['REQUEST_METHOD'] == 'POST' || !is_null($_GET['s']) ){ + return $this->show($item); + }else{//返回下载链接 + + // if (!isset($_COOKIE['openid'])) { + // $go='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; + // $url='/login.php?goto='.$go; + // }else{ + + $url = $item['downloadUrl'];} + + // } + header('Location: '.$url); + } + + + + //文件夹 + function dir(){ + $root = get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).config('root_path'); + $navs = $this->navs(); + + if($this->items['index.html']){ + $this->items['index.html']['path'] = get_absolute_path($this->path).'index.html'; + $index = $this->get_content($this->items['index.html']); + header('Content-type: text/html'); + echo $index; + exit(); + } + + if($this->items['README.md']){ + $this->items['README.md']['path'] = get_absolute_path($this->path).'README.md'; + $readme = $this->get_content($this->items['README.md']); + $Parsedown = new Parsedown(); + $readme = $Parsedown->text($readme); + //不在列表中展示 + unset($this->items['README.md']); + } + + if($this->items['HEAD.md']){ + $this->items['HEAD.md']['path'] = get_absolute_path($this->path).'HEAD.md'; + $head = $this->get_content($this->items['HEAD.md']); + $Parsedown = new Parsedown(); + $head = $Parsedown->text($head); + //不在列表中展示 + unset($this->items['HEAD.md']); + } + return view::load('list')->with('title', 'index of '. urldecode($this->url_path)) + ->with('navs', $navs) + ->with('path',join("/", array_map("rawurlencode", explode("/", $this->url_path))) ) + ->with('root', $root) + ->with('items', $this->items) + ->with('head',$head) + ->with('readme',$readme); + } + + function show($item){ + $root = get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).(config('root_path')?'?/':''); + $ext = strtolower(pathinfo($item['name'], PATHINFO_EXTENSION)); + $data['title'] = $item['name']; + $data['navs'] = $this->navs(); + $data['item'] = $item; + $data['ext'] = $ext; + $data['item']['path'] = get_absolute_path($this->path).$this->name; + $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://'; + $uri = onedrive::urlencode(get_absolute_path($this->url_path.'/'.$this->name)); + $data['url'] = $http_type.$_SERVER['HTTP_HOST'].$root.$uri; + + + $show = config('show'); + foreach($show as $n=>$exts){ + if(in_array($ext,$exts)){ + return view::load('show/'.$n)->with($data); + } + } + + + header('Location: '.$item['downloadUrl']); + } + //缩略图 + function thumbnail($item){ + if(!empty($_GET['t'])){ + list($width, $height) = explode('|', $_GET['t']); + }else{ + //800 176 96 + $width = $height = 800; + } + $item['thumb'] = onedrive::thumbnail($this->path.$this->name); + list($item['thumb'],$tmp) = explode('&width=', $item['thumb']); + $item['thumb'] .= strpos($item['thumb'], '?')?'&':'?'; + return $item['thumb']."width={$width}&height={$height}"; + } + + //文件夹下元素 + function items($path, $fetch=false){ + $items = cache::get('dir_'.$this->path, function(){ + return onedrive::dir($this->path); + }, config('cache_expire_time')); + return $items; + } + + function navs(){ + $root = get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).config('root_path'); + $navs['/'] = get_absolute_path($root.'/'); + foreach(explode('/',$this->url_path) as $v){ + if(empty($v)){ + continue; + } + $navs[rawurldecode($v)] = end($navs).$v.'/'; + } + if(!empty($this->name)){ + $navs[$this->name] = end($navs).urlencode($this->name); + } + + return $navs; + } + + static function get_content($item){ + $content = cache::get('content_'.$item['path'], function() use ($item){ + $resp = fetch::get($item['downloadUrl']); + if($resp->http_code == 200){ + return $resp->content; + } + }, config('cache_expire_time') ); + return $content; + } + + //时候404 + function is404(){ + if(!empty($this->items[$this->name]) || (empty($this->name) && is_array($this->items)) ){ + return false; + } + + http_response_code(404); + view::load('404')->show(); + die(); + } + + function __destruct(){ + if (!function_exists("fastcgi_finish_request")) { + return; + } + } +} diff --git a/controller/UploadController.php b/controller/UploadController.php index 4a21492..e670e2a 100644 --- a/controller/UploadController.php +++ b/controller/UploadController.php @@ -3,6 +3,8 @@ class UploadController{ function index(){ + + if($_POST['upload'] == 1){ $local = realpath($_POST['local']); $remotepath = get_absolute_path($_POST['remote']); @@ -98,7 +100,7 @@ function run(){ } private function task_request($remotepath=''){ - $request['headers'] = "Cookie: admin=".md5(config('password').config('refresh_token')).PHP_EOL; + $request['headers'] = "Cookie: admin=".config('password').PHP_EOL; $request['headers'] .= "Host: ".$_SERVER['HTTP_HOST']; $request['curl_opt']=[CURLOPT_CONNECTTIMEOUT => 1,CURLOPT_TIMEOUT=>1,CURLOPT_FOLLOWLOCATION=>true]; $http_type = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://'; @@ -186,7 +188,7 @@ function upload_large_file($task){ } $request= $this->task_request($task['remotepath']); $resp = fetch::post($request); - //var_dump($resp); + var_dump($resp); } diff --git a/curl.php b/curl.php new file mode 100644 index 0000000..4b16db1 --- /dev/null +++ b/curl.php @@ -0,0 +1,81 @@ + + $url) { + + $timeout=20; + $ch[$nch] = curl_init(); + curl_setopt_array($ch[$nch], array( + CURLOPT_URL => $url, + CURLOPT_TIMEOUT => $timeout, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_MAXREDIRS => 10, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "PATCH", + CURLOPT_POSTFIELDS =>"{\n \"name\": \"".$itemid."\"\n}", + CURLOPT_HTTPHEADER => array( + "Authorization: Bearer ".$token, + "Content-Type: application/json" + ), + + )); + + curl_multi_add_handle($mh, $ch[$nch]); + ++$nch; + + } + + /* wait for performing request */ + + do { + $mrc = curl_multi_exec($mh, $running); + } while (CURLM_CALL_MULTI_PERFORM == $mrc); + + while ($running && $mrc == CURLM_OK) { + // wait for network + if (curl_multi_select($mh, 0.5) > -1) { + // pull in new data; + do { + $mrc = curl_multi_exec($mh, $running); + } while (CURLM_CALL_MULTI_PERFORM == $mrc); + } + + } + + if ($mrc != CURLM_OK) { + error_log("CURL Data Error"); + } + + /* get data */ + + $nch = 0; + + foreach ($urlarr as $moudle=>$node) { + if (($err = curl_error($ch[$nch])) == '') { + $res[$nch]=curl_multi_getcontent($ch[$nch]); + $result[$moudle]=$res[$nch]; + }else{ + error_log("curl error"); + + } + + curl_multi_remove_handle($mh,$ch[$nch]); + curl_close($ch[$nch]); + ++$nch; + } + + curl_multi_close($mh); + echo "批量处理完成"; + return $result; + +} + + + diff --git a/del.php b/del.php new file mode 100644 index 0000000..e8e91ce --- /dev/null +++ b/del.php @@ -0,0 +1,35 @@ + + + + + 恭喜,站点创建成功! + + + +
+

恭喜, 站点创建成功!

+

这是默认index.html,本页面由系统自动生成

+ +
+ + \ No newline at end of file diff --git a/index.php b/index.php index 54a37de..de5dbae 100644 --- a/index.php +++ b/index.php @@ -1,96 +1,100 @@ extractTo('composer'); -/** - * 程序安装 - */ -if( empty( config('refresh_token') ) ){ - route::any('/','AdminController@install'); + + +//var_dump(onedrive::test("me/drive/root/children")); + + + + +if (!file_exists(ROOT.'config/base.php') or !file_exists(ROOT.'config/default.php') ) { + header('Location: /install.php'); + exit; } -/** +switch($_SERVER["REQUEST_METHOD"]){ + case "GET": + break; + case "POST": + break; + default: + // route::any('{path:#all}', 'ApiController@'.$_SERVER["REQUEST_METHOD"]);exit; + require_once(ROOT."lib/api.php"); + exit; + +} + + + + + + + + + +/* * 系统后台 + */ -route::group(function(){ - return ($_COOKIE['admin'] == md5(config('password').config('refresh_token')) ); -},function(){ - route::get('/logout','AdminController@logout'); - route::any('/admin/','AdminController@settings'); - route::any('/admin/cache','AdminController@cache'); - route::any('/admin/show','AdminController@show'); - route::any('/admin/setpass','AdminController@setpass'); - route::any('/admin/images','AdminController@images'); - - route::any('/admin/upload','UploadController@index'); - //守护进程 - route::any('/admin/upload/run','UploadController@run'); - //上传进程 - route::post('/admin/upload/task','UploadController@task'); +route::group(function () { + return $_COOKIE['admin'] == config('password'); +}, function () { + route::get('/logout', 'AdminController@logout'); + route::any('/admin/', 'AdminController@settings'); + route::any('/admin/cache', 'AdminController@cache'); + route::any('/admin/show', 'AdminController@show'); + route::any('/admin/setpass', 'AdminController@setpass'); + route::any('/admin/images', 'AdminController@images'); + route::any('/admin/drives', 'AdminController@drives'); + route::any('/admin/sharepoint', 'AdminController@sharepoint'); + // route::any('/admin/upload', 'UploadController@index'); + //守护进程 + route::any('/admin/upload/run', 'UploadController@run'); + //上传进程 + route::post('/admin/upload/task', 'UploadController@task'); }); //登陆 -route::any('/login','AdminController@login'); +route::any('/login', 'AdminController@login'); //跳转到登陆 -route::any('/admin/',function(){ - return view::direct(get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).'?/login'); +route::any('/admin/', function () { + return view::direct(get_absolute_path(dirname($_SERVER['SCRIPT_NAME'])).'?/login'); }); - - -define('VIEW_PATH', ROOT.'view/'.(config('style')?config('style'):'material').'/'); +define('VIEW_PATH', ROOT.'view/'.(config('style') ? config('style') : 'nexmoe').'/'); /** - * OneImg + * OneImg. */ $images = config('images@base'); -if( ($_COOKIE['admin'] == md5(config('password').config('refresh_token')) || $images['public']) ){ - route::any('/images','ImagesController@index'); - if($images['home']){ - route::any('/','ImagesController@index'); - } +if (($_COOKIE['admin'] == config('password') || $images['public'])) { + route::any('/'.$驱动器.'/images', 'ImagesController@index'); + if ($images['home']) { + route::any('/', 'ImagesController@index'); + } } -/** - * 列目录 - */ -route::group(function () { - $hotlink = config('onedrive_hotlink'); - - // 未启用防盗链 - if (!$hotlink) { - return true; - } - // referer 不存在 - if (!isset($_SERVER['HTTP_REFERER'])) { - return true; - } - - $referer_domain = get_domain($_SERVER['HTTP_REFERER']); - // 当前域本身 - if (str_is(get_domain(), $referer_domain)) { - return true; - } - - // 白名单 - $hotlinks = explode(';', $hotlink); - $referer = false; - - foreach ($hotlinks as $_hotlink) { - if (str_is(trim($_hotlink), $referer_domain)) { - $referer = true; - } - } - if (!$referer) { - header('HTTP/1.1 403 Forbidden'); - } - - return $referer; -}, function() { - route::any('{path:#all}','IndexController@index'); -}); + + + + //route::any('/{path:#all}/items/', 'ImagesController@index'); +route::any('{path:#all}', 'IndexController@index'); + +$etime=microtime(true);//获取程序执行结束的时间 + +$total=$etime-$stime; //计算差值 + +?> +php 运行时间 + + + + + diff --git a/init.php b/init.php index 16b99c6..9ede22f 100644 --- a/init.php +++ b/init.php @@ -1,9 +1,14 @@ +    +    + '; + exit; + } + echo $api=$配置文件["api_url"].'/sites/'.$siteidurl.'/drive/root'; + + config("api@".$驱动器,$api); + echo "配置sharepoint成功
"; + echo '授权成功'; + cache::refresh_cache(get_absolute_path(config('onedrive_root'))); + cache::clear_opcache(); + + exit; + } + + ///////////////////已经授权//////////////// + if($token ["refresh_token"]!=="")//已经授权 + { + if($token['expires_on'] > time()+600){ + return $token['access_token']; + }else + { + $refresh_token = $token['refresh_token']; + $newtoken =get_token($配置文件); + + if(!empty($newtoken['refresh_token'])) + { + $配置文件["expires_on"] = time()+ $newtoken['expires_in']; + $配置文件["access_token"]=$newtoken["access_token"]; + $配置文件["refresh_token"]=$newtoken["refresh_token"]; + config('@'.$驱动器, $配置文件); + return $token['access_token']; + } + } + + + + + + + } + + + + + ///////////////////未授权//////////////// + if($token ["refresh_token"]=="")//未授权 + { + + if($_GET["code"]){ + $code= $_GET["code"]; + $驱动器=str_replace("?code=".$code,"",$驱动器); + $配置文件=config("@".$驱动器); + $client_id = $配置文件["client_id"]; + $client_secret = $配置文件["client_secret"]; + $redirect_uri = $配置文件["redirect_uri"]; + $授权url = $配置文件["oauth_url"]."/token"; + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => $授权url , + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => "code=".$_GET["code"]."&grant_type=authorization_code&client_id=".$client_id."&client_secret=".$client_secret."&redirect_uri=https%3A//coding.mxin.ltd", + CURLOPT_HTTPHEADER => array( + "SdkVersion: postman-graph/v1.0", + "client_secret:" .$client_secret, + "code: ".$_GET["code"], + "redirect_uri: https://coding.mxin.ltd", + "Content-Type: application/x-www-form-urlencoded", + "grant_type: authorization_code", ), + )); + + $response = curl_exec($curl); + + curl_close($curl); + $response=json_decode($response,true); + $response; + if(!empty($response["refresh_token"])){ + config("refresh_token@".$驱动器,$response["refresh_token"]); + config("access_token@".$驱动器,$response["access_token"]); + + + $地址=str_replace("?code=".$code,"",$_SERVER["REQUEST_URI"]); + + echo '授权成功'; + echo "是否启用Sharepoint"; + echo '
+    +    +
'; + + cache::refresh_cache(get_absolute_path(config('onedrive_root'))); + + // 清除php文件缓存 + cache::clear_opcache(); + + + exit; + + }else{echo "授权失败";} + + }else //生成授权地址 + { + + + + +if($配置文件["oauth_url"]==""){return; + +}else{ +if(!is_login()){echo " 未登陆"; +echo '登陆'; +exit;} + + $oauthurl=$配置文件["oauth_url"]; + $client_id=$配置文件["client_id"]; + if ($_SERVER["REQUEST_URI"]=="/"){ + $_SERVER["REQUEST_URI"]="/default"; + } + $redirect_uri=urlencode("http://" .$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]); + $授权地址= $oauthurl."/authorize?client_id=".$client_id."&scope=offline_access+files.readwrite.all+Sites.ReadWrite.All&response_type=code&redirect_uri=https://coding.mxin.ltd&state=".$redirect_uri; + echo '授权应用'; + cache::refresh_cache(get_absolute_path(config('onedrive_root'))); + if(!is_login()){echo " 未登陆"; + echo '登陆'; + exit;} + // 清除php文件缓存 + cache::clear_opcache(); + +} + +exit; + + + + + + } + + + + + +} + + + + return $token['access_token']; + + + //endsub + } + + + + + + + + +} + + + if (!function_exists("get_token")){ +function get_token($配置文件=array()){ + $oauth_url=$配置文件["oauth_url"]; + $client_id=$配置文件["client_id"]; + $redirect_uri=$配置文件["redirect_uri"]; + $client_secret=$配置文件["client_secret"]; + $refresh_token=$配置文件["refresh_token"]; + + $request['url'] = $oauth_url."/token"; + $request['post_data'] = "client_id={$client_id}&redirect_uri={$redirect_uri}&client_secret={$client_secret}&refresh_token={$refresh_token}&grant_type=refresh_token"; + + $request['headers']= "Content-Type: application/x-www-form-urlencoded"; + $resp = fetch::post($request); + if($resp->http_code=="200"){ + $data = json_decode($resp->content, true); + + return $data; + } + else{ + //echo $resp->http_code."错误";exit; + } + + } + +} + +////////////////////////////////////// + -// cache -define('CACHE_PATH', ROOT.'cache/'); -cache::$type = empty( config('cache_type') )?'secache':config('cache_type'); if (!function_exists('db')) { @@ -95,40 +311,20 @@ function e($str) { } } -if (!function_exists('str_is')) { - function str_is($pattern, $value) - { - if (is_null($pattern)) { - $patterns = []; - } - $patterns = ! is_array($pattern) ? [$pattern] : $pattern; - if (empty($patterns)) { - return false; - } - foreach ($patterns as $pattern) { - if ($pattern == $value) { - return true; - } - $pattern = preg_quote($pattern, '#'); - $pattern = str_replace('\*', '.*', $pattern); - if (preg_match('#^'.$pattern.'\z#u', $value) === 1) { - return true; - } - } - return false; - } -} -if (!function_exists('get_domain')) { - function get_domain($url=null) - { - if (is_null($url)) { - return $_SERVER['HTTP_HOST']; - } - return strstr(ltrim(strstr($url, '://'), '://'), '/', true); - } +if(!function_exists("is_login")){ + + + function is_login(){ + if ($_COOKIE["admin"]==config("password")){return true;}else{ + + return false; + + } + + + } } - function get_absolute_path($path) { $path = str_replace(array('/', '\\', '//'), '/', $path); $parts = array_filter(explode('/', $path), 'strlen'); @@ -144,7 +340,72 @@ function get_absolute_path($path) { return str_replace('//','/','/'.implode('/', $absolutes).'/'); } -!defined('CONTROLLER_PATH') && define('CONTROLLER_PATH', ROOT.'controller/'); -onedrive::$client_id = config('client_id'); -onedrive::$client_secret = config('client_secret'); -onedrive::$redirect_uri = config('redirect_uri'); \ No newline at end of file + + + + + + + + +function splitlast($str, $split) +{ + $len = strlen($split); + $pos = strrpos($str, $split); + if ($pos===false) { + $tmp[0] = $str; + $tmp[1] = ''; + } elseif ($pos>0) { + $tmp[0] = substr($str, 0, $pos); + $tmp[1] = substr($str, $pos+$len); + } else { + $tmp[0] = ''; + $tmp[1] = substr($str, $len); + } + return $tmp; +} + +/////// + + +function check_version(){ + return fetch::get('https://pan.mxin.ltd/version.json')->content; + +} + + +/* +$ss= check_version(); + + +if(SOFTVERSION<$ss) +{ini_set('memory_limit', '228M'); + $curl = curl_init(); +//设置抓取的url +curl_setopt($curl, CURLOPT_URL, "https://pan.mxin.ltd/ondindex-9.21.tar.gz"); +//打开文件描述符 +$fp = fopen (ROOT."9.21.tar.gz", 'w+'); +curl_setopt($curl, CURLOPT_FILE, $fp); +//这个选项是意思是跳转,如果你访问的页面跳转到另一个页面,也会模拟访问。 +curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); +curl_setopt($curl,CURLOPT_TIMEOUT,70); + +//执行命令 +curl_exec($curl); +//关闭URL请求 +curl_close($curl); +//关闭文件描述符 +fclose($fp); + + + + echo "当前版本".SOFTVERSION; + echo " 最新版本".$ss; + + $phar = new PharData('9.21.tar.gz'); + $phar->extractTo('./', null, true); + + exit; +} + +*/ \ No newline at end of file diff --git a/install.php b/install.php new file mode 100644 index 0000000..dd74443 --- /dev/null +++ b/install.php @@ -0,0 +1,249 @@ + 'OneIndex', + 'title_name' => 'Index of /', + + 'password' => 'oneindex', + 'drawer' => '
', + 'style' => 'nexmoe', + 'onedrive_root' => '', + 'cache_type' => 'filecache', + 'cache_expire_time' => 3600, + 'cache_refresh_time' => 600, + 'page_item' => 50, + 'root_path' => '', + 'show' => array( + 'stream' => ['txt'], + 'image' => ['bmp', 'jpg', 'jpeg', 'png', 'gif', 'webp'], + 'video5' => [], + 'video' => ['mpg', 'mpeg', 'mov', 'flv', 'mp4', 'webm', 'mkv', 'm3u8'], + 'video2' => ['avi', 'rm', 'rmvb', 'wmv', 'asf', 'ts'], + 'audio' => ['ogg', 'mp3', 'wav', 'flac', 'aac', 'm4a', 'ape'], + 'code' => ['html', 'htm', 'php', 'css', 'go', 'java', 'js', 'json', 'txt', 'sh', 'md'], + 'doc' => ['csv', 'doc', 'docx', 'odp', 'ods', 'odt', 'pot', 'potm', 'potx', 'pps', 'ppsx', 'ppsxm', 'ppt', 'pptm', 'pptx', 'rtf', 'xls', 'xlsx'], + ), + 'images' => ['home' => false, 'public' => false, 'exts' => ['jpg', 'png', 'gif', 'bmp']], + ); + + config("@base",$default_config); + setcookie("admin","oneindex"); + header("refresh: 2"); + echo "初始化成功"; + exit; + } + + + + ///////////////// 权限认证///////////// + + + if($_COOKIE["admin"] !==config("password@base")) + {echo '登陆'; + die("未授权");} + + + + + + + + + + + + + + + + + + + +if($_GET["filename"]) +{ + if($_GET["drivestype"]=="cn"){ + $data=array( + +'drivestype' => 'cn', + 'client_secret' => 'v4[Nq:4=rmFS78BwYi[@x3sGk-iY.U:S', + 'client_id' => '3447f073-eef3-4c60-bb68-113a86f2c39a', + 'redirect_uri' => 'https://coding.mxin.ltd/' , + 'api' => 'https://microsoftgraph.chinacloudapi.cn/v1.0/me/drive/root', + 'api_url' => 'https://microsoftgraph.chinacloudapi.cn/v1.0', + 'oauth_url' => 'https://login.partner.microsoftonline.cn/common/oauth2/v2.0', + ); + + + }elseif($_GET["drivestype"]=="us"){ + $data=array( + +'drivestype' => 'us', + 'client_secret' => '~ZkpvnVoMysK36v0_Og1EPp.l3JA_NY-9a', + 'client_id' => '02be423f-f28c-48de-b265-09327e1a04eb', + 'redirect_uri' => 'https://coding.mxin.ltd/' , + 'api' => 'https://graph.microsoft.com/v1.0/me/drive/root', + 'api_url' => 'https://graph.microsoft.com/v1.0', + 'oauth_url' => 'https://login.microsoftonline.com/common/oauth2/v2.0', + + + + + + ); + + + + } + + + + if(!file_exists(ROOT."config/default.php")) + { + $_GET["filename"]="default"; + } + + + + config("@".$_GET["filename"],$data); + + echo "配置成功点此授权"; +echo "配置成功点此授权"; + + + exit; +} + + + +?> + + + + + + OneIndex 系统安装 + + + + + +
+
+ OneIndex + +
+
+ +
+ + +
+
+

系统安装

+
+ + + + + +
+ + + + + + +
+
+ + +
名称只能是英文
+ + + + + + +
+ 上一步 + + + +
+
+ + + + + + + + diff --git a/lib/BasicCallBack.php b/lib/BasicCallBack.php new file mode 100644 index 0000000..6822f50 --- /dev/null +++ b/lib/BasicCallBack.php @@ -0,0 +1,49 @@ +callBack = $callBack; + $this->realm = 'CloudreveWebDav'; + + } + + + public function getDigestHash($realm, $username){ + $cb = $this->callBack; + return $cb($realm,$username); + } + + + + + + + + + + + + + + + + +} \ No newline at end of file diff --git a/lib/DavAuth.php b/lib/DavAuth.php new file mode 100644 index 0000000..9ed4ee0 --- /dev/null +++ b/lib/DavAuth.php @@ -0,0 +1,22 @@ +uid = 123456; + } + + public function __invoke($realm,$um){ + + return "123456"; + } + +} + +?> \ No newline at end of file diff --git a/lib/Directory.php b/lib/Directory.php new file mode 100644 index 0000000..7916f5f --- /dev/null +++ b/lib/Directory.php @@ -0,0 +1,190 @@ +uid = $ex[0]; + if(empty($this->uid)){ + return false; + } + $t = strpos($path,$this->uid); + if($t == 0){ + $this->myPath = substr($path,$t+strlen($this->uid)); + }else{ + $this->myPath = $path; + } + $this->myPath = empty($this->myPath) ? "/" : $this->myPath; + } + + function createFile($name, $data = NULL){ + $name = str_replace(" ","",$name); + $userData = Db::name("users")->where("id",$this->uid)->find(); + $groupData = Db::name("groups")->where("id",$userData["user_group"])->find(); + $policyData = Db::name("policy")->where("id",$groupData["policy_name"])->find(); + $uploadHandle = new UploadHandler($groupData["policy_name"],$this->uid); + $allowedExt = UploadHandler::getAllowedExt(json_decode($policyData["filetype"],true)); + if(!empty($allowedExt)){ + $ex = explode(".",$name); + $fileSuffix = end($ex); + if(!in_array($fileSuffix, explode(",",$allowedExt))){ + throw new DAV\Exception\InvalidResourceType('File type not allowed'); + } + } + if($policyData["policy_type"] !="local"){ + throw new DAV\Exception\Forbidden('Poliyc not supported yet'); + } + $fileSize = fstat($data)["size"]; + if(empty($fileSize)){ + $fileSize = -1; + } + if($fileSize>$policyData["max_size"]){ + throw new DAV\Exception\InsufficientStorage('File is to large'); + } + if(!FileManage::sotrageCheck($this->uid,$fileSize)){ + throw new DAV\Exception\InsufficientStorage('Quota is not enough'); + } + if($policyData['autoname']){ + $fileName = $uploadHandle->getObjName($policyData['namerule'],"local",$name); + }else{ + $fileName = $name; + } + $generatePath = $uploadHandle->getDirName($policyData['dirrule']); + $savePath = ROOT_PATH . 'public/uploads/'.$generatePath; + if(!file_exists($savePath)){ + mkdir($savePath,0777,true); + } + file_put_contents($savePath."/".$fileName, $data); + if($fileSize<=0){ + $fileSize = filesize($savePath."/".$fileName); + } + $jsonData = array( + "path" => str_replace("/",",",ltrim($this->myPath,"/")), + "fname" => $name, + "objname" => $generatePath."/".$fileName, + "fsize" => $fileSize, + ); + @list($width, $height, $type, $attr) = getimagesize(rtrim($savePath, DS).DS.$fileName); + $picInfo = empty($width)?" ":$width.",".$height; + $addAction = FileManage::addFile($jsonData,$policyData,$this->uid,$picInfo); + if(!$addAction[0]){ + unlink($savePath."/".$fileName); + throw new DAV\Exception\Conflict($addAction[1]); + } + FileManage::storageCheckOut($this->uid,$jsonData["fsize"]); + //echo json_encode(array("key" => $info["name"])); + } + + function getQuotaInfo() { + $this->userObj = new User($this->uid,"",true); + $quotaInfo = json_decode($this->userObj->getMemory(true),true); + return [ + $quotaInfo["used"], + $quotaInfo["total"] + ]; + + } + + function setName($name){ + $reqPath = $this->myPath; + $ex = explode("/",$reqPath); + $newPath = rtrim(dirname($reqPath) == "\\" ?"/":dirname($reqPath),"/")."/".$name; + $renameAction = json_decode(FileManage::RenameHandler($reqPath,$newPath,$this->uid,true),true); + if(!$renameAction["result"]["success"]){ + throw new DAV\Exception\InvalidResourceType($renameAction["result"]["error"]); + } + } + + function getChildren() { + $children = array(); + $fileList = Db::name('files')->where('upload_user',$this->uid)->where('dir',$this->myPath)->select(); + $dirList = Db::name('folders')->where('owner',$this->uid)->where('position',$this->myPath)->select(); + foreach($fileList as $node) { + // Ignoring files staring with . + $children[] = $this->getChildFile($node,false); + } + foreach($dirList as $node) { + // Ignoring files staring with . + $children[] = $this->getChildDir($node,true); + } + return $children; + } + + function getChildFile($name){ + $path = $this->uid.rtrim($this->myPath,"/") . '/' . $name["orign_name"]; + return new Objects($path); + } + + function getChildDir($name){ + $path = $this->uid.rtrim($this->myPath,"/") . '/' . $name["folder_name"]; + return new Directory($path); + } + + function delete(){ + foreach ($this->getChildren() as $child) $child->delete(); + FileManage::DirDeleteHandler([0=>$this->myPath],$this->uid); + } + + function getChild($name) { + $name = str_replace(" ","",$name); + if(!$this->childExists($name)){ + throw new DAV\Exception\NotFound('File with name ' . $name . ' could not be located'); + } + $path = $this->uid.rtrim($this->myPath,"/") . '/' . $name; + if($this->findDir(rtrim($this->myPath,"/") . '/' . $name)){ + $returnObj = new Directory($path); + return $returnObj; + }else{ + return new Objects($path); + } + } + + function childExists($name) { + $name = str_replace(" ","",$name); + $fileObj = new Objects($this->uid.rtrim($this->myPath,"/") . '/' . $name); + if($this->findDir(rtrim($this->myPath,"/") . '/' . $name) || $fileObj->isExist){ + return true; + } + return false; + } + + public function findDir($path){ + if($path == "/"){ + return true; + } + $explode = explode("/",$path); + $dirName = end($explode); + $rootPath = rtrim($path,"/".$dirName); + $rootPath = empty($rootPath) ? "/" : $rootPath; + $dirData = Db::name('folders')->where('owner',$this->uid)->where('position',dirname($path) == "\\" ?"/":dirname($path))->where("folder_name",getDirName($path))->find(); + if(empty($dirData)){ + return false; + } + return true; + } + + function getName() { + $explode = explode("/", $this->myPath); + return end($explode); + + } + + function createDirectory($name) { + $createAction = FileManage::createFolder($name,$this->myPath,$this->uid); + if(!$createAction["result"]["success"]){ + die($this->myPath); + throw new DAV\Exception\InvalidResourceType($createAction["result"]["error"]); + } + } +} +?> \ No newline at end of file diff --git a/lib/Medoo.php b/lib/Medoo.php new file mode 100644 index 0000000..0164591 --- /dev/null +++ b/lib/Medoo.php @@ -0,0 +1,1852 @@ +type = strtolower($options[ 'database_type' ]); + + if ($this->type === 'mariadb') + { + $this->type = 'mysql'; + } + } + + if (isset($options[ 'prefix' ])) + { + $this->prefix = $options[ 'prefix' ]; + } + + if (isset($options[ 'logging' ]) && is_bool($options[ 'logging' ])) + { + $this->logging = $options[ 'logging' ]; + } + + $option = isset($options[ 'option' ]) ? $options[ 'option' ] : []; + $commands = (isset($options[ 'command' ]) && is_array($options[ 'command' ])) ? $options[ 'command' ] : []; + + switch ($this->type) + { + case 'mysql': + // Make MySQL using standard quoted identifier + $commands[] = 'SET SQL_MODE=ANSI_QUOTES'; + + break; + + case 'mssql': + // Keep MSSQL QUOTED_IDENTIFIER is ON for standard quoting + $commands[] = 'SET QUOTED_IDENTIFIER ON'; + + // Make ANSI_NULLS is ON for NULL value + $commands[] = 'SET ANSI_NULLS ON'; + + break; + } + + if (isset($options[ 'pdo' ])) + { + if (!$options[ 'pdo' ] instanceof PDO) + { + throw new InvalidArgumentException('Invalid PDO object supplied'); + } + + $this->pdo = $options[ 'pdo' ]; + + foreach ($commands as $value) + { + $this->pdo->exec($value); + } + + return; + } + + if (isset($options[ 'dsn' ])) + { + if (is_array($options[ 'dsn' ]) && isset($options[ 'dsn' ][ 'driver' ])) + { + $attr = $options[ 'dsn' ]; + } + else + { + throw new InvalidArgumentException('Invalid DSN option supplied'); + } + } + else + { + if ( + isset($options[ 'port' ]) && + is_int($options[ 'port' ] * 1) + ) + { + $port = $options[ 'port' ]; + } + + $is_port = isset($port); + + switch ($this->type) + { + case 'mysql': + $attr = [ + 'driver' => 'mysql', + 'dbname' => $options[ 'database_name' ] + ]; + + if (isset($options[ 'socket' ])) + { + $attr[ 'unix_socket' ] = $options[ 'socket' ]; + } + else + { + $attr[ 'host' ] = $options[ 'server' ]; + + if ($is_port) + { + $attr[ 'port' ] = $port; + } + } + + break; + + case 'pgsql': + $attr = [ + 'driver' => 'pgsql', + 'host' => $options[ 'server' ], + 'dbname' => $options[ 'database_name' ] + ]; + + if ($is_port) + { + $attr[ 'port' ] = $port; + } + + break; + + case 'sybase': + $attr = [ + 'driver' => 'dblib', + 'host' => $options[ 'server' ], + 'dbname' => $options[ 'database_name' ] + ]; + + if ($is_port) + { + $attr[ 'port' ] = $port; + } + + break; + + case 'oracle': + $attr = [ + 'driver' => 'oci', + 'dbname' => $options[ 'server' ] ? + '//' . $options[ 'server' ] . ($is_port ? ':' . $port : ':1521') . '/' . $options[ 'database_name' ] : + $options[ 'database_name' ] + ]; + + if (isset($options[ 'charset' ])) + { + $attr[ 'charset' ] = $options[ 'charset' ]; + } + + break; + + case 'mssql': + if (isset($options[ 'driver' ]) && $options[ 'driver' ] === 'dblib') + { + $attr = [ + 'driver' => 'dblib', + 'host' => $options[ 'server' ] . ($is_port ? ':' . $port : ''), + 'dbname' => $options[ 'database_name' ] + ]; + + if (isset($options[ 'appname' ])) + { + $attr[ 'appname' ] = $options[ 'appname' ]; + } + + if (isset($options[ 'charset' ])) + { + $attr[ 'charset' ] = $options[ 'charset' ]; + } + } + else + { + $attr = [ + 'driver' => 'sqlsrv', + 'Server' => $options[ 'server' ] . ($is_port ? ',' . $port : ''), + 'Database' => $options[ 'database_name' ] + ]; + + if (isset($options[ 'appname' ])) + { + $attr[ 'APP' ] = $options[ 'appname' ]; + } + + $config = [ + 'ApplicationIntent', + 'AttachDBFileName', + 'Authentication', + 'ColumnEncryption', + 'ConnectionPooling', + 'Encrypt', + 'Failover_Partner', + 'KeyStoreAuthentication', + 'KeyStorePrincipalId', + 'KeyStoreSecret', + 'LoginTimeout', + 'MultipleActiveResultSets', + 'MultiSubnetFailover', + 'Scrollable', + 'TraceFile', + 'TraceOn', + 'TransactionIsolation', + 'TransparentNetworkIPResolution', + 'TrustServerCertificate', + 'WSID', + ]; + + foreach ($config as $value) + { + $keyname = strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $value)); + + if (isset($options[ $keyname ])) + { + $attr[ $value ] = $options[ $keyname ]; + } + } + } + + break; + + case 'sqlite': + $attr = [ + 'driver' => 'sqlite', + $options[ 'database_file' ] + ]; + + break; + } + } + + if (!isset($attr)) + { + throw new InvalidArgumentException('Incorrect connection options'); + } + + $driver = $attr[ 'driver' ]; + + if (!in_array($driver, PDO::getAvailableDrivers())) + { + throw new InvalidArgumentException("Unsupported PDO driver: {$driver}"); + } + + unset($attr[ 'driver' ]); + + $stack = []; + + foreach ($attr as $key => $value) + { + $stack[] = is_int($key) ? $value : $key . '=' . $value; + } + + $dsn = $driver . ':' . implode(';', $stack); + + if ( + in_array($this->type, ['mysql', 'pgsql', 'sybase', 'mssql']) && + isset($options[ 'charset' ]) + ) + { + $commands[] = "SET NAMES '{$options[ 'charset' ]}'" . ( + $this->type === 'mysql' && isset($options[ 'collation' ]) ? + " COLLATE '{$options[ 'collation' ]}'" : '' + ); + } + + $this->dsn = $dsn; + + try { + $this->pdo = new PDO( + $dsn, + isset($options[ 'username' ]) ? $options[ 'username' ] : null, + isset($options[ 'password' ]) ? $options[ 'password' ] : null, + $option + ); + + foreach ($commands as $value) + { + $this->pdo->exec($value); + } + } + catch (PDOException $e) { + throw new PDOException($e->getMessage()); + } + } + + public function query($query, $map = []) + { + $raw = $this->raw($query, $map); + + $query = $this->buildRaw($raw, $map); + + return $this->exec($query, $map); + } + + public function exec($query, $map = []) + { + $this->statement = null; + + if ($this->debug_mode) + { + echo $this->generate($query, $map); + + $this->debug_mode = false; + + return false; + } + + if ($this->logging) + { + $this->logs[] = [$query, $map]; + } + else + { + $this->logs = [[$query, $map]]; + } + + $statement = $this->pdo->prepare($query); + + if (!$statement) + { + $this->errorInfo = $this->pdo->errorInfo(); + $this->statement = null; + + return false; + } + + $this->statement = $statement; + + foreach ($map as $key => $value) + { + $statement->bindValue($key, $value[ 0 ], $value[ 1 ]); + } + + $execute = $statement->execute(); + + $this->errorInfo = $statement->errorInfo(); + + if (!$execute) + { + $this->statement = null; + } + + return $statement; + } + + protected function generate($query, $map) + { + $identifier = [ + 'mysql' => '`$1`', + 'mssql' => '[$1]' + ]; + + $query = preg_replace( + '/"([a-zA-Z0-9_]+)"/i', + isset($identifier[ $this->type ]) ? $identifier[ $this->type ] : '"$1"', + $query + ); + + foreach ($map as $key => $value) + { + if ($value[ 1 ] === PDO::PARAM_STR) + { + $replace = $this->quote($value[ 0 ]); + } + elseif ($value[ 1 ] === PDO::PARAM_NULL) + { + $replace = 'NULL'; + } + elseif ($value[ 1 ] === PDO::PARAM_LOB) + { + $replace = '{LOB_DATA}'; + } + else + { + $replace = $value[ 0 ]; + } + + $query = str_replace($key, $replace, $query); + } + + return $query; + } + + public static function raw($string, $map = []) + { + $raw = new Raw(); + + $raw->map = $map; + $raw->value = $string; + + return $raw; + } + + protected function isRaw($object) + { + return $object instanceof Raw; + } + + protected function buildRaw($raw, &$map) + { + if (!$this->isRaw($raw)) + { + return false; + } + + $query = preg_replace_callback( + '/(([`\']).*?)?((FROM|TABLE|INTO|UPDATE|JOIN)\s*)?\<(([a-zA-Z0-9_]+)(\.[a-zA-Z0-9_]+)?)\>(.*?\2)?/i', + function ($matches) + { + if (!empty($matches[ 2 ]) && isset($matches[ 8 ])) + { + return $matches[ 0 ]; + } + + if (!empty($matches[ 4 ])) + { + return $matches[ 1 ] . $matches[ 4 ] . ' ' . $this->tableQuote($matches[ 5 ]); + } + + return $matches[ 1 ] . $this->columnQuote($matches[ 5 ]); + }, + $raw->value); + + $raw_map = $raw->map; + + if (!empty($raw_map)) + { + foreach ($raw_map as $key => $value) + { + $map[ $key ] = $this->typeMap($value, gettype($value)); + } + } + + return $query; + } + + public function quote($string) + { + return $this->pdo->quote($string); + } + + protected function tableQuote($table) + { + if (!preg_match('/^[a-zA-Z0-9_]+$/i', $table)) + { + throw new InvalidArgumentException("Incorrect table name \"$table\""); + } + + return '"' . $this->prefix . $table . '"'; + } + + protected function mapKey() + { + return ':MeDoO_' . $this->guid++ . '_mEdOo'; + } + + protected function typeMap($value, $type) + { + $map = [ + 'NULL' => PDO::PARAM_NULL, + 'integer' => PDO::PARAM_INT, + 'double' => PDO::PARAM_STR, + 'boolean' => PDO::PARAM_BOOL, + 'string' => PDO::PARAM_STR, + 'object' => PDO::PARAM_STR, + 'resource' => PDO::PARAM_LOB + ]; + + if ($type === 'boolean') + { + $value = ($value ? '1' : '0'); + } + elseif ($type === 'NULL') + { + $value = null; + } + + return [$value, $map[ $type ]]; + } + + protected function columnQuote($string) + { + if (!preg_match('/^[a-zA-Z0-9_]+(\.?[a-zA-Z0-9_]+)?$/i', $string)) + { + throw new InvalidArgumentException("Incorrect column name \"$string\""); + } + + if (strpos($string, '.') !== false) + { + return '"' . $this->prefix . str_replace('.', '"."', $string) . '"'; + } + + return '"' . $string . '"'; + } + + protected function columnPush(&$columns, &$map, $root, $is_join = false) + { + if ($columns === '*') + { + return $columns; + } + + $stack = []; + + if (is_string($columns)) + { + $columns = [$columns]; + } + + foreach ($columns as $key => $value) + { + if (!is_int($key) && is_array($value) && $root && count(array_keys($columns)) === 1) + { + $stack[] = $this->columnQuote($key); + + $stack[] = $this->columnPush($value, $map, false, $is_join); + } + elseif (is_array($value)) + { + $stack[] = $this->columnPush($value, $map, false, $is_join); + } + elseif (!is_int($key) && $raw = $this->buildRaw($value, $map)) + { + preg_match('/(?[a-zA-Z0-9_\.]+)(\s*\[(?(String|Bool|Int|Number))\])?/i', $key, $match); + + $stack[] = $raw . ' AS ' . $this->columnQuote($match[ 'column' ]); + } + elseif (is_int($key) && is_string($value)) + { + if ($is_join && strpos($value, '*') !== false) + { + throw new InvalidArgumentException('Cannot use table.* to select all columns while joining table'); + } + + preg_match('/(?[a-zA-Z0-9_\.]+)(?:\s*\((?[a-zA-Z0-9_]+)\))?(?:\s*\[(?(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $match); + + if (!empty($match[ 'alias' ])) + { + $stack[] = $this->columnQuote($match[ 'column' ]) . ' AS ' . $this->columnQuote($match[ 'alias' ]); + + $columns[ $key ] = $match[ 'alias' ]; + + if (!empty($match[ 'type' ])) + { + $columns[ $key ] .= ' [' . $match[ 'type' ] . ']'; + } + } + else + { + $stack[] = $this->columnQuote($match[ 'column' ]); + } + } + } + + return implode(',', $stack); + } + + protected function arrayQuote($array) + { + $stack = []; + + foreach ($array as $value) + { + $stack[] = is_int($value) ? $value : $this->pdo->quote($value); + } + + return implode(',', $stack); + } + + protected function innerConjunct($data, $map, $conjunctor, $outer_conjunctor) + { + $stack = []; + + foreach ($data as $value) + { + $stack[] = '(' . $this->dataImplode($value, $map, $conjunctor) . ')'; + } + + return implode($outer_conjunctor . ' ', $stack); + } + + protected function dataImplode($data, &$map, $conjunctor) + { + $stack = []; + + foreach ($data as $key => $value) + { + $type = gettype($value); + + if ( + $type === 'array' && + preg_match("/^(AND|OR)(\s+#.*)?$/", $key, $relation_match) + ) + { + $relationship = $relation_match[ 1 ]; + + $stack[] = $value !== array_keys(array_keys($value)) ? + '(' . $this->dataImplode($value, $map, ' ' . $relationship) . ')' : + '(' . $this->innerConjunct($value, $map, ' ' . $relationship, $conjunctor) . ')'; + + continue; + } + + $map_key = $this->mapKey(); + + if ( + is_int($key) && + preg_match('/([a-zA-Z0-9_\.]+)\[(?\>\=?|\<\=?|\!?\=)\]([a-zA-Z0-9_\.]+)/i', $value, $match) + ) + { + $stack[] = $this->columnQuote($match[ 1 ]) . ' ' . $match[ 'operator' ] . ' ' . $this->columnQuote($match[ 3 ]); + } + else + { + preg_match('/([a-zA-Z0-9_\.]+)(\[(?\>\=?|\<\=?|\!|\<\>|\>\<|\!?~|REGEXP)\])?/i', $key, $match); + $column = $this->columnQuote($match[ 1 ]); + + if (isset($match[ 'operator' ])) + { + $operator = $match[ 'operator' ]; + + if (in_array($operator, ['>', '>=', '<', '<='])) + { + $condition = $column . ' ' . $operator . ' '; + + if (is_numeric($value)) + { + $condition .= $map_key; + $map[ $map_key ] = [$value, is_float($value) ? PDO::PARAM_STR : PDO::PARAM_INT]; + } + elseif ($raw = $this->buildRaw($value, $map)) + { + $condition .= $raw; + } + else + { + $condition .= $map_key; + $map[ $map_key ] = [$value, PDO::PARAM_STR]; + } + + $stack[] = $condition; + } + elseif ($operator === '!') + { + switch ($type) + { + case 'NULL': + $stack[] = $column . ' IS NOT NULL'; + break; + + case 'array': + $placeholders = []; + + foreach ($value as $index => $item) + { + $stack_key = $map_key . $index . '_i'; + + $placeholders[] = $stack_key; + $map[ $stack_key ] = $this->typeMap($item, gettype($item)); + } + + $stack[] = $column . ' NOT IN (' . implode(', ', $placeholders) . ')'; + break; + + case 'object': + if ($raw = $this->buildRaw($value, $map)) + { + $stack[] = $column . ' != ' . $raw; + } + break; + + case 'integer': + case 'double': + case 'boolean': + case 'string': + $stack[] = $column . ' != ' . $map_key; + $map[ $map_key ] = $this->typeMap($value, $type); + break; + } + } + elseif ($operator === '~' || $operator === '!~') + { + if ($type !== 'array') + { + $value = [ $value ]; + } + + $connector = ' OR '; + $data = array_values($value); + + if (is_array($data[ 0 ])) + { + if (isset($value[ 'AND' ]) || isset($value[ 'OR' ])) + { + $connector = ' ' . array_keys($value)[ 0 ] . ' '; + $value = $data[ 0 ]; + } + } + + $like_clauses = []; + + foreach ($value as $index => $item) + { + $item = strval($item); + + if (!preg_match('/(\[.+\]|[\*\?\!\%#^-_]|%.+|.+%)/', $item)) + { + $item = '%' . $item . '%'; + } + + $like_clauses[] = $column . ($operator === '!~' ? ' NOT' : '') . ' LIKE ' . $map_key . 'L' . $index; + $map[ $map_key . 'L' . $index ] = [$item, PDO::PARAM_STR]; + } + + $stack[] = '(' . implode($connector, $like_clauses) . ')'; + } + elseif ($operator === '<>' || $operator === '><') + { + if ($type === 'array') + { + if ($operator === '><') + { + $column .= ' NOT'; + } + + $stack[] = '(' . $column . ' BETWEEN ' . $map_key . 'a AND ' . $map_key . 'b)'; + + $data_type = (is_numeric($value[ 0 ]) && is_numeric($value[ 1 ])) ? PDO::PARAM_INT : PDO::PARAM_STR; + + $map[ $map_key . 'a' ] = [$value[ 0 ], $data_type]; + $map[ $map_key . 'b' ] = [$value[ 1 ], $data_type]; + } + } + elseif ($operator === 'REGEXP') + { + $stack[] = $column . ' REGEXP ' . $map_key; + $map[ $map_key ] = [$value, PDO::PARAM_STR]; + } + } + else + { + switch ($type) + { + case 'NULL': + $stack[] = $column . ' IS NULL'; + break; + + case 'array': + $placeholders = []; + + foreach ($value as $index => $item) + { + $stack_key = $map_key . $index . '_i'; + + $placeholders[] = $stack_key; + $map[ $stack_key ] = $this->typeMap($item, gettype($item)); + } + + $stack[] = $column . ' IN (' . implode(', ', $placeholders) . ')'; + break; + + case 'object': + if ($raw = $this->buildRaw($value, $map)) + { + $stack[] = $column . ' = ' . $raw; + } + break; + + case 'integer': + case 'double': + case 'boolean': + case 'string': + $stack[] = $column . ' = ' . $map_key; + $map[ $map_key ] = $this->typeMap($value, $type); + break; + } + } + } + } + + return implode($conjunctor . ' ', $stack); + } + + protected function whereClause($where, &$map) + { + $where_clause = ''; + + if (is_array($where)) + { + $where_keys = array_keys($where); + + $conditions = array_diff_key($where, array_flip( + ['GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LIKE', 'MATCH'] + )); + + if (!empty($conditions)) + { + $where_clause = ' WHERE ' . $this->dataImplode($conditions, $map, ' AND'); + } + + if (isset($where[ 'MATCH' ]) && $this->type === 'mysql') + { + $MATCH = $where[ 'MATCH' ]; + + if (is_array($MATCH) && isset($MATCH[ 'columns' ], $MATCH[ 'keyword' ])) + { + $mode = ''; + + $mode_array = [ + 'natural' => 'IN NATURAL LANGUAGE MODE', + 'natural+query' => 'IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION', + 'boolean' => 'IN BOOLEAN MODE', + 'query' => 'WITH QUERY EXPANSION' + ]; + + if (isset($MATCH[ 'mode' ], $mode_array[ $MATCH[ 'mode' ] ])) + { + $mode = ' ' . $mode_array[ $MATCH[ 'mode' ] ]; + } + + $columns = implode(', ', array_map([$this, 'columnQuote'], $MATCH[ 'columns' ])); + $map_key = $this->mapKey(); + $map[ $map_key ] = [$MATCH[ 'keyword' ], PDO::PARAM_STR]; + + $where_clause .= ($where_clause !== '' ? ' AND ' : ' WHERE') . ' MATCH (' . $columns . ') AGAINST (' . $map_key . $mode . ')'; + } + } + + if (isset($where[ 'GROUP' ])) + { + $GROUP = $where[ 'GROUP' ]; + + if (is_array($GROUP)) + { + $stack = []; + + foreach ($GROUP as $column => $value) + { + $stack[] = $this->columnQuote($value); + } + + $where_clause .= ' GROUP BY ' . implode(',', $stack); + } + elseif ($raw = $this->buildRaw($GROUP, $map)) + { + $where_clause .= ' GROUP BY ' . $raw; + } + else + { + $where_clause .= ' GROUP BY ' . $this->columnQuote($GROUP); + } + + if (isset($where[ 'HAVING' ])) + { + if ($raw = $this->buildRaw($where[ 'HAVING' ], $map)) + { + $where_clause .= ' HAVING ' . $raw; + } + else + { + $where_clause .= ' HAVING ' . $this->dataImplode($where[ 'HAVING' ], $map, ' AND'); + } + } + } + + if (isset($where[ 'ORDER' ])) + { + $ORDER = $where[ 'ORDER' ]; + + if (is_array($ORDER)) + { + $stack = []; + + foreach ($ORDER as $column => $value) + { + if (is_array($value)) + { + $stack[] = 'FIELD(' . $this->columnQuote($column) . ', ' . $this->arrayQuote($value) . ')'; + } + elseif ($value === 'ASC' || $value === 'DESC') + { + $stack[] = $this->columnQuote($column) . ' ' . $value; + } + elseif (is_int($column)) + { + $stack[] = $this->columnQuote($value); + } + } + + $where_clause .= ' ORDER BY ' . implode(',', $stack); + } + elseif ($raw = $this->buildRaw($ORDER, $map)) + { + $where_clause .= ' ORDER BY ' . $raw; + } + else + { + $where_clause .= ' ORDER BY ' . $this->columnQuote($ORDER); + } + + if ( + isset($where[ 'LIMIT' ]) && + in_array($this->type, ['oracle', 'mssql']) + ) + { + $LIMIT = $where[ 'LIMIT' ]; + + if (is_numeric($LIMIT)) + { + $LIMIT = [0, $LIMIT]; + } + + if ( + is_array($LIMIT) && + is_numeric($LIMIT[ 0 ]) && + is_numeric($LIMIT[ 1 ]) + ) + { + $where_clause .= ' OFFSET ' . $LIMIT[ 0 ] . ' ROWS FETCH NEXT ' . $LIMIT[ 1 ] . ' ROWS ONLY'; + } + } + } + + if (isset($where[ 'LIMIT' ]) && !in_array($this->type, ['oracle', 'mssql'])) + { + $LIMIT = $where[ 'LIMIT' ]; + + if (is_numeric($LIMIT)) + { + $where_clause .= ' LIMIT ' . $LIMIT; + } + elseif ( + is_array($LIMIT) && + is_numeric($LIMIT[ 0 ]) && + is_numeric($LIMIT[ 1 ]) + ) + { + $where_clause .= ' LIMIT ' . $LIMIT[ 1 ] . ' OFFSET ' . $LIMIT[ 0 ]; + } + } + } + elseif ($raw = $this->buildRaw($where, $map)) + { + $where_clause .= ' ' . $raw; + } + + return $where_clause; + } + + protected function selectContext($table, &$map, $join, &$columns = null, $where = null, $column_fn = null) + { + preg_match('/(?[a-zA-Z0-9_]+)\s*\((?[a-zA-Z0-9_]+)\)/i', $table, $table_match); + + if (isset($table_match[ 'table' ], $table_match[ 'alias' ])) + { + $table = $this->tableQuote($table_match[ 'table' ]); + + $table_query = $table . ' AS ' . $this->tableQuote($table_match[ 'alias' ]); + } + else + { + $table = $this->tableQuote($table); + + $table_query = $table; + } + + $is_join = false; + $join_key = is_array($join) ? array_keys($join) : null; + + if ( + isset($join_key[ 0 ]) && + strpos($join_key[ 0 ], '[') === 0 + ) + { + $is_join = true; + $table_query .= ' ' . $this->buildJoin($table, $join); + } + else + { + if (is_null($columns)) + { + if ( + !is_null($where) || + (is_array($join) && isset($column_fn)) + ) + { + $where = $join; + $columns = null; + } + else + { + $where = null; + $columns = $join; + } + } + else + { + $where = $columns; + $columns = $join; + } + } + + if (isset($column_fn)) + { + if ($column_fn === 1) + { + $column = '1'; + + if (is_null($where)) + { + $where = $columns; + } + } + elseif ($raw = $this->buildRaw($column_fn, $map)) + { + $column = $raw; + } + else + { + if (empty($columns) || $this->isRaw($columns)) + { + $columns = '*'; + $where = $join; + } + + $column = $column_fn . '(' . $this->columnPush($columns, $map, true) . ')'; + } + } + else + { + $column = $this->columnPush($columns, $map, true, $is_join); + } + + return 'SELECT ' . $column . ' FROM ' . $table_query . $this->whereClause($where, $map); + } + + protected function buildJoin($table, $join) + { + $table_join = []; + + $join_array = [ + '>' => 'LEFT', + '<' => 'RIGHT', + '<>' => 'FULL', + '><' => 'INNER' + ]; + + foreach($join as $sub_table => $relation) + { + preg_match('/(\[(?\<\>?|\>\[a-zA-Z0-9_]+)\s?(\((?[a-zA-Z0-9_]+)\))?/', $sub_table, $match); + + if ($match[ 'join' ] !== '' && $match[ 'table' ] !== '') + { + if (is_string($relation)) + { + $relation = 'USING ("' . $relation . '")'; + } + + if (is_array($relation)) + { + // For ['column1', 'column2'] + if (isset($relation[ 0 ])) + { + $relation = 'USING ("' . implode('", "', $relation) . '")'; + } + else + { + $joins = []; + + foreach ($relation as $key => $value) + { + $joins[] = ( + strpos($key, '.') > 0 ? + // For ['tableB.column' => 'column'] + $this->columnQuote($key) : + + // For ['column1' => 'column2'] + $table . '."' . $key . '"' + ) . + ' = ' . + $this->tableQuote(isset($match[ 'alias' ]) ? $match[ 'alias' ] : $match[ 'table' ]) . '."' . $value . '"'; + } + + $relation = 'ON ' . implode(' AND ', $joins); + } + } + + $table_name = $this->tableQuote($match[ 'table' ]) . ' '; + + if (isset($match[ 'alias' ])) + { + $table_name .= 'AS ' . $this->tableQuote($match[ 'alias' ]) . ' '; + } + + $table_join[] = $join_array[ $match[ 'join' ] ] . ' JOIN ' . $table_name . $relation; + } + } + + return implode(' ', $table_join); + } + + protected function columnMap($columns, &$stack, $root) + { + if ($columns === '*') + { + return $stack; + } + + foreach ($columns as $key => $value) + { + if (is_int($key)) + { + preg_match('/([a-zA-Z0-9_]+\.)?(?[a-zA-Z0-9_]+)(?:\s*\((?[a-zA-Z0-9_]+)\))?(?:\s*\[(?(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $key_match); + + $column_key = !empty($key_match[ 'alias' ]) ? + $key_match[ 'alias' ] : + $key_match[ 'column' ]; + + if (isset($key_match[ 'type' ])) + { + $stack[ $value ] = [$column_key, $key_match[ 'type' ]]; + } + else + { + $stack[ $value ] = [$column_key, 'String']; + } + } + elseif ($this->isRaw($value)) + { + preg_match('/([a-zA-Z0-9_]+\.)?(?[a-zA-Z0-9_]+)(\s*\[(?(String|Bool|Int|Number))\])?/i', $key, $key_match); + + $column_key = $key_match[ 'column' ]; + + if (isset($key_match[ 'type' ])) + { + $stack[ $key ] = [$column_key, $key_match[ 'type' ]]; + } + else + { + $stack[ $key ] = [$column_key, 'String']; + } + } + elseif (!is_int($key) && is_array($value)) + { + if ($root && count(array_keys($columns)) === 1) + { + $stack[ $key ] = [$key, 'String']; + } + + $this->columnMap($value, $stack, false); + } + } + + return $stack; + } + + protected function dataMap($data, $columns, $column_map, &$stack, $root, &$result) + { + if ($root) + { + $columns_key = array_keys($columns); + + if (count($columns_key) === 1 && is_array($columns[$columns_key[0]])) + { + $index_key = array_keys($columns)[0]; + $data_key = preg_replace("/^[a-zA-Z0-9_]+\./i", "", $index_key); + + $current_stack = []; + + foreach ($data as $item) + { + $this->dataMap($data, $columns[ $index_key ], $column_map, $current_stack, false, $result); + + $index = $data[ $data_key ]; + + $result[ $index ] = $current_stack; + } + } + else + { + $current_stack = []; + + $this->dataMap($data, $columns, $column_map, $current_stack, false, $result); + + $result[] = $current_stack; + } + + return; + } + + foreach ($columns as $key => $value) + { + $isRaw = $this->isRaw($value); + + if (is_int($key) || $isRaw) + { + $map = $column_map[ $isRaw ? $key : $value ]; + + $column_key = $map[ 0 ]; + + $item = $data[ $column_key ]; + + if (isset($map[ 1 ])) + { + if ($isRaw && in_array($map[ 1 ], ['Object', 'JSON'])) + { + continue; + } + + if (is_null($item)) + { + $stack[ $column_key ] = null; + continue; + } + + switch ($map[ 1 ]) + { + case 'Number': + $stack[ $column_key ] = (double) $item; + break; + + case 'Int': + $stack[ $column_key ] = (int) $item; + break; + + case 'Bool': + $stack[ $column_key ] = (bool) $item; + break; + + case 'Object': + $stack[ $column_key ] = unserialize($item); + break; + + case 'JSON': + $stack[ $column_key ] = json_decode($item, true); + break; + + case 'String': + $stack[ $column_key ] = $item; + break; + } + } + else + { + $stack[ $column_key ] = $item; + } + } + else + { + $current_stack = []; + + $this->dataMap($data, $value, $column_map, $current_stack, false, $result); + + $stack[ $key ] = $current_stack; + } + } + } + + public function create($table, $columns, $options = null) + { + $stack = []; + + $tableName = $this->prefix . $table; + + foreach ($columns as $name => $definition) + { + if (is_int($name)) + { + $stack[] = preg_replace('/\<([a-zA-Z0-9_]+)\>/i', '"$1"', $definition); + } + elseif (is_array($definition)) + { + $stack[] = $name . ' ' . implode(' ', $definition); + } + elseif (is_string($definition)) + { + $stack[] = $name . ' ' . $this->query($definition); + } + } + + $table_option = ''; + + if (is_array($options)) + { + $option_stack = []; + + foreach ($options as $key => $value) + { + if (is_string($value) || is_int($value)) + { + $option_stack[] = "$key = $value"; + } + } + + $table_option = ' ' . implode(', ', $option_stack); + } + elseif (is_string($options)) + { + $table_option = ' ' . $options; + } + + return $this->exec("CREATE TABLE IF NOT EXISTS $tableName (" . implode(', ', $stack) . ")$table_option"); + } + + public function drop($table) + { + $tableName = $this->prefix . $table; + + return $this->exec("DROP TABLE IF EXISTS $tableName"); + } + + public function select($table, $join, $columns = null, $where = null) + { + $map = []; + $result = []; + $column_map = []; + + $index = 0; + + $column = $where === null ? $join : $columns; + + $is_single = (is_string($column) && $column !== '*'); + + $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where), $map); + + $this->columnMap($columns, $column_map, true); + + if (!$this->statement) + { + return false; + } + + if ($columns === '*') + { + return $query->fetchAll(PDO::FETCH_ASSOC); + } + + while ($data = $query->fetch(PDO::FETCH_ASSOC)) + { + $current_stack = []; + + $this->dataMap($data, $columns, $column_map, $current_stack, true, $result); + } + + if ($is_single) + { + $single_result = []; + $result_key = $column_map[ $column ][ 0 ]; + + foreach ($result as $item) + { + $single_result[] = $item[ $result_key ]; + } + + return $single_result; + } + + return $result; + } + + public function insert($table, $datas) + { + $stack = []; + $columns = []; + $fields = []; + $map = []; + + if (!isset($datas[ 0 ])) + { + $datas = [$datas]; + } + + foreach ($datas as $data) + { + foreach ($data as $key => $value) + { + $columns[] = $key; + } + } + + $columns = array_unique($columns); + + foreach ($datas as $data) + { + $values = []; + + foreach ($columns as $key) + { + if ($raw = $this->buildRaw($data[ $key ], $map)) + { + $values[] = $raw; + continue; + } + + $map_key = $this->mapKey(); + + $values[] = $map_key; + + if (!isset($data[ $key ])) + { + $map[ $map_key ] = [null, PDO::PARAM_NULL]; + } + else + { + $value = $data[ $key ]; + + $type = gettype($value); + + switch ($type) + { + case 'array': + $map[ $map_key ] = [ + strpos($key, '[JSON]') === strlen($key) - 6 ? + json_encode($value) : + serialize($value), + PDO::PARAM_STR + ]; + break; + + case 'object': + $value = serialize($value); + + case 'NULL': + case 'resource': + case 'boolean': + case 'integer': + case 'double': + case 'string': + $map[ $map_key ] = $this->typeMap($value, $type); + break; + } + } + } + + $stack[] = '(' . implode(', ', $values) . ')'; + } + + foreach ($columns as $key) + { + $fields[] = $this->columnQuote(preg_replace("/(\s*\[JSON\]$)/i", '', $key)); + } + + return $this->exec('INSERT INTO ' . $this->tableQuote($table) . ' (' . implode(', ', $fields) . ') VALUES ' . implode(', ', $stack), $map); + } + + public function update($table, $data, $where = null) + { + $fields = []; + $map = []; + + foreach ($data as $key => $value) + { + $column = $this->columnQuote(preg_replace("/(\s*\[(JSON|\+|\-|\*|\/)\]$)/i", '', $key)); + + if ($raw = $this->buildRaw($value, $map)) + { + $fields[] = $column . ' = ' . $raw; + continue; + } + + $map_key = $this->mapKey(); + + preg_match('/(?[a-zA-Z0-9_]+)(\[(?\+|\-|\*|\/)\])?/i', $key, $match); + + if (isset($match[ 'operator' ])) + { + if (is_numeric($value)) + { + $fields[] = $column . ' = ' . $column . ' ' . $match[ 'operator' ] . ' ' . $value; + } + } + else + { + $fields[] = $column . ' = ' . $map_key; + + $type = gettype($value); + + switch ($type) + { + case 'array': + $map[ $map_key ] = [ + strpos($key, '[JSON]') === strlen($key) - 6 ? + json_encode($value) : + serialize($value), + PDO::PARAM_STR + ]; + break; + + case 'object': + $value = serialize($value); + + case 'NULL': + case 'resource': + case 'boolean': + case 'integer': + case 'double': + case 'string': + $map[ $map_key ] = $this->typeMap($value, $type); + break; + } + } + } + + return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $fields) . $this->whereClause($where, $map), $map); + } + + public function delete($table, $where) + { + $map = []; + + return $this->exec('DELETE FROM ' . $this->tableQuote($table) . $this->whereClause($where, $map), $map); + } + + public function replace($table, $columns, $where = null) + { + if (!is_array($columns) || empty($columns)) + { + return false; + } + + $map = []; + $stack = []; + + foreach ($columns as $column => $replacements) + { + if (is_array($replacements)) + { + foreach ($replacements as $old => $new) + { + $map_key = $this->mapKey(); + + $stack[] = $this->columnQuote($column) . ' = REPLACE(' . $this->columnQuote($column) . ', ' . $map_key . 'a, ' . $map_key . 'b)'; + + $map[ $map_key . 'a' ] = [$old, PDO::PARAM_STR]; + $map[ $map_key . 'b' ] = [$new, PDO::PARAM_STR]; + } + } + } + + if (!empty($stack)) + { + return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $stack) . $this->whereClause($where, $map), $map); + } + + return false; + } + + public function get($table, $join = null, $columns = null, $where = null) + { + $map = []; + $result = []; + $column_map = []; + $current_stack = []; + + if ($where === null) + { + $column = $join; + unset($columns[ 'LIMIT' ]); + } + else + { + $column = $columns; + unset($where[ 'LIMIT' ]); + } + + $is_single = (is_string($column) && $column !== '*'); + + $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where) . ' LIMIT 1', $map); + + if (!$this->statement) + { + return false; + } + + $data = $query->fetchAll(PDO::FETCH_ASSOC); + + if (isset($data[ 0 ])) + { + if ($column === '*') + { + return $data[ 0 ]; + } + + $this->columnMap($columns, $column_map, true); + + $this->dataMap($data[ 0 ], $columns, $column_map, $current_stack, true, $result); + + if ($is_single) + { + return $result[ 0 ][ $column_map[ $column ][ 0 ] ]; + } + + return $result[ 0 ]; + } + } + + public function has($table, $join, $where = null) + { + $map = []; + $column = null; + + if ($this->type === 'mssql') + { + $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, Medoo::raw('TOP 1 1')), $map); + } + else + { + $query = $this->exec('SELECT EXISTS(' . $this->selectContext($table, $map, $join, $column, $where, 1) . ')', $map); + } + + if (!$this->statement) + { + return false; + } + + $result = $query->fetchColumn(); + + return $result === '1' || $result === 1 || $result === true; + } + + public function rand($table, $join = null, $columns = null, $where = null) + { + $type = $this->type; + + $order = 'RANDOM()'; + + if ($type === 'mysql') + { + $order = 'RAND()'; + } + elseif ($type === 'mssql') + { + $order = 'NEWID()'; + } + + $order_raw = $this->raw($order); + + if ($where === null) + { + if ($columns === null) + { + $columns = [ + 'ORDER' => $order_raw + ]; + } + else + { + $column = $join; + unset($columns[ 'ORDER' ]); + + $columns[ 'ORDER' ] = $order_raw; + } + } + else + { + unset($where[ 'ORDER' ]); + + $where[ 'ORDER' ] = $order_raw; + } + + return $this->select($table, $join, $columns, $where); + } + + private function aggregate($type, $table, $join = null, $column = null, $where = null) + { + $map = []; + + $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, strtoupper($type)), $map); + + if (!$this->statement) + { + return false; + } + + $number = $query->fetchColumn(); + + return is_numeric($number) ? $number + 0 : $number; + } + + public function count($table, $join = null, $column = null, $where = null) + { + return $this->aggregate('count', $table, $join, $column, $where); + } + + public function avg($table, $join, $column = null, $where = null) + { + return $this->aggregate('avg', $table, $join, $column, $where); + } + + public function max($table, $join, $column = null, $where = null) + { + return $this->aggregate('max', $table, $join, $column, $where); + } + + public function min($table, $join, $column = null, $where = null) + { + return $this->aggregate('min', $table, $join, $column, $where); + } + + public function sum($table, $join, $column = null, $where = null) + { + return $this->aggregate('sum', $table, $join, $column, $where); + } + + public function action($actions) + { + if (is_callable($actions)) + { + $this->pdo->beginTransaction(); + + try { + $result = $actions($this); + + if ($result === false) + { + $this->pdo->rollBack(); + } + else + { + $this->pdo->commit(); + } + } + catch (Exception $e) { + $this->pdo->rollBack(); + + throw $e; + } + + return $result; + } + + return false; + } + + public function id() + { + if ($this->statement == null) + { + return null; + } + + $type = $this->type; + + if ($type === 'oracle') + { + return 0; + } + elseif ($type === 'pgsql') + { + return $this->pdo->query('SELECT LASTVAL()')->fetchColumn(); + } + + $lastId = $this->pdo->lastInsertId(); + + if ($lastId != "0" && $lastId != "") + { + return $lastId; + } + + return null; + } + + public function debug() + { + $this->debug_mode = true; + + return $this; + } + + public function error() + { + return $this->errorInfo; + } + + public function last() + { + $log = end($this->logs); + + return $this->generate($log[ 0 ], $log[ 1 ]); + } + + public function log() + { + return array_map(function ($log) + { + return $this->generate($log[ 0 ], $log[ 1 ]); + }, + $this->logs + ); + } + + public function info() + { + $output = [ + 'server' => 'SERVER_INFO', + 'driver' => 'DRIVER_NAME', + 'client' => 'CLIENT_VERSION', + 'version' => 'SERVER_VERSION', + 'connection' => 'CONNECTION_STATUS' + ]; + + foreach ($output as $key => $value) + { + $output[ $key ] = @$this->pdo->getAttribute(constant('PDO::ATTR_' . $value)); + } + + $output[ 'dsn' ] = $this->dsn; + + return $output; + } +} \ No newline at end of file diff --git a/lib/README.md b/lib/README.md new file mode 100644 index 0000000..fc5a268 --- /dev/null +++ b/lib/README.md @@ -0,0 +1,208 @@ +## 预览地址 +[pan.mxin.ltd](https://pan.mxin.ltd/) +必须设置伪静态 + + +其他说明 + +1.nginx伪静态 +``` +if (!-f $request_filename){ +set $rule_0 1$rule_0; +} +if (!-d $request_filename){ +set $rule_0 2$rule_0; +} +if ($rule_0 = "21"){ +rewrite ^/(.*)$ /index.php?/$1 last; +} +``` +重要:如设置了伪静态去除/?/,需把view/nexmoe/list.php的173和179行的"&s=1"改为"?s"(或者改为以post方式请求这个链接,我不会改啊) + +2.后台侧边栏代码示例(可放自定义的css/js) +``` +
+
+ folder +
Test
+ keyboard_arrow_down +
+
+ 456 +
+
+ 345 +
+
+ + + folder +
234
+
+ + + message +
Telegram频道
+
+ + + attach_money +
打赏
+
+ + + bubble_chart +
Blog
+
+ + + info_outline +
关于
+
+ + + +``` + +---------------------------------------------------------------------------------------------- + +# oneindex +OneDrive Directory Index + +## 功能: +不用服务器空间,不走服务器流量, + +直接列onedrive目录,文件直链下载。 + + + +## 创意整合 +1.极大简化安装步骤。 +2.一些样式美化修改。 +3.分页模式,加快页面预览速度。创意来自[oneindex-h](https://github.com/hang666/oneindex-h) +4.可后台自定义网站主标题,副标题。 +5.可后台自定义每页显示项目数量。 + +## 重新安装 +删除 oneindex/config 下的所有文件即可. + + +## change log: +20-06-14 文件批量移动功能(debug) +20-06-13 文件批量删除(debug) +20-06-12 增加主题背景 +20-06-09 增加新建文件夹功能 +20-06-07 文件管理/删除/重命名 +20-06=07 修复md文件全屏 +20-06=07 修复加密文件夹无法验证密码 +20-06=06 增加重命名文件方法 +20-06=06 增加删除文件方法 +20-06=06 修复重建缓存 +20-06-05 cli 功能增加列表 删除文件创建文件夹 +20-06-05 修复cli上传模式并且支持多盘/sharepoint +20-06-05 修复多盘引起图床失效 +20-06-05 bug 重建缓存失效(文件过多导致炸了api,考虑是否弃用) +20-06-05 增加离线下载功能(开发中 +20—06-02: 添加侧边栏网盘导航 +20-06-01: 修复首页空白问题 +20-05-29: 增加sharepoint站点id自动获取工具,账户显示,空间显示 +20-05-24: 移除cli模式 +20-05-25: 完成自动配置 +20-05-24: 完成多盘配置 +20-05-21: 添加防盗链接 +20-05-20: 移除pdfjs +20-05-19: 静态资源cdn 使用jsdevil +18-03-29: 更新直链获取机制、缓存机制,避免频繁访问的token失效 +18-03-29: 解决非英文编码问题 +18-03-29: 添加onedrive共享的起始目录 功能 +18-03-29: 添加rewrite的配置文件 +18-03-29: 增加sqlite模式cache支持 +18-03-29: 添加缩略图功能 +18-03-29: 添加404判断 +18-03-31: 添加console +18-04-13: 修复特殊文件名无法下载问题 +18-04-13: 添加命令行上传功能 +18-04-16: 更新 2.0 beta +18-04-16: 更新展示界面 +18-04-16: 响应式,支持小屏设备 +18-04-16: 图片在线预览 +18-04-16: 视频在线播放 +18-04-16: 代码在线查看(js、css、html、sh、php、java、md等) +18-04-16: README.md 支持,解析各目录下(onedirive目录下) README.md 文件,在页面尾部展示。 +18-04-18: 音频在线播放 +18-04-18: HEAD.md 支持,在页面头部展示 +18-04-18: .password 文件夹加密 +18-05-06: 在线视频播放器替换成 Dplayer +18-05-06: 在线视频播放支持'mp4','webm','avi','mpg', 'mpeg', 'rm', 'rmvb', 'mov', 'wmv', 'mkv', 'asf' +18-06-01: 支持个人账号 +18-06-01: cli文件夹上传(单线程) +18-06-01: 管理后台(后台地址:?/admin 默认密码:oneindex) +18-06-01: 不同后缀展示设置 +18-06-01: 文件直接输出 +18-06-01: 文件上传管理(后台) +18-06-01: 增加index.html特性 +18-06-01: 图床功能 + +## 需求: +1、PHP空间,PHP 5.6+ 打开curl支持 +2、onedrive 账号 (个人、企业版或教育版/工作或学校帐户) +3、oneindex 程序 + +## 安装: +image + + +## 计划任务   +[可选]**推荐配置**,非必需。后台定时刷新缓存,可增加前台访问的速度   +``` +# 每小时刷新一次token +0 * * * * /具体路径/php /程序具体路径/one.php token:refresh + +# 每十分钟后台刷新一遍缓存 +*/10 * * * * /具体路径/php /程序具体路径/one.php cache:refresh +``` + +## 特殊文件实现功能   +` README.md `、`HEAD.md` 、 `.password`特殊文件使用 + +可以参考[https://github.com/0oVicero0/oneindex/tree/files](https://github.com/0oVicero0/oneindex/tree/files) + +**在文件夹底部添加说明:**   +>在onedrive的文件夹中添加` README.md `文件,使用markdown语法。 + +**在文件夹头部添加说明:**   +>在onedrive的文件夹中添加`HEAD.md` 文件,使用markdown语法。   + +**加密文件夹:**   +>在onedrive的文件夹中添加`.password`文件,填入密码,密码不能为空。   + +**直接输出网页:** +>在onedrive的文件夹中添加`index.html` 文件,程序会直接输出网页而不列目录。 +>配合 文件展示设置-直接输出 效果更佳 + +## 命令行功能   +仅能在php cli模式下运行 +**清除缓存:**   +``` +php one.php cache:clear +``` +**刷新缓存:**   +``` +php one.php cache:refresh +``` +**刷新令牌:**   +``` +php one.php token:refresh +``` +**上传文件:**   +``` +php one.php upload:file 本地文件 [onedrive文件] +``` diff --git a/lib/abc.php b/lib/abc.php new file mode 100644 index 0000000..e2cb8e0 --- /dev/null +++ b/lib/abc.php @@ -0,0 +1,24 @@ +content, true); + if($resp->http_code == 409){ + return false; + } + + echo $resp->content; + +} + +if ($_SERVER["REQUEST_METHOD"]=="DELETE"){ + echo " 删除文件"; + if($_GET["action"]=="dellist"){ + $bodyData = @file_get_contents('php://input'); + $ss=json_decode( $bodyData,true); + if( !is_array( $ss ) ) +{ + $ss=array( + 0=> $ss); +} + + + + var_dump($ss); + // foreach ($ss as $s1s) { + echo onedrive::delete($ss); + // } + } + +} + +if ($_SERVER["REQUEST_METHOD"]=="RENAME"){ + $bodyData = @file_get_contents('php://input'); + + $ss=json_decode( $bodyData,true); + + onedrive::rename($ss["id"],$ss["name"]) ; + +} +if ($_SERVER["REQUEST_METHOD"]=="CREAT"){ + echo " 新建文件"; + + +} +if ($_SERVER["REQUEST_METHOD"]=="PROPFIND"){ + echo " webdav"; + + +} \ No newline at end of file diff --git a/lib/cache.php b/lib/cache.php index a045b12..44c2a7a 100644 --- a/lib/cache.php +++ b/lib/cache.php @@ -2,8 +2,8 @@ !defined('CACHE_PATH') && define('CACHE_PATH', sys_get_temp_dir().'/'); class cache{ - // 驱动方式(支持filecache/memcache/secache) - static $type = 'secache'; + // 驱动方式(支持filecache/memcache/secache/redis) + static $type = 'filecache'; // 返回缓存实例 protected static function c(){ @@ -68,7 +68,10 @@ static function pull($key){ return $value; } - static function refresh_cache($path, $next=true){ + + + + static function refresh_cache($path, $next=true){ $path2 = onedrive::urlencode($path); set_time_limit(0); if( php_sapi_name() == "cli" ){ @@ -93,4 +96,12 @@ static function clear_opcache(){ opcache_reset(); } } + + + + + + + + } diff --git a/lib/cache/filecache_.php b/lib/cache/filecache_.php index 6b3e0d3..d767134 100644 --- a/lib/cache/filecache_.php +++ b/lib/cache/filecache_.php @@ -10,8 +10,11 @@ function __construct($cache_path= null){ } function get($key){ - $file = $this->cache_path . md5($key) . '.php'; + // $file = $this->cache_path . md5($key) . '.php'; + $key=str_replace("/","-",$key); + $file = $this->cache_path . urldecode($key). '.php'; $data = @include $file; + if(is_login()){ return null;}//管理员不用缓存 if( is_array($data) && $data['expire'] > time() && !is_null($data['data']) ){ return $data['data']; }else{ @@ -20,7 +23,11 @@ function get($key){ } function set($key, $value=null, $expire=99999999){ - $file = $this->cache_path . md5($key) . '.php'; + $key=str_replace("/","-",$key); + $file = $this->cache_path . urldecode($key) . '.php'; + //$file = $this->cache_path . md5($key) . '.php'; + if(is_login()){ return ;}//管理员不用缓 + $data['expire'] = time() + $expire; $data['data'] = $value; return @file_put_contents($file, "redis->set("OneIndex_gRefreshTime", $gRefreshTime); } $key = "OneIndex_$gRefreshTime\_" . $key; - return $this->redis->set($key, serialize($value), $expire); + return $this->redis->set($key, serialize($value), (time() + $expire)); } function clear(){ diff --git a/lib/fetch.php b/lib/fetch.php index dba173a..e811a40 100644 --- a/lib/fetch.php +++ b/lib/fetch.php @@ -1,4 +1,5 @@ = "0"){ + + echo "用户在线"; + echo $_SESSION["userid"]; +} + + +} + + + + + + + + + + +} \ No newline at end of file diff --git a/lib/onedb.php b/lib/onedb.php new file mode 100644 index 0000000..6b9d488 Binary files /dev/null and b/lib/onedb.php differ diff --git a/lib/onedrive.php b/lib/onedrive.php index 56610d9..e67ee5d 100644 --- a/lib/onedrive.php +++ b/lib/onedrive.php @@ -1,11 +1,16 @@ $api, + 'headers' => [ + 'Accept' => 'application/json', + 'Authorization' => $配置文件["access_token"], + 'Content-Type' => 'application/json', + ], + 'http_errors' => false +]); + + return json_decode($apc->get($url)->getBody()); + + + + + + + + + +} //使用 $code, 获取 $refresh_token static function authorize($code = ""){ $client_id = self::$client_id; @@ -45,20 +80,28 @@ static function get_token($refresh_token){ $request['headers']= "Content-Type: application/x-www-form-urlencoded"; $resp = fetch::post($request); $data = json_decode($resp->content, true); + + return $data; } - //获取 $access_token, 带缓存 - static function access_token(){ - $token = config('@token'); - if($token['expires_on'] > time()+600){ + + + + static function access_token(){ + $varrr=explode("/",$_SERVER["REQUEST_URI"]); + $驱动器=$varrr["1"]; + $配置文件 = config('@'.$驱动器); + if($配置文件['expires_on'] > time()+600){ return $token['access_token']; }else{ - $refresh_token = config('refresh_token'); + $refresh_token = config('refresh_token@'.$驱动器); $token = self::get_token($refresh_token); if(!empty($token['refresh_token'])){ - $token['expires_on'] = time()+ $token['expires_in']; - config('@token', $token); + $配置文件['expires_on'] = time()+ $token['expires_in']; + $配置文=$token; + + config('@'.$驱动器, $配置文件); return $token['access_token']; } } @@ -66,20 +109,30 @@ static function access_token(){ } + + + + + + + // 生成一个request,带token static function request($path="/", $query=""){ $path = self::urlencode($path); $path = empty($path)?'/':":/{$path}:/"; - $token = self::access_token(); + $token=self::$access_token; $request['headers'] = "Authorization: bearer {$token}".PHP_EOL."Content-Type: application/json".PHP_EOL; - $request['url'] = self::$api_url."/me/drive/root".$path.$query; + $request['url']=self::$typeurl.$path.$query; + return $request; + } //返回目录信息 static function dir($path="/"){ - $request = self::request($path, "children?select=name,size,folder,@microsoft.graph.downloadUrl,lastModifiedDateTime"); + $request = self::request($path, "children?select=name,size,folder,lastModifiedDateTime,id,@microsoft.graph.downloadUrl"); + // $items = array(); self::dir_next_page($request, $items); //不在列表显示的文件夹 @@ -87,8 +140,7 @@ static function dir($path="/"){ if(is_array($hide_list) && count($hide_list)>0){ foreach($hide_list as $hide_dir){ foreach($items as $key=>$_array){ - $buf = trim($hide_dir); - if($buf && stristr($key, $buf))unset($items[$key]); + if(!empty(trim($hide_dir)) && stristr($key,trim($hide_dir)))unset($items[$key]); } } } @@ -109,6 +161,7 @@ static function dir_next_page($request, &$items, $retry=0){ //var_dump($item); $items[$item['name']] = array( 'name'=>$item['name'], + 'id'=>$item['id'], 'size'=>$item['size'], 'lastModifiedDateTime'=>strtotime($item['lastModifiedDateTime']), 'downloadUrl'=>$item['@microsoft.graph.downloadUrl'], @@ -124,14 +177,358 @@ static function dir_next_page($request, &$items, $retry=0){ } - //static function content($path){ - // $token = self::access_token(); - // fetch::$headers = "Authorization: bearer {$token}"; - // $url = self::$api_url."/me/drive/root:".self::urlencode($path).":/content"; - // $resp = fetch::get($url); - // return $resp->content; - //} + + + static function rename($itemid,$name){ + $access_token=self::$access_token; + $api=str_replace("root","items/".$itemid,self::$typeurl) ; + + + $curl = curl_init(); + + curl_setopt_array($curl, array( + CURLOPT_URL => $api, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "PATCH", + CURLOPT_POSTFIELDS =>"{\n \"name\": \"".$name."\"\n}", + CURLOPT_HTTPHEADER => array( + "Authorization: Bearer ".$access_token, + "Content-Type: application/json" + ), +)); + +$response = curl_exec($curl); + +curl_close($curl); +var_dump($response) ; + + + + } + + + + + static function delete($itemid=array()){ + + $varrr=explode("/",$_SERVER["REQUEST_URI"]); + $驱动器=$varrr["1"] ;array_splice($varrr,0, 1);unset($varrr['0']); + $请求路径 = implode("/", $varrr); + $请求路径= self::urlencode(str_replace("?".$_SERVER["QUERY_STRING"],"",$请求路径)); + $path = empty($请求路径)?'/':":/{$请求路径}:/"; + $配置文件=require(ROOT."config/".$驱动器.".php"); + + $access_token=$配置文件["access_token"]; + $apie=str_replace("root","items/",$配置文件["api"]) ; + + $apis=array(); + + for($i=0; $i $url) { + + $timeout=20; + $ch[$nch] = curl_init(); + curl_setopt_array($ch[$nch], array( + CURLOPT_URL => $url, + CURLOPT_TIMEOUT => $timeout, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_MAXREDIRS => 10, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "DELETE", + CURLOPT_HTTPHEADER => array( + "Authorization: Bearer ". $access_token, + "Content-Type: application/json" + ), + + )); + + curl_multi_add_handle($mh, $ch[$nch]); + ++$nch; + + } + + /* wait for performing request */ + + do { + $mrc = curl_multi_exec($mh, $running); + } while (CURLM_CALL_MULTI_PERFORM == $mrc); + + while ($running && $mrc == CURLM_OK) { + // wait for network + if (curl_multi_select($mh, 0.5) > -1) { + // pull in new data; + do { + $mrc = curl_multi_exec($mh, $running); + } while (CURLM_CALL_MULTI_PERFORM == $mrc); + } + + } + + if ($mrc != CURLM_OK) { + error_log("CURL Data Error"); + } + + /* get data */ + + $nch = 0; + + foreach ($apis as $moudle=>$node) { + if (($err = curl_error($ch[$nch])) == '') { + $res[$nch]=curl_multi_getcontent($ch[$nch]); + $result[$moudle]=$res[$nch]; + }else{ + error_log("curl error"); + + } + + curl_multi_remove_handle($mh,$ch[$nch]); + curl_close($ch[$nch]); + ++$nch; + } + + curl_multi_close($mh); + echo "批量处理完成"; + + + } + + + + + static function pathtoid($access_token,$path){ + $request=self::request(urldecode($path)); + $request['headers'] = "Authorization: bearer {$access_token}".PHP_EOL."Content-Type: application/json".PHP_EOL; + $resp= fetch::get($request); + $data = json_decode($resp->content, true); + return $data["id"]; + + } + static function movepast($itemid,$newitemid){ + + $varrr=explode("/",$_SERVER["REQUEST_URI"]); + $驱动器=$varrr["1"] ;array_splice($varrr,0, 1);unset($varrr['0']); + + $配置文件=require(ROOT."config/".$驱动器.".php"); + onedrive::$typeurl=$配置文件["api"] ; + onedrive::$access_token=access_token($配置文件,$驱动器); + $api=str_replace("root","items/".$itemid,self::$typeurl) ; + $access_token=self::$access_token; + + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => $api, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "PATCH", + CURLOPT_POSTFIELDS =>"{\n \"parentReference\": {\n \"id\": \"".$newitemid."\"\n }\n \n}", + CURLOPT_HTTPHEADER => array( + "Authorization: Bearer ".onedrive::$access_token, + "Content-Type: application/json" ), + )); + + $response = curl_exec($curl); + + curl_close($curl); + echo $response; + echo $id."完成"; + + + } + + + +static function downloadbyid($itemid){ + + $varrr=explode("/",$_SERVER["REQUEST_URI"]); + $驱动器=$varrr["1"] ;array_splice($varrr,0, 1);unset($varrr['0']); + $配置文件=require(ROOT."config/".$驱动器.".php"); + $token=$配置文件["access_token"]; + $api=str_replace("root","items/",$配置文件["api"]) ; + + $request['headers'] = "Authorization: bearer {$token}".PHP_EOL."Content-Type: application/json".PHP_EOL; + $request['url']=$api.$itemid; + $resp= fetch::get($request); + + $ss= json_decode($resp->content,true)["@microsoft.graph.downloadUrl"]; + + header('Location:'.$ss); + +} + + + + + + + +static function 批量移动($itemid=array(),$newitemid){ + + + $varrr=explode("/",$_SERVER["REQUEST_URI"]); + $驱动器=$varrr["1"] ;array_splice($varrr,0, 1);unset($varrr['0']); + $配置文件=require(ROOT."config/".$驱动器.".php"); + $token=$配置文件["access_token"]; + echo $typeurl=$配置文件["api"] ; + var_dump($itemid); + $apis=array(); + $api=str_replace("root","items/",$typeurl); + for($i=0; $i $url) { + + $timeout=20; + $ch[$nch] = curl_init(); + curl_setopt_array($ch[$nch], array( + CURLOPT_URL => $url, + CURLOPT_TIMEOUT => $timeout, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_MAXREDIRS => 10, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "PATCH", + CURLOPT_POSTFIELDS =>"{\n \"parentReference\": {\n \"id\": \"".$newitemid."\"\n }\n \n}", + CURLOPT_HTTPHEADER => array( + "Authorization: Bearer ".$token, + "Content-Type: application/json" + ), + + )); + + curl_multi_add_handle($mh, $ch[$nch]); + ++$nch; + + } + + /* wait for performing request */ + + do { + $mrc = curl_multi_exec($mh, $running); + } while (CURLM_CALL_MULTI_PERFORM == $mrc); + + while ($running && $mrc == CURLM_OK) { + // wait for network + if (curl_multi_select($mh, 0.5) > -1) { + // pull in new data; + do { + $mrc = curl_multi_exec($mh, $running); + } while (CURLM_CALL_MULTI_PERFORM == $mrc); + } + + } + + if ($mrc != CURLM_OK) { + error_log("CURL Data Error"); + } + + /* get data */ + + $nch = 0; + + foreach ($apis as $moudle=>$node) { + if (($err = curl_error($ch[$nch])) == '') { + $res[$nch]=curl_multi_getcontent($ch[$nch]); + $result[$moudle]=$res[$nch]; + }else{ + error_log("curl error"); + + } + + curl_multi_remove_handle($mh,$ch[$nch]); + curl_close($ch[$nch]); + ++$nch; + } + + curl_multi_close($mh); + echo "批量处理完成"; + var_dump($result) ; + +} + + + + + +static function get_siteidbyname($sitename,$access_token,$api_url){ + + + $request['headers'] = "Authorization: bearer {$access_token}".PHP_EOL.'Content-Type: application/json'.PHP_EOL; + $request['url'] = $api_url.'/sites/root'; + $resp = fetch::get($request); + $data = json_decode($resp->content, true); + $hostname = $data['siteCollection']['hostname']; + $getsiteid = $api_url.'/sites/'.$hostname.':'.$_REQUEST['site']; + $request['url'] = $getsiteid; + $respp = fetch::get($request); + $datass = json_decode($respp->content, true); + return $siteidurl= $datass["id"]; + + + +} + + + + + + + + + +static function create_folder($path,$name="新建文件夹"){ + $path = self::urlencode($path); + $path = empty($path)?'/':":/{$path}:/"; + $api=self::$typeurl.$path."/children"; + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => $api, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS =>"{\n \"name\": \"".$name."\",\n \"folder\": { },\n \"@microsoft.graph.conflictBehavior\": \"rename\"\n}", + CURLOPT_HTTPHEADER => array( + "Authorization: Bearer ".self::$access_token."", + "Content-Type: application/json" + ), +)); + +$response = curl_exec($curl); + +curl_close($curl); +echo $response; + + } //文件缩略图链接 static function thumbnail($path,$size='large'){ $request = self::request($path,"thumbnails/0?select={$size}"); @@ -141,16 +538,7 @@ static function thumbnail($path,$size='large'){ return @$data[$size]['url']; } - static function share($path){ - $request = self::request($path,"createLink"); - $post_data['type'] = 'view'; - $post_data['scope'] = 'anonymous'; - $resp = fetch::post($request, json_encode($post_data)); - $data = json_decode($resp->content, true); - return $data; - } - - //文件上传函数 + //简单文件上传函数 static function upload($path,$content){ $request = self::request($path,"content"); $request['post_data'] = $content; diff --git a/lib/oneindex.php b/lib/oneindex.php index 92d848e..5779e7f 100644 --- a/lib/oneindex.php +++ b/lib/oneindex.php @@ -1,13 +1,11 @@ 0 ){ - $k = array_pop($arr); - unset($arr[3]); - unset($arr[4]); - return join('/', $arr).'/_layouts/15/download.aspx?share='.$k; - }elseif ( strpos($arr[2],'1drv.ms') >0 ){ - # code... - } - } - } - //工具函数获取绝对路径 static function get_absolute_path($path) { @@ -147,4 +118,47 @@ static function get_absolute_path($path) { } return str_replace('//','/','/'.implode('/', $absolutes).'/'); } - } + + + + + static function is_mobile(){ + $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : ''; + $mobile_browser = '0'; + if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) + $mobile_browser++; + if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false)) + $mobile_browser++; + if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) + $mobile_browser++; + if(isset($_SERVER['HTTP_PROFILE'])) + $mobile_browser++; + $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4)); + $mobile_agents = array( + 'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac', + 'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno', + 'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-', + 'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-', + 'newt','noki','oper','palm','pana','pant','phil','play','port','prox', + 'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar', + 'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-', + 'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp', + 'wapr','webc','winw','winw','xda','xda-' + ); + if(in_array($mobile_ua, $mobile_agents)) + $mobile_browser++; + if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false) + $mobile_browser++; + // Pre-final check to reset everything if the user is on Windows + if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false) + $mobile_browser=0; + // But WP7 is also Windows, with a slightly different characteristic + if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false) + $mobile_browser++; + if($mobile_browser>0) + return true; + else + return false; +} + + } \ No newline at end of file diff --git a/lib/route.php b/lib/route.php index b21e1f9..db4ce31 100644 --- a/lib/route.php +++ b/lib/route.php @@ -1,4 +1,5 @@ +   +   +'; +exit; + + + +} + $request['headers'] = "Authorization: bearer {$config["access_token"]}".PHP_EOL."Content-Type: application/json".PHP_EOL; + $request["url"]='https://microsoftgraph.chinacloudapi.cn/v1.0/sites/root'; + $resp=fetch::get($request) ; + $data = json_decode($resp->content, true); + $hostname= $data["siteCollection"]["hostname"]; + + $getsiteid='https://microsoftgraph.chinacloudapi.cn/v1.0/sites/'.$hostname.':'.$_GET["site"]; + $request["url"]=$getsiteid; + $respp=fetch::get($request) ; + $datass = json_decode($respp->content, true); + +echo $siteidurl=($datass["id"]); +if (($datass["id"])==""){echo "获取站点id失败刷新重试试"; + + echo '站点名称填写/sites/名称或者/teams/名称'; + echo '
+   +   +'; + +exit;} +$b = ' +进入后台刷新缓存生效 默认密码oneindex'; diff --git a/lib/view.php b/lib/view.php index 74f39f4..01d0b00 100644 --- a/lib/view.php +++ b/lib/view.php @@ -1,4 +1,5 @@ '', 'data' => array()); diff --git a/lib/webdav/Controller.php b/lib/webdav/Controller.php new file mode 100644 index 0000000..3f9b121 --- /dev/null +++ b/lib/webdav/Controller.php @@ -0,0 +1,21 @@ +getFileInfo("/"); + $rootDirectory = new Folder("/",$current,$client); + $server = new DAV\Server($rootDirectory); + $server->addPlugin(new DAV\Browser\Plugin()); + $server->setBaseUri($path); + if(!empty($pass)){ + $authBackend = new DAV\Auth\Backend\BasicCallBack(function($username, $password) use($pass) { + return "$username:$password"==$pass; + }); + $authBackend->setRealm('TCShare WebDAV'); + $auth = new \Sabre\DAV\Auth\Plugin($authBackend); + $server->addPlugin($auth); + } + $server->exec(); + } +} \ No newline at end of file diff --git a/lib/webdav/File.php b/lib/webdav/File.php new file mode 100644 index 0000000..b3db9d1 --- /dev/null +++ b/lib/webdav/File.php @@ -0,0 +1,49 @@ +path = $path; + $this->file = $file; + $this->client = $client; + } + function getName() { + return $this->file->name(); + } + function get() { + $url = $this->file->url(); + if(!$url){ + //Url not present in list.Got it from client. + $this->file = $this->client->getFileInfo($this->path); + $url = $this->file->url(); + } + header("HTTP/1.1 301 TCShare Redirect"); + header("Location: ".$url); + exit; + } + function getSize() { + return $this->file->size(); + } + function getETag() { + return '"' . $this->file->size() . '"'; + } + function getLastModified(){ + return strtotime($this->file->timeModified()); + } + function getContentType(){ + $mimes = new MimeTypes; + $filemime=$mimes->getMimeType($this->file->extension()); + if(!$filemime)$filemime = "application/octet-stream"; + return $filemime; + } + public function getQuotaInfo(){ + return [ + 0, + 1024*1024*1024 + ]; + } +} \ No newline at end of file diff --git a/lib/webdav/Folder.php b/lib/webdav/Folder.php new file mode 100644 index 0000000..b42c8bb --- /dev/null +++ b/lib/webdav/Folder.php @@ -0,0 +1,40 @@ +current = $current; + $this->client = $client; + $this->path = $path; + } + function getChildren() { + list($folders,$files)=$this->client->listFiles($this->current); + $res=[]; + foreach($folders as $r){ + $res[]=new Folder(TC::path($this->path."/".$r->name()),$r,$this->client); + } + foreach($files as $r){ + $res[]=new File(TC::path($this->path."/".$r->name()),$r,$this->client); + } + return $res; + } + function childExists($name){ + return true; + } + function getName() { + return $this->current->name(); + } + function getLastModified(){ + return strtotime($this->current->timeModified()); + } + public function getQuotaInfo(){ + return [ + 0, + 1024*1024*1024 + ]; + } +} \ No newline at end of file diff --git a/lib/zip.php b/lib/zip.php new file mode 100644 index 0000000..1df7ecd --- /dev/null +++ b/lib/zip.php @@ -0,0 +1,135 @@ +zip = new ZipArchive; + } + /** + * 解压zip文件到指定文件夹 + * + * @access public + * @param string $zipfile 压缩文件路径 + * @param string $path 压缩包解压到的目标路径 + * @return booleam 解压成功返回 true 否则返回 false + */ + public function unzip ($zipfile, $path) { + if ($this->zip->open($zipfile) === true) { + $file_tmp = @fopen($zipfile, "rb"); + $bin = fread($file_tmp, 15); //只读15字节 各个不同文件类型,头信息不一样。 + fclose($file_tmp); + /* 只针对zip的压缩包进行处理 */ + if (true === $this->getTypeList($bin)) + { + $result = $this->zip->extractTo($path); + $this->zip->close(); + return $result; + } + else + { + return false; + } + } + return false; + } + /** + * 创建压缩文件 + * @access public + * @param string $zipfile 将要生成的压缩文件路径 + * @param strng $folder 将要被压缩的文件夹路径 + * @param array $ignored 要忽略的文件列表 + * @return booleam 压缩包生成成功返回true 否则返回 false + */ + public function zip ($zipfile, $folder, $ignored = null) { + $this->ignored_names = is_array($ignored) ? $ignored : $ignored ? array($ignored) : array(); + if ($this->zip->open($zipfile, ZIPARCHIVE::CREATE) !== true) { + throw new Exception("cannot open <$zipfile>\n"); + } + $folder = substr($folder, -1) == '/' ? substr($folder, 0, strlen($folder)-1) : $folder; + if(strstr($folder, '/')) { + $this->root = substr($folder, 0, strrpos($folder, '/')+1); + $folder = substr($folder, strrpos($folder, '/')+1); + } + $this->createZip($folder); + return $this->zip->close(); + } + /** + * 递归添加文件到压缩包 + * + * @access private + * @param string $folder 添加到压缩包的文件夹路径 + * @param string $parent 添加到压缩包的文件夹上级路径 + * @return void + */ + private function createZip ($folder, $parent=null) { + $full_path = $this->root . $parent . $folder; + $zip_path = $parent . $folder; + $this->zip->addEmptyDir($zip_path); + $dir = new DirectoryIterator($full_path); + foreach($dir as $file) { + if(!$file->isDot()) { + $filename = $file->getFilename(); + if(!in_array($filename, $this->ignored_names)) { + if($file->isDir()) { + $this->createZip($filename, $zip_path.'/'); + }else { + //第二个参数是重命名文件名,带上路径就可以改变当前文件在压缩包里面的路径. + $this->zip->addFile($full_path.'/'.$filename, $zip_path.'/'.$filename); + } + } + } + } + } + /** + * 读取压缩包文件与目录列表 + * + * @access public + * @param string $zipfile 压缩包文件 + * @return array 文件与目录列表 + */ + public function fileList($zipfile) { + $file_dir_list = array(); + $file_list = array(); + if ($this->zip->open($zipfile) == true) { + for ($i = 0; $i < $this->zip->numFiles; $i++) { + $numfiles = $this->zip->getNameIndex($i); + if (preg_match('/\/$/i', $numfiles)) + { + $file_dir_list[] = $numfiles; + } + else + { + $file_list[] = $numfiles; + } + } + } + return array('files'=>$file_list, 'dirs'=>$file_dir_list); + } + /** + * 得到文件头与文件类型映射表 + * + * @author wengxianhu + * @date 2013-08-10 + * @param $bin string 文件的二进制前一段字符 + * @return boolean + */ + private function getTypeList ($bin) + { + $array = array( + array("504B0304", "zip") + ); + foreach ($array as $v) + { + $blen = strlen(pack("H*", $v[0])); //得到文件头标记字节数 + $tbin = substr($bin, 0, intval($blen)); ///需要比较文件头长度 + if(strtolower($v[0]) == strtolower(array_shift(unpack("H*", $tbin)))) + { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/login.php b/login.php new file mode 100644 index 0000000..ee3ed58 --- /dev/null +++ b/login.php @@ -0,0 +1,90 @@ + top.location.href='" . $dialog_url . "'"); + } + //Step2:通过Authorization Code获取Access Token + if($_REQUEST['state']!=="" ) + { + //拼接URL + $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&" + . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) + . "&client_secret=" . $app_secret . "&code=" . $code; + $response = file_get_contents($token_url); + if (strpos($response, "callback") !== false) + { + $lpos = strpos($response, "("); + $rpos = strrpos($response, ")"); + $response = substr($response, $lpos + 1, $rpos - $lpos -1); + $msg = json_decode($response); + if (isset($msg->error)) + { + echo "

error:

" . $msg->error; + echo "

msg :

" . $msg->error_description; + exit; + } + } + //Step3:使用Access Token来获取用户的OpenID + $params = array(); + parse_str($response, $params); + $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token']; + $str = file_get_contents($graph_url); + if (strpos($str, "callback") !== false) + { + $lpos = strpos($str, "("); + $rpos = strrpos($str, ")"); + $str = substr($str, $lpos + 1, $rpos - $lpos -1); + } + $user = json_decode($str); + if (isset($user->error)) + { + echo "

error:

" . $user->error; + echo "

msg :

" . $user->error_description; + exit; + } + //cho("Hello " . $user->openid); + if(config("openid")==""){ + config("openid",$user->openid); + config("password",$user->openid); + setcookie("admin",config("password")); + header('Location:/'); + }elseif($user->openid==config("openid")){ + setcookie("admin",config("password")); + header('Location:/'); + }else{ + echo"不是管理员"; + } + + + } + else + { + echo("The state does not match. You may be a victim of CSRF."); + } + + + + + + // header('Location: '.$goto); + + \ No newline at end of file diff --git a/one.php b/one.php index e615a83..bd27389 100644 --- a/one.php +++ b/one.php @@ -3,32 +3,114 @@ die( "NoAccess" ); } require 'init.php'; + + ini_set('memory_limit', '128M'); + class one{ + static function cac(){ + echo CACHE_PATH; + } static function cache_clear(){ cache::clear(); } - static function cache_refresh(){ - //oneindex::refresh_cache(get_absolute_path(config('onedrive_root'))); + static function cache_refresh($drives="default"){ + echo "缓存更新"; +echo $drivesfile = ROOT.'config/'.$drives.'.php'; + +if (file_exists($drivesfile)) { + $配置文件 = include $drivesfile; + + + + + } + +define('CACHE_PATH', ROOT.'cache/'.$drives."/"); + +echo cache::$type = empty( config('cache_type') )?'secache':config('cache_type'); + echo onedrive::$client_id = $配置文件["client_id"]; + echo onedrive::$client_secret =$配置文件["client_secret"]; + echo onedrive::$redirect_uri = $配置文件["redirect_uri"]; + echo onedrive::$api_url = $配置文件["api_url"]; + echo onedrive::$oauth_url = $配置文件["oauth_url"]; + echo onedrive::$access_token=access_token($配置文件,$drives); + + onedrive::$typeurl=$配置文件["api"]; + + + + + + //oneindex::refresh_cache(get_absolute_path(config('onedrive_root'))); cache::refresh_cache(get_absolute_path(config('onedrive_root'))); + // 清除php文件缓存 cache::clear_opcache(); } - static function token_refresh(){ - $refresh_token = config('refresh_token'); + static function token_refresh($drives="default"){ + +$drivesfile = ROOT.'config/'.$drives.'.php'; + + + $配置文件 = include $drivesfile; + if( $配置文件==""){exit;} + + + + + +onedrive::$client_id = $配置文件["client_id"]; +onedrive::$client_secret =$配置文件["client_secret"]; +onedrive::$redirect_uri = $配置文件["redirect_uri"]; +onedrive::$api_url = $配置文件["api_url"]; +onedrive::$oauth_url = $配置文件["oauth_url"]; + + + $refresh_token = $配置文件['refresh_token']; $token = onedrive::get_token($refresh_token); - if(!empty($token['refresh_token'])){ - config('@token', $token); - } + +$配置文件["access_token"]=$token["access_token"]; + $配置文件['expires_on'] = time()+ $token['expires_in']; + config("@".$drives,$配置文件 ); + echo" 刷新成功"; + } - static function upload_file($localfile, $remotefile=null){ + static function upload_file($localfile, $remotefile=null,$drives="default"){ + + +$drivesfile = ROOT.'config/'.$drives.'.php'; + + + $配置文件 = include $drivesfile; + + + + + + +onedrive::$client_id = $配置文件["client_id"]; +onedrive::$client_secret =$配置文件["client_secret"]; +onedrive::$redirect_uri = $配置文件["redirect_uri"]; +onedrive::$api_url = $配置文件["api_url"]; +onedrive::$oauth_url = $配置文件["oauth_url"]; + onedrive::$access_token=access_token($配置文件,$驱动器); +onedrive::$typeurl=$配置文件["api"] ; + + + + + + + + $localfile = realpath($localfile); if(!file_exists($localfile)){ - exit('file not exists'); + print ' 本地文件不存在'; } print ' 本地文件:'.$localfile.PHP_EOL; @@ -43,9 +125,10 @@ static function upload_file($localfile, $remotefile=null){ print ' 远程文件:'.$remotepath.PHP_EOL; $filesize = onedrive::_filesize($localfile) OR die('无法获取文件大小'); - if($filesize < 10485760){ + if($filesize < 10){ print ' 上传方式:直接上传'.PHP_EOL; $begin_time = microtime(true); + $result = onedrive::upload($remotepath, file_get_contents($localfile)); if(!empty($result)){ $upload_time = microtime(true) - $begin_time; @@ -111,6 +194,7 @@ static function folder2upload($localfolder, $remotefolder){ static function upload_large_file($localfile, $remotepath){ + print ' 创建上传会话'.PHP_EOL; fetch::init([CURLOPT_TIMEOUT=>200]); $upload = config('@upload'); $info = $upload[$remotepath]; @@ -181,6 +265,49 @@ static function upload_large_file($localfile, $remotepath){ } + + + + +static function ls ($path="/",$drives="default"){ + + +$drivesfile = ROOT.'config/'.$drives.'.php'; + + + $配置文件 = include $drivesfile; + + + + + + +onedrive::$client_id = $配置文件["client_id"]; +onedrive::$client_secret =$配置文件["client_secret"]; +onedrive::$redirect_uri = $配置文件["redirect_uri"]; +onedrive::$api_url = $配置文件["api_url"]; +onedrive::$oauth_url = $配置文件["oauth_url"]; + onedrive::$access_token=access_token($配置文件,$驱动器); +onedrive::$typeurl=$配置文件["api"] ; + + + + + print "列目录"; + + $item=onedrive::dir($path); + foreach ($item as $item) + { + + echo $path."/".$item["name"].$item["id"]."\n"; + } + + + + + + +} } @@ -195,10 +322,10 @@ static function upload_large_file($localfile, $remotepath){ ?> oneindex commands : cache - cache:clear clear cache - cache:refresh refresh cache + cache:clear clear cache + cache:refresh refresh cache token - token:refresh refresh token - upload - upload:file upload a file to onedrive - upload:folder upload a folder to onedrive +token:refresh 参数说明 php one.php token:refresh 驱动器名称(default) +upload文件上传 非默认盘时候不能省列远程路径 +upload:file 参数说明 php one.php upload:file 本地文件 远程路径 驱动器名称(default) +upload:folder 参数说明 php one.php upload:folder 本地文件 远程路径 驱动器名称(default) diff --git a/page.html b/page.html new file mode 100644 index 0000000..24c12b0 --- /dev/null +++ b/page.html @@ -0,0 +1,22 @@ + + + + +Untitled Document + + + + + + + + diff --git a/pass b/pass new file mode 100644 index 0000000..c312f5a --- /dev/null +++ b/pass @@ -0,0 +1 @@ +foo:SabreDAV:5790c3784a79a018d1186528df520e11 \ No newline at end of file diff --git a/php.php b/php.php new file mode 100644 index 0000000..75b9612 --- /dev/null +++ b/php.php @@ -0,0 +1,7 @@ +buildFromDirectory(__DIR__.'/','/\.php$/'); //从哪个文件夹打包 参数1为程序根目录(最好用__DIR__等魔术常量) 参数2是正则表达式(选填)表示要打包文件的后缀 +$phar->compressFiles(phar::GZ); //压缩方式 +$phar->stopBuffering(); //停止缓冲 +$a=$phar->createDefaultStub('./index.php'); //程序入口文件 +$phar->setStub($a); \ No newline at end of file diff --git a/sharepoint.php b/sharepoint.php new file mode 100644 index 0000000..304defe --- /dev/null +++ b/sharepoint.php @@ -0,0 +1,57 @@ + +   +   +'; +exit; + + + +} + $request['headers'] = "Authorization: bearer {$config["access_token"]}".PHP_EOL."Content-Type: application/json".PHP_EOL; + $request["url"]='https://microsoftgraph.chinacloudapi.cn/v1.0/sites/root'; + $resp=fetch::get($request) ; + $data = json_decode($resp->content, true); + $hostname= $data["siteCollection"]["hostname"]; + + $getsiteid='https://microsoftgraph.chinacloudapi.cn/v1.0/sites/'.$hostname.':'.$_GET["site"]; + $request["url"]=$getsiteid; + $respp=fetch::get($request) ; + $datass = json_decode($respp->content, true); + +echo $siteidurl=($datass["id"]); +if (($datass["id"])==""){echo "获取站点id失败刷新重试试"; + + echo '站点名称填写/sites/名称或者/teams/名称'; + echo '
+   +   +'; + +exit;} +$b = ' +进入后台刷新缓存生效 默认密码oneindex'; diff --git a/test.php b/test.php new file mode 100644 index 0000000..abe2106 --- /dev/null +++ b/test.php @@ -0,0 +1,92 @@ + $api, + 'headers' => [ + 'Accept' => 'application/json', + 'Authorization' => $access, + 'Content-Type' => 'application/json', + ], + 'http_errors' => false +]); + + return json_decode($apc->get($url)->getBody()); + + + +} + + + + + + +function get_drivebyname($token,$name="/me",$type="cn") + +{ if($type=="cn"){ + $api="https://microsoftgraph.chinacloudapi.cn/v1.0/"; + }else{ + $api="https://graph.microsoft.com/v1.0/"; + } + $apc=new Client([ + 'base_uri' => $api, + 'headers' => [ + 'Accept' => 'application/json', + 'Authorization' => $token, + 'Content-Type' => 'application/json', + ], + 'http_errors' => false +]); +if($name=="/me"){ + return $data=json_decode($apc->get("me/drive/")->getBody()); +}else{ + + $hostname=json_decode($apc->get("sites/root")->getBody())->siteCollection->hostname; + $siteid=json_decode(($apc->get("sites/". $hostname.":".$name)->getBody()))->id; + return $driveid=json_decode($apc->get("sites/".($siteid."/drive"))->getBody());} + +} +$t1=microtime(true); +$clients = new Client([ + + + 'http_errors' => false +]); + + +// Initiate each request but do not block +$promises = array(); + for ($i;$i<30;$i++){ + $promises[$i] = $clients->requestAsync('get', 'https://www.hostloc.com/forum-45-1.html'); + } + + + +// Wait on all of the requests to complete. +$results = Promise\unwrap($promises); + + + +foreach ($results as $k=>$v){ + echo "1"; + $v->getBody(); + +} +$t2=microtime(true); +echo $time1=$t2-$t1; \ No newline at end of file diff --git a/timg.jpeg b/timg.jpeg new file mode 100644 index 0000000..d863c5b Binary files /dev/null and b/timg.jpeg differ diff --git a/version.json b/version.json new file mode 100644 index 0000000..eaf8c9f --- /dev/null +++ b/version.json @@ -0,0 +1 @@ +9.3 \ No newline at end of file diff --git a/version.php b/version.php new file mode 100644 index 0000000..1dd9b09 --- /dev/null +++ b/version.php @@ -0,0 +1 @@ +9.21 \ No newline at end of file diff --git a/view/404.php b/view/404.php new file mode 100644 index 0000000..2b56657 --- /dev/null +++ b/view/404.php @@ -0,0 +1,5 @@ + + + +
404
+ \ No newline at end of file diff --git a/view/admin/install/install_0.php b/view/admin/install/install_0.php index 3f84402..2e31a18 100644 --- a/view/admin/install/install_0.php +++ b/view/admin/install/install_0.php @@ -4,7 +4,7 @@
-

程序安装 环境检测

+

系统安装 环境检测

diff --git a/view/admin/install/install_1.php b/view/admin/install/install_1.php index 74f259e..67a5f99 100644 --- a/view/admin/install/install_1.php +++ b/view/admin/install/install_1.php @@ -1,46 +1,71 @@ - + + + + + + - -
-

程序安装 应用ID和机密

+

系统安装 设置应用ID和世纪互联(世纪互联无需填写,国际版自行注册应用支持无api权限账户)

- 填入client_idclient_secret, - 获取应用ID和机密(分两个页面显示,请注意保存) + 填入client_idclient_secret

-
+ + +
+ + + + + + + +
+ + + + +
+ + + https + - -
应用机密不能为空
+ +
-
-
+ +
+ https + - -
应用 ID不能为空
+ +
-
- -
+ +
- - - - - - + +
重定向URL不能为空
-
上一步 @@ -48,4 +73,4 @@
- \ No newline at end of file + \ No newline at end of file diff --git a/view/admin/install/install_2.php b/view/admin/install/install_2.php index 1cebd6f..4614a0c 100644 --- a/view/admin/install/install_2.php +++ b/view/admin/install/install_2.php @@ -4,10 +4,20 @@
-

程序安装 绑定微软账号

+

系统安装 绑定账号

+ + + 上一步 绑定账号 diff --git a/view/admin/install/install_3.php b/view/admin/install/install_3.php index c81de70..981c3db 100644 --- a/view/admin/install/install_3.php +++ b/view/admin/install/install_3.php @@ -4,13 +4,33 @@
-

程序安装 完成安装

+

系统安装 完成安装

-

程序安装成功!

+

授权成功!

+ 初始密码:

- 管理后台(初始密码:oneindex) + + + +
+
+ + + + + + + 管理后台 访问网站

程序安装失败!

diff --git a/view/admin/install/layout.php b/view/admin/install/layout.php index 4a4a179..41c3500 100644 --- a/view/admin/install/layout.php +++ b/view/admin/install/layout.php @@ -4,8 +4,8 @@ OneIndex <?php e($title);?> - - + + + + +
+
+ + $l):?> + chevron_right + + + +
+
+ +
+ +
+ + \ No newline at end of file diff --git a/view/classic/password.php b/view/classic/password.php new file mode 100644 index 0000000..c421419 --- /dev/null +++ b/view/classic/password.php @@ -0,0 +1,24 @@ + + + + +
+
+

这是一个受保护的文件夹,您需要提供访问密码才能查看。

+ +
+ https + + +
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/view/classic/show/audio.php b/view/classic/show/audio.php new file mode 100644 index 0000000..8ade9a1 --- /dev/null +++ b/view/classic/show/audio.php @@ -0,0 +1,36 @@ + + + + +
+
+
+
+ +
+
+ +
+ + +
+
+ + +
+
+file_download + + + + diff --git a/view/classic/show/code.php b/view/classic/show/code.php new file mode 100644 index 0000000..8cc5f0b --- /dev/null +++ b/view/classic/show/code.php @@ -0,0 +1,53 @@ + + + + +
+
+
+
+ + +
+file_download + + + + + \ No newline at end of file diff --git a/view/classic/show/doc.php b/view/classic/show/doc.php new file mode 100644 index 0000000..abe38a6 --- /dev/null +++ b/view/classic/show/doc.php @@ -0,0 +1,9 @@ + diff --git a/view/classic/show/image.php b/view/classic/show/image.php new file mode 100644 index 0000000..6a3ca7c --- /dev/null +++ b/view/classic/show/image.php @@ -0,0 +1,24 @@ + + + + +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+
+file_download + diff --git a/view/classic/show/pdf.php b/view/classic/show/pdf.php new file mode 100644 index 0000000..5d5d5a6 --- /dev/null +++ b/view/classic/show/pdf.php @@ -0,0 +1,30 @@ + + + + +file_download + + \ No newline at end of file diff --git a/view/classic/show/stream.php b/view/classic/show/stream.php new file mode 100644 index 0000000..ec3193e --- /dev/null +++ b/view/classic/show/stream.php @@ -0,0 +1,105 @@ +'application/octet-stream', + 'ppt'=>'application/vnd.ms-powerpoint', + 'xls'=>'application/vnd.ms-excel', + 'doc'=>'application/msword', + 'exe'=>'application/octet-stream', + 'rar'=>'application/octet-stream', + 'js'=>"javascrīpt/js", + 'css'=>"text/css", + 'hqx'=>"application/mac-binhex40", + 'bin'=>"application/octet-stream", + 'oda'=>"application/oda", + 'pdf'=>"application/pdf", + 'ai'=>"application/postsrcipt", + 'eps'=>"application/postsrcipt", + 'es'=>"application/postsrcipt", + 'rtf'=>"application/rtf", + 'mif'=>"application/x-mif", + 'csh'=>"application/x-csh", + 'dvi'=>"application/x-dvi", + 'hdf'=>"application/x-hdf", + 'nc'=>"application/x-netcdf", + 'cdf'=>"application/x-netcdf", + 'latex'=>"application/x-latex", + 'ts'=>"application/x-troll-ts", + 'src'=>"application/x-wais-source", + 'zip'=>"application/zip", + 'bcpio'=>"application/x-bcpio", + 'cpio'=>"application/x-cpio", + 'gtar'=>"application/x-gtar", + 'shar'=>"application/x-shar", + 'sv4cpio'=>"application/x-sv4cpio", + 'sv4crc'=>"application/x-sv4crc", + 'tar'=>"application/x-tar", + 'ustar'=>"application/x-ustar", + 'man'=>"application/x-troff-man", + 'sh'=>"application/x-sh", + 'tcl'=>"application/x-tcl", + 'tex'=>"application/x-tex", + 'texi'=>"application/x-texinfo", + 'texinfo'=>"application/x-texinfo", + 't'=>"application/x-troff", + 'tr'=>"application/x-troff", + 'roff'=>"application/x-troff", + 'shar'=>"application/x-shar", + 'me'=>"application/x-troll-me", + 'ts'=>"application/x-troll-ts", + 'gif'=>"image/gif", + 'jpeg'=>"image/pjpeg", + 'jpg'=>"image/pjpeg", + 'jpe'=>"image/pjpeg", + 'ras'=>"image/x-cmu-raster", + 'pbm'=>"image/x-portable-bitmap", + 'ppm'=>"image/x-portable-pixmap", + 'xbm'=>"image/x-xbitmap", + 'xwd'=>"image/x-xwindowdump", + 'ief'=>"image/ief", + 'tif'=>"image/tiff", + 'tiff'=>"image/tiff", + 'pnm'=>"image/x-portable-anymap", + 'pgm'=>"image/x-portable-graymap", + 'rgb'=>"image/x-rgb", + 'xpm'=>"image/x-xpixmap", + 'txt'=>"text/plain", + 'c'=>"text/plain", + 'cc'=>"text/plain", + 'h'=>"text/plain", + 'html'=>"text/html", + 'htm'=>"text/html", + 'htl'=>"text/html", + 'txt'=>"text/html", + 'php'=>"text/html", + 'rtx'=>"text/richtext", + 'etx'=>"text/x-setext", + 'tsv'=>"text/tab-separated-values", + 'mpeg'=>"video/mpeg", + 'mpg'=>"video/mpeg", + 'mpe'=>"video/mpeg", + 'avi'=>"video/x-msvideo", + 'qt'=>"video/quicktime", + 'mov'=>"video/quicktime", + 'moov'=>"video/quicktime", + 'movie'=>"video/x-sgi-movie", + 'au'=>"audio/basic", + 'snd'=>"audio/basic", + 'wav'=>"audio/x-wav", + 'aif'=>"audio/x-aiff", + 'aiff'=>"audio/x-aiff", + 'aifc'=>"audio/x-aiff", + 'swf'=>"application/x-shockwave-flash", + 'myz'=>"application/myz" +]; +//大于 5M 跳转为直连下载 +if($item['size'] > 5242880){ + header('Location: '.$item['downloadUrl']);exit(); +} +$type = empty($types[$ext])?"application/octet-stream":$types[$ext]; +$content = IndexController::get_content($item); + +header('Content-type: '.$type); +echo $content; +exit(); +?> diff --git a/view/classic/show/video.php b/view/classic/show/video.php new file mode 100644 index 0000000..9a8f888 --- /dev/null +++ b/view/classic/show/video.php @@ -0,0 +1,35 @@ + + + + +
+
+
+
+ +
+ + +
+
+ + +
+
+'); } ?> + + +file_download + diff --git a/view/classic/show/video2.php b/view/classic/show/video2.php new file mode 100644 index 0000000..cfb1d08 --- /dev/null +++ b/view/classic/show/video2.php @@ -0,0 +1,42 @@ + + + + + + + + +
+
+
+
+ +
+ + +
+
+ + +
+
+ +file_download + \ No newline at end of file diff --git a/view/classic/show/video5.php b/view/classic/show/video5.php new file mode 100644 index 0000000..69f5e4d --- /dev/null +++ b/view/classic/show/video5.php @@ -0,0 +1,25 @@ + + + + + +
+
+ +
+ +
+ + +
+
+ + +
+
+file_download + \ No newline at end of file diff --git a/view/material/list.php b/view/material/list.php index 8c78e9b..6e168ed 100644 --- a/view/material/list.php +++ b/view/material/list.php @@ -84,6 +84,7 @@ function file_ico($item){
+ + \ No newline at end of file diff --git a/view/nexmoe/404.php b/view/nexmoe/404.php index c2a8717..2b56657 100644 --- a/view/nexmoe/404.php +++ b/view/nexmoe/404.php @@ -1,5 +1,5 @@ -
404 not found.
+
404
\ No newline at end of file diff --git a/view/nexmoe/guest.js b/view/nexmoe/guest.js new file mode 100644 index 0000000..574ab38 --- /dev/null +++ b/view/nexmoe/guest.js @@ -0,0 +1,275 @@ +var $$ = mdui.JQ; +$$(function() { + $$('.file .iframe').each(function() { + $$(this).on('click', function() { + layer.open({ + type: 2, + title: ''+ $$(this).find('span').text()+'(点击新窗口打开)', //如伪静态去除了/?/,需把"&s=1"改为"?s",或者改为以post请求这个链接//jia + //shadeClose: true, + move: false, + shade: false, + maxmin: true, + area: ['100%', '100%'], + content: $$(this).attr('href')+"?s" //如伪静态去除了/?/,需把"&s=1"改为"?s",或者改为以post请求这个链接//le + ,min: function(layero){ + //zi; + layero.css({top: '90%'}) + } + }); + return false; + }); + }); + $('.file .dl').each(function () { + $(this).on('click', function () { + var form = $('
').attr('action', $(this).attr('href')).get(0); + $(document.body).append(form); + form.submit(); + $(form).remove(); + return false; + }); + }); +}); +window.TC=window.TC||{}; +jQuery(".file .audio").click(function(e){ + e.preventDefault(); + TC.preview_audio(this); +}); +TC.preview_audio = function(aud){ + if(!TC.aplayer){ + TC.aplayerList=[]; + jQuery(".file .audio").each(function(){ + var ext = jQuery(this).data("readypreview"); + var n = jQuery(this).find("span").text(); + var l = n.replace("."+ext,".lrc"); + var la = jQuery('a[data-name="'+l+'"]'); + var lrc = undefined; + if(la.length>0){ + lrc = la[0].href+"?s"; + } + TC.aplayerList.push({ + name:n, + url:this.href, + artist:" ", + lrc:lrc + }); + }) + jQuery('
').appendTo("body"); + TC.aplayer = new APlayer({ + container: document.getElementById('aplayer'), + fixed: true, + audio: TC.aplayerList, + lrcType: 3 + }); + } + var k=-1; + for(var i in TC.aplayerList){ + if(TC.aplayerList[i].name==jQuery(aud).data("name")){ + k=i; + break; + } + } + if(k>=0){ + TC.aplayer.list.switch(k); + TC.aplayer.play(); + TC.aplayer.setMode("normal"); + } +} + +$ = mdui.JQ; +$.fn.extend({ + sortElements: function (comparator, getSortable) { + getSortable = getSortable || function () { return this; }; + + var placements = this.map(function () { + var sortElement = getSortable.call(this), + parentNode = sortElement.parentNode, + nextSibling = parentNode.insertBefore( + document.createTextNode(''), + sortElement.nextSibling + ); + + return function () { + parentNode.insertBefore(this, nextSibling); + parentNode.removeChild(nextSibling); + }; + }); + + return [].sort.call(this, comparator).each(function (i) { + placements[i].call(getSortable.call(this)); + }); + } +}); +var lightbox = GLightbox(); +function downall() { + let dl_link_list = Array.from(document.querySelectorAll("li a")) + .map(x => x.href) // 所有list中的链接 + .filter(x => x.slice(-1) != "/"); // 筛选出非文件夹的文件下载链接 + + let blob = new Blob([dl_link_list.join("\r\n")], { + type: 'text/plain' + }); // 构造Blog对象 + let a = document.createElement('a'); // 伪造一个a对象 + a.href = window.URL.createObjectURL(blob); // 构造href属性为Blob对象生成的链接 + a.download = "folder_download_link.txt"; // 文件名称,你可以根据你的需要构造 + a.click() // 模拟点击 + a.remove(); +} + +function thumb(){ + if($('#thumb i').text() == "apps"){ + $('#thumb i').text("format_list_bulleted"); + $('.nexmoe-item').removeClass('thumb'); + $('.nexmoe-item .mdui-icon').show(); + $('.nexmoe-item .mdui-list-item').css("background",""); + }else{ + $('#thumb i').text("apps"); + $('.nexmoe-item').addClass('thumb'); + $('.mdui-col-xs-12 i.mdui-icon').each(function(){ + if($(this).text() == "image" || $(this).text() == "ondemand_video"){ + var href = $(this).parent().parent().attr('href'); + var thumb =(href.indexOf('?') == -1)?'?t=220':'&t=220'; + $(this).hide(); + $(this).parent().parent().parent().css("background","url("+href+thumb+") no-repeat center top"); + } + }); + } + +} + +$(function(){ + + + $('.icon-sort').on('click', function () { + let sort_type = $(this).attr("data-sort"), sort_order = $(this).attr("data-order"); + let sort_order_to = (sort_order === "less") ? "more" : "less"; + + $('li[data-sort]').sortElements(function (a, b) { + let data_a = $(a).attr("data-sort-" + sort_type), data_b = $(b).attr("data-sort-" + sort_type); + let rt = data_a.localeCompare(data_b, undefined, {numeric: true}); + return (sort_order === "more") ? 0-rt : rt; + }); + + $(this).attr("data-order", sort_order_to).text("expand_" + sort_order_to); + }); + + + +}); + +var ckname='image_mode'; +function getCookie(name) +{ + var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); + if(arr=document.cookie.match(reg)) + return unescape(arr[2]); + else + return null; +} +function setCookie(key,value,day){ + var exp = new Date(); + exp.setTime(exp.getTime() - 1); + var cval=getCookie(key); + if(cval!=null) + document.cookie= key + "="+cval+";expires="+exp.toGMTString(); + var date = new Date(); + var nowDate = date.getDate(); + date.setDate(nowDate + day); + var cookie = key+"="+value+"; expires="+date; + document.cookie = cookie; + return cookie; +} +$('#image_view').on('click', function () { + if($(this).prop('checked') == true){ + setCookie(ckname,1,1); + window.location.href=window.location.href; + }else{ + setCookie(ckname,0,1); + window.location.href=window.location.href; + } +}); + + function checkall(){ + var box = document.getElementById("sellall"); + var loves = document.getElementsByName("itemid"); + if(box.checked == false){ + for (var i = 0; i < loves.length; i++) { + loves[i].checked = false; + } + }else{ + for (var i = 0; i < loves.length; i++) { + loves[i].checked = true; + } + } + onClickHander(); + } + + + function onClickHander(){ + + obj = document.getElementsByName("itemid"); + check_val = []; + for(k in obj){ + if(obj[k].checked) + check_val.push(obj[k].value); + } + //alert(check_val); +console.log(check_val); + + + if(check_val!=""){ + var div=document.getElementById("mangger"); + div.style.display='block'; + + }else{ + var div=document.getElementById("mangger"); + div.style.display='none'; + }; + + + + + } + + + + + + + function sellcheckbox() +{ obj = document.getElementsByName("itemid"); + + check_val = []; + for(k in obj){ + if(obj[k].checked) + check_val.push(obj[k].value); + } + //alert(check_val); +console.log(check_val); + data=JSON.stringify(check_val); + + +console.log(data); + +} + + /////////////重建缓存 + function deldel(){ + + Cookies.remove('moveitem') + var xhr = new XMLHttpRequest(); + xhr.withCredentials = true; + xhr.addEventListener("readystatechange", function() { + if(this.readyState === 4) { + console.log(this.responseText); + location.reload(); + } + }); + +xhr.open("GET", "/del.php"); + xhr.send(); +} + + function logout() { + document.cookie = "admin=; path=/"; + location.href = location.href; + } \ No newline at end of file diff --git a/view/nexmoe/images/layout.php b/view/nexmoe/images/layout.php index fd6a06f..cca4c3a 100644 --- a/view/nexmoe/images/layout.php +++ b/view/nexmoe/images/layout.php @@ -4,9 +4,9 @@ <?php e($title.' - '.config('site_name'));?> - + - +
diff --git a/view/nexmoe/layout.php b/view/nexmoe/layout.php index 18f03a2..381356f 100644 --- a/view/nexmoe/layout.php +++ b/view/nexmoe/layout.php @@ -1,41 +1,253 @@ - - - <?php e(config('site_name'));?> - 私人云服务 - - - - + + + <?php e($title.' - '.config('site_name'));?> + + + + + + + + + + + - -
- \ No newline at end of file + + + + diff --git a/view/nexmoe/list.php b/view/nexmoe/list.php index 524b522..acd927f 100644 --- a/view/nexmoe/list.php +++ b/view/nexmoe/list.php @@ -1,22 +1,66 @@ + + + + + + + + + + + + + - - -
@@ -31,7 +75,7 @@ function file_ico($item){ display: none; } .thumb .mdui-list-item a ,.thumb .mdui-list-item { - width:217px; + width:213px; height: 230px; float: left; margin: 10px 10px !important; @@ -46,7 +90,7 @@ function file_ico($item){ font-size:100px; display: block; margin-top: 40px; - color: #7e7e7e; + color: #7ab5ef; } .thumb .mdui-list-item span{ float: left; @@ -56,18 +100,31 @@ function file_ico($item){ position: absolute; top: 180px; } +.thumb .forcedownload { + display: none; + + -
-
-
- face - README.md -
- +
+
+ face + README.md
+
+ +
+ + + +
+ +
+ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -format_list_bulleted + + + diff --git a/view/nexmoe/manger.js b/view/nexmoe/manger.js new file mode 100644 index 0000000..fdcb084 --- /dev/null +++ b/view/nexmoe/manger.js @@ -0,0 +1,400 @@ +///////////////////文件管理模块/////////////////////////////////////////// + + +///////文件上传 +function uploadfieone(){ + document.getElementById('upload_file').webkitdirectory=""; + document.getElementById("upload_file").click(); + } +//////文件夹上传 +function uploadfietwo(){ + document.getElementById('upload_file').webkitdirectory=1; + document.getElementById("upload_file").click(); + } +//新建文件夹 +function create_folder() + { + mdui.prompt('新建文件夹', + function (value) { + var url="/"+驱动器+"/"+请求路径; + var xhr4 = new XMLHttpRequest(); + xhr4.withCredentials = true; + xhr4.addEventListener("readystatechange", function() { + if(this.readyState === 4) { + + console.log(this.responseText); + deldel()} + }); +xhr4.open("GET", ""+"?create_folder="+value); +xhr4.send(); +console.log(xhr4); + + }, + function (value) { + + } +); + + } +//单文件删除 +function delitem(){ + + var id = Cookies.get('flieid') + + data=JSON.stringify(id); + alert("确认删除"+data) + var myHeaders = new Headers(); + myHeaders.append("Content-Type", "application/json"); + var raw = data; + var requestOptions = { + method: 'DELETE', + headers: myHeaders, + body: raw, + redirect: 'follow' +}; + +fetch("/"+驱动器+"/?action=dellist", requestOptions) + .then(response => response.text() + ) + .then(data=>{alert(data); + deldel();//清空缓存 + }) + + .then(result => console.log(result)) + .catch(error => console.log('error', error)); + +} + + ////批量删除文件函数 +function dellistitem(){ + obj = document.getElementsByName("itemid"); + check_val = []; + for(k in obj){ + if(obj[k].checked) + check_val.push(obj[k].value); + } + + console.log(check_val); + data=JSON.stringify(check_val); + alert("确认删除"+data) + var myHeaders = new Headers(); + myHeaders.append("Content-Type", "application/json"); + var raw = data; + var requestOptions = { + method: 'DELETE', + headers: myHeaders, + body: raw, + redirect: 'follow' +}; + +fetch("/"+驱动器+"/?action=dellist", requestOptions) + .then(response => response.text() + ) + .then(data=>{alert(data); + deldel();//清空缓存 + }) + + .then(result => console.log(result)) + .catch(error => console.log('error', error)); + +} + +/////文件重命名 +function renamebox(){ + mdui.prompt('重命名', + function (value) { + var id = Cookies.get('flieid') + var xhr4 = new XMLHttpRequest(); + xhr4.withCredentials = true; + xhr4.addEventListener("readystatechange", function() { + if(this.readyState === 4) { + console.log(this.responseText);deldel()} + }); +xhr4.open("GET", "/"+驱动器+"/?rename="+id+"&name="+value); +xhr4.send(); +console.log(xhr4); + + }, + function (value) { + + } +); +} + +///剪切文件 + function moveitem(){ + obj = document.getElementsByName("itemid"); + + check_val = []; + for(k in obj){ + if(obj[k].checked) + check_val.push(obj[k].value); + } + //alert(check_val); +console.log(check_val); + data=JSON.stringify(check_val); + alert(data); + Cookies.set('moveitem', data, { expires: 0.025 }); + +} + +///粘贴文件axios + function pastitem(){ + var url=location+"?this=path" ; + ajaxLoading(); + axios.get(url) + .then(function (response) { + dataid=(response.data) + ajaxLoadEnd() + var move= Cookies.get('moveitem'); + if(typeof move == "undefined") { + return false; + } + alert ("粘贴"+move+"到"+dataid) + ajaxLoading(); + var urls="/"+驱动器+"/?filemanger=move&id="+move+"&newid="+dataid; + axios.get(urls) + .then(function (response) { + ajaxLoadEnd() + deldel(); + console.log(response); + }) + .catch(function (error) { + console.log(error); + }); + + }) + .catch(function (error) { + console.log(error); + }); + + + } + + + + +////////////////文件上传函数 + +function ajaxLoading() { + layer.msg('文件移动中请等待', { + icon: 16 + ,shade: 0.1 +}); + } + + function ajaxLoadEnd() { + layer.closeAll('loading'); + } + + function uploadbuttonhide() { + document.getElementById('exampleDialog').style.display='block'; + + } + function uploadkill() { + document.getElementById('exampleDialog').style.display='none'; + deldel() + } + function preup() { + + + + // uploadbuttonhide(); + var files=document.getElementById('upload_file').files; + if (files.length<1) { + uploadbuttonhide() + return; + }; + var table1=document.createElement('table'); + document.getElementById('upload_div').appendChild(table1); + table1.setAttribute('class','list-table'); + var timea=new Date().getTime(); + var i=0; + getuplink(i); + function getuplink(i) { + + var file=files[i]; + var tr1=document.createElement('tr'); + table1.appendChild(tr1); + tr1.setAttribute('data-to',1); + var td1=document.createElement('td'); + tr1.appendChild(td1); + td1.setAttribute('style','width:30%;word-break:break-word;'); + td1.setAttribute('id','upfile_td1_'+timea+'_'+i); + td1.innerHTML=(file.webkitRelativePath||file.name)+'
'+size_format(file.size); + var td2=document.createElement('td'); + tr1.appendChild(td2); + td2.setAttribute('id','upfile_td2_'+timea+'_'+i); + if (file.size>15*1024*1024*1024) { + td2.innerHTML='文件过大,终止上传。'; + uploadbuttonshow(); + return; + } + upbigfilename = encodeURIComponent((file.webkitRelativePath||file.name)); + + td2.innerHTML='获取上传链接 ...'; + var xhr1 = new XMLHttpRequest(); + xhr1.open("GET", "/"+驱动器+"/"+请求路径+'?action=upbigfile&upbigfilename='+ upbigfilename +'&filesize='+ file.size +'&lastModified='+ file.lastModified); + xhr1.setRequestHeader('x-requested-with','XMLHttpRequest'); + xhr1.send(null); + xhr1.onload = function(e){ + td2.innerHTML=''+xhr1.responseText+''; + if (xhr1.status==200) { + + console.log(xhr1.responseText); + var html=JSON.parse(xhr1.responseText); + if (!html['uploadUrl']) { + td2.innerHTML=''+xhr1.responseText+'
'; + uploadbuttonshow(); + } else { + td2.innerHTML='开始上传 ...'; + binupfile(file,html['uploadUrl'],timea+'_'+i, upbigfilename); + } + } + if (xhr1.status==409) { + td2.innerHTML='md5: '+filemd5; + tdnum = timea+'_'+i; + document.getElementById('upfile_td1_'+tdnum).innerHTML='
'+document.getElementById('upfile_td1_'+tdnum).innerHTML+'上传完成'; + + + } + if (i1024) { + num=num/1024; + } else { + return num.toFixed(2) + ' B'; + } + if (num>1024) { + num=num/1024; + } else { + return num.toFixed(2) + ' KB'; + } + if (num>1024) { + num=num/1024; + } else { + return num.toFixed(2) + ' MB'; + } + return num.toFixed(2) + ' GB'; + } + function binupfile(file,url,tdnum,filename){ + var label=document.getElementById('upfile_td2_'+tdnum); + var reader = new FileReader(); + var StartStr=''; + var MiddleStr=''; + var StartTime; + var EndTime; + var newstartsize = 0; + if(!!file){ + var asize=0; + var totalsize=file.size; + var xhr2 = new XMLHttpRequest(); + xhr2.open("GET", url); + //xhr2.setRequestHeader('x-requested-with','XMLHttpRequest'); + xhr2.send(null); + xhr2.onload = function(e){ + if (xhr2.status==200) { + var html = JSON.parse(xhr2.responseText); + var a = html['nextExpectedRanges'][0]; + newstartsize = Number( a.slice(0,a.indexOf("-")) ); + StartTime = new Date(); + asize = newstartsize; + if (newstartsize==0) { + StartStr='开始于:' +StartTime.toLocaleString()+'
' ; + } else { + StartStr='上次上传'+size_format(newstartsize)+ '
本次开始于:' +StartTime.toLocaleString()+'
' ; + } + var chunksize=5*1024*1024; // chunk size, max 60M. 每小块上传大小,最大60M,微软建议10M + if (totalsize>200*1024*1024) chunksize=100*1024*1024; + function readblob(start) { + var end=start+chunksize; + var blob = file.slice(start,end); + reader.readAsArrayBuffer(blob); + } + readblob(asize); + + reader.onload = function(e){ + var binary = this.result; + var xhr = new XMLHttpRequest(); + xhr.open("PUT", url, true); + //xhr.setRequestHeader('x-requested-with','XMLHttpRequest'); + bsize=asize+e.loaded-1; + xhr.setRequestHeader('Content-Range', 'bytes ' + asize + '-' + bsize +'/'+ totalsize); + xhr.upload.onprogress = function(e){ + if (e.lengthComputable) { + var tmptime = new Date(); + var tmpspeed = e.loaded*1000/(tmptime.getTime()-C_starttime.getTime()); + var remaintime = (totalsize-asize-e.loaded)/tmpspeed; + label.innerHTML=StartStr+'上传 ' +size_format(asize+e.loaded)+ ' / '+size_format(totalsize) + ' = ' + ((asize+e.loaded)*100/totalsize).toFixed(2) + '% 平均速度:'+size_format((asize+e.loaded-newstartsize)*1000/(tmptime.getTime()-StartTime.getTime()))+'/s
即时速度 '+size_format(tmpspeed)+'/s 预计还要 '+remaintime.toFixed(1)+'s'; + } + } + var C_starttime = new Date(); + xhr.onload = function(e){ + if (xhr.status<500) { + var response=JSON.parse(xhr.responseText); + if (response['size']>0) { + // contain size, upload finish. 有size说明是最终返回,上传结束 + var xhr3 = new XMLHttpRequest(); + xhr3.open("GET", '?action=del_upload_cache&filelastModified='+file.lastModified+'&filesize='+file.size+'&filename='+filename); + xhr3.setRequestHeader('x-requested-with','XMLHttpRequest'); + xhr3.send(null); + xhr3.onload = function(e){ + console.log(xhr3.responseText+','+xhr3.status); + } + EndTime=new Date(); + MiddleStr = '结束于:'+EndTime.toLocaleString()+'
'; + if (newstartsize==0) { + MiddleStr += '平均速度:'+size_format(totalsize*1000/(EndTime.getTime()-StartTime.getTime()))+'/s
'; + } else { + MiddleStr += '本次平均速度:'+size_format((totalsize-newstartsize)*1000/(EndTime.getTime()-StartTime.getTime()))+'/s
'; + } + document.getElementById('upfile_td1_'+tdnum).innerHTML=''; + label.innerHTML=StartStr+MiddleStr; + uploadbuttonshow(); + + response.name=file.webkitRelativePath||response.name; + addelement(response); + + } else { + if (!response['nextExpectedRanges']) { + label.innerHTML=''+xhr.responseText+'
'; + } else { + var a=response['nextExpectedRanges'][0]; + asize=Number( a.slice(0,a.indexOf("-")) ); + readblob(asize); + } + } } else readblob(asize); + } + xhr.send(binary); + } + } else { + if (window.location.pathname.indexOf('%23')>0||filename.indexOf('%23')>0) { + label.innerHTML='目录或文件名含有#,上传失败。'; + } else { + label.innerHTML=''+xhr2.responseText+''; + } + + uploadbuttonshow(); + } + } + } + } + + + function operatediv_close(operate) { + document.getElementById(operate+'_div').style.display='none'; + document.getElementById('mask').style.display='none'; + } + + + diff --git a/view/nexmoe/password.php b/view/nexmoe/password.php index f4f2efb..ac1aa89 100644 --- a/view/nexmoe/password.php +++ b/view/nexmoe/password.php @@ -1,20 +1,24 @@ + +
-

世界上最帅的人是谁?

+

输入密码进行查看

https - +

+
+ \ No newline at end of file diff --git a/view/nexmoe/show/audio.php b/view/nexmoe/show/audio.php index fdb2b62..a6d706f 100644 --- a/view/nexmoe/show/audio.php +++ b/view/nexmoe/show/audio.php @@ -1,13 +1,22 @@ - +
+
+ +
+
-
-
- -
+ +
file_download @@ -16,11 +25,12 @@ container: document.getElementById('aplayer'), audio: [{ name: '', - artist: 'Oneindex Preview', - url: '', + artist: '', + url: '', cover: '' }] }); +ap.play() //自动播放 - + \ No newline at end of file diff --git a/view/nexmoe/show/code.php b/view/nexmoe/show/code.php index 716b51c..f50ef54 100644 --- a/view/nexmoe/show/code.php +++ b/view/nexmoe/show/code.php @@ -9,7 +9,7 @@ function code_type($ext){ $code_type['java'] = 'java'; $code_type['js'] = 'javascript'; $code_type['json'] = 'json'; - $code_type['txt'] = 'Text'; + $code_type['txt'] = 'text'; $code_type['sh'] = 'sh'; $code_type['md'] = 'Markdown'; @@ -30,17 +30,31 @@ function code_type($ext){
-
- - -
+
+ + +
+
file_download - - + + + \ No newline at end of file diff --git a/view/nexmoe/show/image.php b/view/nexmoe/show/image.php index a03de4e..ec8e3ac 100644 --- a/view/nexmoe/show/image.php +++ b/view/nexmoe/show/image.php @@ -1,28 +1,41 @@ - +
- - -
- - -
-
- - -
-
- - +
+
+ +
- +
-file_download +" class="mdui-fab mdui-fab-fixed mdui-ripple mdui-color-theme-accent">file_download diff --git a/view/nexmoe/show/pdf.php b/view/nexmoe/show/pdf.php index 5d5d5a6..0658564 100644 --- a/view/nexmoe/show/pdf.php +++ b/view/nexmoe/show/pdf.php @@ -1,30 +1,22 @@ - + + + + - \ No newline at end of file + + + + diff --git a/view/nexmoe/show/stream.php b/view/nexmoe/show/stream.php index c939e0d..99b0589 100644 --- a/view/nexmoe/show/stream.php +++ b/view/nexmoe/show/stream.php @@ -1,5 +1,6 @@ 'application/octet-stream', 'ppt'=>'application/vnd.ms-powerpoint', @@ -64,6 +65,7 @@ 'rgb'=>"image/x-rgb", 'xpm'=>"image/x-xpixmap", 'txt'=>"text/plain", + 'lrc'=>"text/plain", 'c'=>"text/plain", 'cc'=>"text/plain", 'h'=>"text/plain", diff --git a/view/nexmoe/show/video.php b/view/nexmoe/show/video.php index 1af2cd9..3776f00 100644 --- a/view/nexmoe/show/video.php +++ b/view/nexmoe/show/video.php @@ -1,25 +1,66 @@ - - - - + + + + + + + +
-
+
+ + +
-file_download - \ No newline at end of file + + \ No newline at end of file diff --git a/view/nexmoe/show/video2.php b/view/nexmoe/show/video2.php index 538b5cb..a98f9e9 100644 --- a/view/nexmoe/show/video2.php +++ b/view/nexmoe/show/video2.php @@ -1,5 +1,5 @@ - - + + - - - - + + + +
-
+
+
-file_download - \ No newline at end of file + + + diff --git a/view/nexmoe/show/video5.php b/view/nexmoe/show/video5.php index c9491c5..3dcce2a 100644 --- a/view/nexmoe/show/video5.php +++ b/view/nexmoe/show/video5.php @@ -1,12 +1,47 @@ - - - + + +
- + + +
+ + +
+
file_download - \ No newline at end of file + +