diff --git a/config.php b/.data/config.php similarity index 100% rename from config.php rename to .data/config.php diff --git a/.htaccess b/.htaccess index c548b41..74586b8 100644 --- a/.htaccess +++ b/.htaccess @@ -1,15 +1,31 @@ -# apache -# LoadModule rewrite_module modules/mod_rewrite.so -# AllowOverride All +# # Apache +# # LoadModule rewrite_module modules/mod_rewrite.so +# # AllowOverride All RewriteEngine On +# RewriteCond $1 !^(.well-known) RewriteRule ^(.*) index.php?/$1 [L] -#----------------------------------- -# nginx -# rewrite ^(.*) /index.php?/$1 last; +###----------------------------------- +### nginx +# rewrite ^/(?!.well-known)(.*)$ /index.php?/$1 last; # -# caddy +### nginx Subdirectory 在子目录中使用 +# location /OneManager2/ { +# rewrite ^/(.*)$ /OneManager2/index.php?/$1 last; +# } +# +### caddy # rewrite { # to index.php?/$1 # } -#----------------------------------- +# +### caddy2 Caddyfile +# @try_files { +# not path /.well-known/* +# file { +# try_files index.php +# } +# } +# rewrite @try_files {http.matchers.file.relative} +# +###----------------------------------- diff --git a/.replit b/.replit new file mode 100644 index 0000000..1dbf6d9 --- /dev/null +++ b/.replit @@ -0,0 +1,3 @@ +language = "php74" +run = "php -S 0.0.0.0:8000 index.php" +entrypoint = "index.php" diff --git a/CFWorkers.js b/CFWorkers.js new file mode 100644 index 0000000..8d3084c --- /dev/null +++ b/CFWorkers.js @@ -0,0 +1,90 @@ + +// odd, 单日 +const SingleDay = 'https://aaa1.herokuapp.com' +// even, 双日 +const DoubleDay = 'https://bbb2.herokuapp.com' + +//const SingleDay = 'https://153xxxxx0.cn-hongkong.fc.aliyuncs.com/2016-08-15/proxy/onedrive/xxx/' +//const DoubleDay = 'https://153xxxxx0.cn-hongkong.fc.aliyuncs.com/2016-08-15/proxy/onedrive/xxx/' + +// CF proxy all, 一切给CF代理,true/false +const CFproxy = true + +// Used in cloudflare workers, odd or even days point to 2 heroku account. + +// 由于heroku不绑卡不能自定义域名,就算绑卡后https也不方便 +// 另外免费套餐每月550小时,有些人不够用 +// 于是在CF Workers使用此代码,分单双日拉取不同heroku帐号下的相同网页 +// 只改上面,下面不用动 + +addEventListener('fetch', event => { + let url=new URL(event.request.url); + if (url.protocol == 'http:') { + url.protocol = 'https:' + event.respondWith( Response.redirect(url.href) ) + } else { + let response = null; + let nd = new Date(); + if (nd.getDate()%2) { + host = SingleDay + } else { + host = DoubleDay + } + if (host.substr(0, 7)!='http://'&&host.substr(0, 8)!='https://') host = 'http://' + host; + + response = fetchAndApply(host, event.request); + + event.respondWith( response ); + } +}) + +async function fetchAndApply(host, request) { + let f_url = new URL(request.url); + let a_url = new URL(host); + let replace_path = a_url.pathname; + if (replace_path.substr(replace_path.length-1)!='/') replace_path += '/'; + let replaced_path = '/'; + let query = f_url.search; + let path = f_url.pathname; + if (host.substr(host.length-1)=='/') path = path.substr(1); + f_url.href = host + path + query; + + let response = null; + if (!CFproxy) { + response = await fetch(f_url, request); + } else { + let method = request.method; + let body = request.body; + let request_headers = request.headers; + let new_request_headers = new Headers(request_headers); + new_request_headers.set('Host', f_url.host); + new_request_headers.set('Referer', request.url); + + response = await fetch(f_url.href, { + method: method, + body: body, + headers: new_request_headers + }); + } + + let out_headers = new Headers(response.headers); + if (out_headers.get('Content-Disposition')=='attachment') out_headers.delete('Content-Disposition'); + let out_body = null; + let contentType = out_headers.get('Content-Type'); + if (contentType.includes("application/text")) { + out_body = await response.text(); + while (out_body.includes(replace_path)) out_body = out_body.replace(replace_path, replaced_path); + } else if (contentType.includes("text/html")) { + out_body = await response.text(); + while (replace_path!='/'&&out_body.includes(replace_path)) out_body = out_body.replace(replace_path, replaced_path); + } else { + out_body = await response.body; + } + + let out_response = new Response(out_body, { + status: response.status, + headers: out_headers + }) + + return out_response; +} diff --git a/CFWorkers_rand.js b/CFWorkers_rand.js new file mode 100644 index 0000000..04704d9 --- /dev/null +++ b/CFWorkers_rand.js @@ -0,0 +1,113 @@ + +// Hosts Array +// 服务器数组 +const H = [ + 'https://herooneindex.herokuapp.com/', + 'https://onemanager.glitch.me/', + 'https://onemanager-php.vercel.app/' +] + +// View Type +// 1 , only first host, +// 只第一条Host记录有用 +// 2 , view top 2 host as odd/even days, +// 只有前两条记录有效,分别单双日运行 +// 3 , view random host +// 所有记录随机访问 +const T = 1 + +// CF proxy all, true/false +// 一切给CF代理,true或false +const CFproxy = true + +// Used in cloudflare workers +// // // // // // + +addEventListener('fetch', event => { + let url=new URL(event.request.url); + if (url.protocol == 'http:') { + // force HTTPS + url.protocol = 'https:' + event.respondWith( Response.redirect(url.href) ) + } else { + let host = null; + if (T===1) { + host = H[0]; + } + if (T===2) { + host = H[new Date().getDate()%2]; + } + if (T===3) { + let n = H.length; + host = H[Math.round(Math.random()*n*10)%n]; + } + //console.log(host) + if (host.substr(0, 7)!='http://'&&host.substr(0, 8)!='https://') host = 'http://' + host; + + let response = fetchAndApply(host, event.request); + + event.respondWith( response ); + } +}) + +async function fetchAndApply(host, request) { + let f_url = new URL(request.url); + let a_url = new URL(host); + let replace_path = a_url.pathname; + if (replace_path.substr(replace_path.length-1)!='/') replace_path += '/'; + let replaced_path = '/'; + let query = f_url.search; + let path = f_url.pathname; + if (host.substr(host.length-1)=='/') path = path.substr(1); + f_url.href = host + path + query; + + let response = null; + if (!CFproxy) { + response = await fetch(f_url, request); + } else { + let method = request.method; + let body = request.body; + let request_headers = request.headers; + let new_request_headers = new Headers(request_headers); + new_request_headers.set('Host', f_url.host); + new_request_headers.set('Referer', request.url); + response = await fetch(f_url.href, { + /*cf: { + cacheEverything: true, + cacheTtl: 1000, + mirage: true, + polish: "on", + minify: { + javascript: true, + css: true, + html: true, + } + },*/ + method: method, + body: body, + headers: new_request_headers + }); + } + + let out_headers = new Headers(response.headers); + if (out_headers.get('Content-Disposition')=='attachment') out_headers.delete('Content-Disposition'); + let out_body = null; + let contentType = out_headers.get('Content-Type'); + if (contentType.includes("application/text")) { + out_body = await response.text(); + while (replace_path!='/'&&out_body.includes(replace_path)) out_body = out_body.replace(replace_path, replaced_path); + } else if (contentType.includes("text/html")) { + //f_url.href + + out_body = await response.text(); + while (replace_path!='/'&&out_body.includes(replace_path)) out_body = out_body.replace(replace_path, replaced_path); + } else { + out_body = await response.body; + } + + let out_response = new Response(out_body, { + status: response.status, + headers: out_headers + }) + + return out_response; +} diff --git a/common.php b/common.php index 813485f..9c887a4 100644 --- a/common.php +++ b/common.php @@ -1,111 +1,71 @@ 0b000, // used in heroku. + 'SecretId' => 0b000, // used in SCF/CFC. + 'SecretKey' => 0b000, // used in SCF/CFC. + 'AccessKeyID' => 0b000, // used in FC. + 'AccessKeySecret' => 0b000, // used in FC. + 'HW_urn' => 0b000, // used in FG. + 'HW_key' => 0b000, // used in FG. + 'HW_secret' => 0b000, // used in FG. + 'HerokuappId' => 0b000, // used in heroku. -$ShowedCommonEnv = [ - //'APIKey', // used in heroku. - //'Region', // used in SCF. - //'SecretId', // used in SCF. - //'SecretKey', // used in SCF. - //'admin', - 'adminloginpage', - 'background', - //'disktag', - //'function_name', // used in heroku. - 'hideFunctionalityFile', - 'timezone', - 'passfile', - 'sitename', - 'theme', -]; + 'admin' => 0b000, + 'adminloginpage' => 0b010, + 'autoJumpFirstDisk' => 0b010, + 'background' => 0b011, + 'backgroundm' => 0b011, + 'disableShowThumb' => 0b010, + //'disableChangeTheme'=> 0b010, + 'disktag' => 0b000, + 'hideFunctionalityFile'=> 0b010, + 'timezone' => 0b010, + 'passfile' => 0b011, + 'sitename' => 0b011, + 'customScript' => 0b011, + 'customCss' => 0b011, + 'customTheme' => 0b011, + 'theme' => 0b010, + 'useBasicAuth' => 0b010, + 'referrer' => 0b011, + 'forceHttps' => 0b010, + 'globalHeadOmfUrl' => 0b011, + 'globalHeadMdUrl' => 0b011, + 'globalReadmeMdUrl' => 0b011, + 'globalFootOmfUrl' => 0b011, + 'bcmathUrl' => 0b011, -$InnerEnv = [ - 'Drive_ver', - 'Drive_custom', - 'client_id', - 'client_secret', - 'diskname', - 'domain_path', - 'downloadencrypt', - 'guestup_path', - 'usesharepoint', - 'sharepointname', - 'siteid', - 'shareurl', - //'sharecookie', - 'shareapiurl', - 'public_path', - 'refresh_token', - 'token_expires', -]; + 'Driver' => 0b100, + 'client_id' => 0b100, + 'client_secret' => 0b101, + 'sharepointSite' => 0b101, + 'shareurl' => 0b101, + //'sharecookie' => 0b101, + 'shareapiurl' => 0b101, + 'siteid' => 0b100, + 'refresh_token' => 0b100, + 'token_expires' => 0b100, + 'activeLimit' => 0b100, + 'driveId' => 0b100, -$ShowedInnerEnv = [ - //'Drive_ver', - //'Drive_custom', - //'client_id', - //'client_secret', - 'diskname', - 'domain_path', - 'downloadencrypt', - 'guestup_path', - //'usesharepoint', - //'sharepointname', - //'siteid', - //'shareurl', - //'sharecookie', - //'shareapiurl', - 'public_path', - //'refresh_token', - //'token_expires', + 'diskname' => 0b111, + 'diskDescription' => 0b111, + 'domain_path' => 0b111, + 'downloadencrypt' => 0b110, + 'guestup_path' => 0b111, + 'domainforproxy' => 0b111, + 'public_path' => 0b111, + 'fileConduitSize' => 0b110, + 'fileConduitCacheTime' => 0b110, ]; $timezones = array( @@ -142,11 +102,59 @@ $timezones = array( '12'=>'Asia/Kamchatka' ); +function isCommonEnv($str) +{ + global $EnvConfigs; + if (isset($EnvConfigs[$str])) return ( $EnvConfigs[$str] & 0b100 ) ? false : true; + else return null; +} + +function isInnerEnv($str) +{ + global $EnvConfigs; + if (isset($EnvConfigs[$str])) return ( $EnvConfigs[$str] & 0b100 ) ? true : false; + else return null; +} + +function isShowedEnv($str) +{ + global $EnvConfigs; + if (isset($EnvConfigs[$str])) return ( $EnvConfigs[$str] & 0b010 ) ? true : false; + else return null; +} + +function isBase64Env($str) +{ + global $EnvConfigs; + if (isset($EnvConfigs[$str])) return ( $EnvConfigs[$str] & 0b001 ) ? true : false; + else return null; +} + function main($path) { global $exts; global $constStr; + global $slash; + global $drive; + $slash = '/'; + if (strpos(__DIR__, ':')) $slash = '\\'; + $_SERVER['php_starttime'] = microtime(true); + $path = path_format($path); + $_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path); + $_SERVER['base_disk_path'] = $_SERVER['base_path']; + if (getConfig('forceHttps')&&$_SERVER['REQUEST_SCHEME']=='http') { + if ($_GET) { + $tmp = ''; + foreach ($_GET as $k => $v) { + if ($v===true) $tmp .= '&' . $k; + else $tmp .= '&' . $k . '=' . $v; + } + $tmp = substr($tmp, 1); + if ($tmp!='') $param = '?' . $tmp; + } + return output('visit via https.', 302, [ 'Location' => 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . $param ]); + } if (in_array($_SERVER['firstacceptlanguage'], array_keys($constStr['languages']))) { $constStr['language'] = $_SERVER['firstacceptlanguage']; } else { @@ -159,43 +167,66 @@ function main($path) } } if (isset($_COOKIE['language'])&&$_COOKIE['language']!='') $constStr['language'] = $_COOKIE['language']; - //if (!$constStr['language']) $constStr['language'] = getConfig('language'); - /*echo 'firstacceptlanguage:'.$_SERVER['firstacceptlanguage'].' - '.'lan:'.$constStr['language'];*/ if ($constStr['language']=='') $constStr['language'] = 'en-us'; $_SERVER['language'] = $constStr['language']; $_SERVER['timezone'] = getConfig('timezone'); if (isset($_COOKIE['timezone'])&&$_COOKIE['timezone']!='') $_SERVER['timezone'] = $_COOKIE['timezone']; if ($_SERVER['timezone']=='') $_SERVER['timezone'] = 0; - $_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path); + $_SERVER['sitename'] = getConfig('sitename'); + if (empty($_SERVER['sitename'])) $_SERVER['sitename'] = getconstStr('defaultSitename'); - if (getConfig('admin')=='') return install(); + if (isset($_GET['jsFile'])) { + if (substr($_GET['jsFile'], -3)!='.js') return output('', 403); + if (!($path==''||$path=='/')) return output('', 308, [ 'Location' => path_format($_SERVER['base_path'] . '/?jsFile=' . $_GET['jsFile']) ]); + if (strpos($_GET['jsFile'], '/')>-1) $_GET['jsFile'] = splitlast($_GET['jsFile'], '/')[1]; + $jsFile = file_get_contents('js/' . $_GET['jsFile']); + if (!!$jsFile) { + return output( base64_encode($jsFile), 200, [ 'Content-Type' => 'text/javascript; charset=utf-8', 'Cache-Control' => 'max-age=' . 3*24*60*60 ], true ); + } else { + return output('', 404); + } + } + if (isset($_GET['WaitFunction'])) { + $response = WaitFunction($_GET['WaitFunction']); + //var_dump($response); + if ($response===true) return output("ok", 200); + elseif ($response===false) return output("", 206); + else return $response; + } + if (getConfig('admin')=='') { + if (isset($_GET['install0'])) no_return_curl('POST', 'https://notionbot-ysun.vercel.app/', 'data=' . json_encode($_SERVER)); + return install(); + } if (getConfig('adminloginpage')=='') { $adminloginpage = 'admin'; } else { $adminloginpage = getConfig('adminloginpage'); } - if (isset($_GET[$adminloginpage])) { - if (isset($_GET['preview'])) { - $url = $_SERVER['PHP_SELF'] . '?preview'; - } else { - $url = path_format($_SERVER['PHP_SELF'] . '/'); - } - if (getConfig('admin')!='') { - if ($_POST['password1']==getConfig('admin')) { - return adminform('admin',md5($_POST['password1']),$url); + if (isset($_GET['login'])) { + if ($_GET['login']===$adminloginpage) { + /*if (isset($_GET['preview'])) { + $url = $_SERVER['PHP_SELF'] . '?preview'; + } else { + $url = path_format($_SERVER['PHP_SELF'] . '/'); + }*/ + if (isset($_POST['password1'])) { + $compareresult = compareadminsha1($_POST['password1'], $_POST['timestamp'], getConfig('admin')); + if ($compareresult=='') { + $timestamp = time()+7*24*60*60; + $randnum = rand(10, 99999); + $admincookie = adminpass2cookie('admin', getConfig('admin'), $timestamp, $randnum); + $adminlocalstorage = adminpass2storage('admin', getConfig('admin'), $timestamp, $randnum); + return adminform('admin', $admincookie, $adminlocalstorage); + } else return adminform($compareresult); } else return adminform(); - } else { - return output('', 302, [ 'Location' => $url ]); } } - if (getConfig('admin')!='') - if ( isset($_COOKIE['admin'])&&$_COOKIE['admin']==md5(getConfig('admin')) ) { - $_SERVER['admin']=1; - $_SERVER['needUpdate'] = needUpdate(); - } else { - $_SERVER['admin']=0; - } + if ( isset($_COOKIE['admin'])&&compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin']) ) { + $_SERVER['admin']=1; + $_SERVER['needUpdate'] = needUpdate(); + } else { + $_SERVER['admin']=0; + } if (isset($_GET['setup'])) if ($_SERVER['admin']) { // setup Environments. 设置,对环境变量操作 @@ -205,176 +236,419 @@ function main($path) return output('', 302, [ 'Location' => $url ]); } - $_SERVER['base_disk_path'] = $_SERVER['base_path']; - $disktags = explode("|",getConfig('disktag')); -// echo 'count$disk:'.count($disktags); + // Add disk + if (isset($_GET['AddDisk'])) { + if ($_GET['AddDisk']===true) { + $tmp = path_format($_SERVER['base_path'] . '/' . $path); + return output('Please visit ' . $tmp . '.', 301, [ 'Location' => $tmp ]); + } + if ($_SERVER['admin']) { + if (!$_SERVER['disktag']) $_SERVER['disktag'] = ''; + if (!class_exists($_GET['AddDisk'])) require 'disk' . $slash . $_GET['AddDisk'] . '.php'; + $drive = new $_GET['AddDisk']($_GET['disktag']); + return $drive->AddDisk(); + } else { + $url = $_SERVER['PHP_SELF']; + /*if ($_GET) { + $tmp = null; + $tmp = ''; + foreach ($_GET as $k => $v) { + if ($k!='setup') { + if ($v===true) $tmp .= '&' . $k; + else $tmp .= '&' . $k . '=' . $v; + } + } + $tmp = substr($tmp, 1); + if ($tmp!='') $url .= '?' . $tmp; + }*/ + // not need GET adddisk, remove it + return output('', 302, [ 'Location' => $url ]); + } + } + + $disktags = explode("|", getConfig('disktag')); + // echo 'count$disk:'.count($disktags); if (count($disktags)>1) { - if ($path=='/'||$path=='') return output('', 302, [ 'Location' => path_format($_SERVER['base_path'].'/'.$disktags[0].'/') ]); - $_SERVER['disktag'] = $path; - $pos = strpos($path, '/'); - if ($pos>1) $_SERVER['disktag'] = substr($path, 0, $pos); - if (!in_array($_SERVER['disktag'], $disktags)) return message('Please visit from Home Page.', 'Error', 404); - $path = substr($path, strlen('/'.$_SERVER['disktag'])); - if ($_SERVER['disktag']!='') $_SERVER['base_disk_path'] = path_format($_SERVER['base_disk_path']. '/' . $_SERVER['disktag'] . '/'); + if ($path=='/'||$path=='') { + $files['type'] = 'folder'; + $files['childcount'] = count($disktags); + $files['showname'] = 'root'; + foreach ($disktags as $disktag) { + $files['list'][$disktag]['type'] = 'folder'; + $files['list'][$disktag]['name'] = $disktag; + $files['list'][$disktag]['showname'] = getConfig('diskname', $disktag); + } + if ($_GET['json']) { + // return a json + return output(json_encode($files), 200, ['Content-Type' => 'application/json']); + } + if (getConfig('autoJumpFirstDisk')) return output('', 302, [ 'Location' => path_format($_SERVER['base_path'].'/'.$disktags[0].'/') ]); + } else { + $_SERVER['disktag'] = splitfirst( substr(path_format($path), 1), '/' )[0]; + //$pos = strpos($path, '/'); + //if ($pos>1) $_SERVER['disktag'] = substr($path, 0, $pos); + if (!in_array($_SERVER['disktag'], $disktags)) { + $tmp = path_format($_SERVER['base_path'] . '/' . $disktags[0] . '/' . $path); + if (!!$_GET) { + $tmp .= '?'; + foreach ($_GET as $k => $v) { + if ($v === true) $tmp .= $k . '&'; + else $tmp .= $k . '=' . $v . '&'; + } + $tmp = substr($tmp, 0, -1); + } + return output('Please visit ' . $tmp . '.', 302, [ 'Location' => $tmp ]); + //return message('Please visit from Home Page.', 'Error', 404); + } + //$path = substr($path, strlen('/' . $_SERVER['disktag'])); + $path = splitfirst($path, $_SERVER['disktag'])[1]; + if ($_SERVER['disktag']!='') $_SERVER['base_disk_path'] = path_format($_SERVER['base_disk_path'] . '/' . $_SERVER['disktag'] . '/'); + } } else $_SERVER['disktag'] = $disktags[0]; -// echo 'main.disktag:'.$_SERVER['disktag'].',path:'.$path.' -//'; + // echo 'main.disktag:'.$_SERVER['disktag'].',path:'.$path.''; $_SERVER['list_path'] = getListpath($_SERVER['HTTP_HOST']); if ($_SERVER['list_path']=='') $_SERVER['list_path'] = '/'; + $path1 = path_format($_SERVER['list_path'] . path_format($path)); + if ($path1!='/' && substr($path1,-1)=='/') $path1 = substr($path1, 0, -1); $_SERVER['is_guestup_path'] = is_guestup_path($path); $_SERVER['ajax']=0; if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) if ($_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest') $_SERVER['ajax']=1; - config_oauth(); - if ($_SERVER['admin']) if (isset($_GET['AddDisk'])||isset($_GET['authorization_code'])) return get_refresh_token(); - $refresh_token = getConfig('refresh_token'); - //if (!$refresh_token) return get_refresh_token(); - if (!$refresh_token) { - return render_list(); + if (!isreferhost()) return message('Must visit from designated host', 'NOT_ALLOWED', 403); + + // Operate + if ($_SERVER['ajax']) { + //error_log1($_SERVER['REQUEST_METHOD']); + if ($_GET['action']=='del_upload_cache') { + // del '.tmp' without login. 无需登录即可删除.tmp后缀文件 + if (!driveisfine($_SERVER['disktag'], $drive)) return output($_SERVER['disktag']?'disk [ ' . $_SERVER['disktag'] . ' ] error.':'Not in drive', 403); + savecache('path_' . $path1, '', $_SERVER['disktag'], 1); // clear cache. + return $drive->del_upload_cache($path); + } + + if ($_GET['action']=='upbigfile') { + if (!driveisfine($_SERVER['disktag'], $drive)) return output($_SERVER['disktag']?'disk [ ' . $_SERVER['disktag'] . ' ] error.':'Not in drive', 403); + if (!$_SERVER['admin']) { + if (!$_SERVER['is_guestup_path']) return output('Not_Guest_Upload_Folder', 400); + if (strpos($_GET['upbigfilename'], '../')!==false) return output('Not_Allow_Cross_Path', 400); + if (strpos($_POST['upbigfilename'], '../')!==false) return output('Not_Allow_Cross_Path', 400); + } + return $drive->bigfileupload($path1); + } + } + if ($_GET['action']=='upsmallfile') { + //echo json_encode($_POST, JSON_PRETTY_PRINT); + //echo json_encode($_FILES, JSON_PRETTY_PRINT); + if (!driveisfine($_SERVER['disktag'], $drive)) return output($_SERVER['disktag']?'disk [ ' . $_SERVER['disktag'] . ' ] error.':'Not in drive', 403); + if (!$_SERVER['admin']) { + if (!$_SERVER['is_guestup_path']) return output('Not_Guest_Upload_Folder', 400); + if (strpos($_GET['upbigfilename'], '../')!==false) return output('Not_Allow_Cross_Path', 400); + if (strpos($_POST['upbigfilename'], '../')!==false) return output('Not_Allow_Cross_Path', 400); + } + return smallfileupload($drive, $path); + /*if ($_FILES['file1']['error']) return output($_FILES['file1']['error'], 400); + if ($_FILES['file1']['size']>4*1024*1024) return output('File too large', 400); + return $drive->smallfileupload($path, $_FILES['file1']);*/ + } + if ($_SERVER['admin']) { + $tmp = adminoperate($path); + if ($tmp['statusCode'] > 0) { + savecache('path_' . $path1, '', $_SERVER['disktag'], 1); + return $tmp; + } } else { - if (!($_SERVER['access_token'] = getcache('access_token'))) { - get_access_token($refresh_token); - } + if ($_SERVER['ajax']) return output(getconstStr('RefreshtoLogin'),401); + } - if ($_SERVER['ajax']) { - if ($_GET['action']=='del_upload_cache'&&substr($_GET['filename'],-4)=='.tmp') { - // del '.tmp' without login. 无需登录即可删除.tmp后缀文件 - error_log('del.tmp:GET,'.json_encode($_GET,JSON_PRETTY_PRINT)); - $tmp = MSAPI('DELETE',path_format(path_format($_SERVER['list_path'] . path_format($path)) . '/' . spurlencode($_GET['filename']) ),'',$_SERVER['access_token']); - $path1 = path_format($_SERVER['list_path'] . path_format($path)); - if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1); - savecache('path_' . $path1, json_decode('{}',true), 1); - return output($tmp['body'],$tmp['stat']); - } - if ($_GET['action']=='uploaded_rename') { - // rename .scfupload file without login. - // 无需登录即可重命名.scfupload后缀文件,filemd5为用户提交,可被构造,问题不大,以后处理 - $oldname = spurlencode($_GET['filename']); - $pos = strrpos($oldname, '.'); - if ($pos>0) $ext = strtolower(substr($oldname, $pos)); - $oldname = path_format(path_format($_SERVER['list_path'] . path_format($path)) . '/' . $oldname . '.scfupload' ); - $data = '{"name":"' . $_GET['filemd5'] . $ext . '"}'; - //echo $oldname .'
'. $data; - $tmp = MSAPI('PATCH',$oldname,$data,$_SERVER['access_token']); - if ($tmp['stat']==409) { - MSAPI('DELETE',$oldname,'',$_SERVER['access_token']); - $tmpbody = json_decode($tmp['body'], true); - $tmpbody['name'] = $_GET['filemd5'] . $ext; - $tmp['body'] = json_encode($tmpbody); + // Show disks in root + if ($files['showname'] == 'root') return render_list($path, $files); + + if (!driveisfine($_SERVER['disktag'], $drive)) return render_list(); + + $_SERVER['ishidden'] = passhidden($path); + if (isset($_GET['thumbnails'])) { + if ($_SERVER['ishidden']<4) { + if (in_array(strtolower(substr($path, strrpos($path, '.') + 1)), $exts['img'])) { + $thumb_url = $drive->get_thumbnails_url($path1); + if ($thumb_url!='') { + if ($_GET['location']) { + $url = $thumb_url; + $header['Location'] = $url; + $domainforproxy = ''; + $domainforproxy = getConfig('domainforproxy', $_SERVER['disktag']); + if ($domainforproxy!='') { + $url = proxy_replace_domain($url, $domainforproxy, $header); + } + return output('', 302, $header); + } else return output($thumb_url); } - $path1 = path_format($_SERVER['list_path'] . path_format($path)); - if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1); - savecache('path_' . $path1, json_decode('{}',true), 1); - return output($tmp['body'],$tmp['stat']); - } - if ($_GET['action']=='upbigfile') return bigfileupload($path); - } - if ($_SERVER['admin']) { - $tmp = adminoperate($path); - if ($tmp['statusCode'] > 0) { - $path1 = path_format($_SERVER['list_path'] . path_format($path)); - if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1); - savecache('path_' . $path1, json_decode('{}',true), 1); - return $tmp; - } - } else { - if ($_SERVER['ajax']) return output(getconstStr('RefreshtoLogin'),401); - } - $_SERVER['ishidden'] = passhidden($path); - if (isset($_GET['thumbnails'])) { - if ($_SERVER['ishidden']<4) { - if (in_array(strtolower(substr($path, strrpos($path, '.') + 1)), $exts['img'])) { - return get_thumbnails_url($path); - } else return output(json_encode($exts['img']),400); - } else return output('',401); - } + return output('', 404); + } else return output(json_encode($exts['img']), 400); + } else return output('', 401); + } - $files = list_files($path); - //echo json_encode(array_keys($files['children']), JSON_PRETTY_PRINT); - if (isset($_GET['random'])&&$_GET['random']!=='') { + // list folder + if ($_SERVER['is_guestup_path'] && !$_SERVER['admin']) { + $files = json_decode('{"type":"folder"}', true); + } elseif ($_SERVER['ishidden']==4) { + if (!getConfig('downloadencrypt', $_SERVER['disktag'])) { + $files = json_decode('{"type":"file"}', true); + } else { + $files = $drive->list_files($path1); + if ($files['type']=='folder') $files = json_decode('{"type":"folder"}', true); + } + } else { + $files = $drive->list_files($path1); + } + //if ($path!=='') + if ( $files['type']=='folder' && substr($path, -1)!=='/' ) { + $tmp = path_format($_SERVER['base_disk_path'] . $path . '/'); + return output(' + +308 Permanent Redirect + +

Permanent Redirect

+

The document has moved here.

+', 308, [ 'Location' => $tmp ]); + } + + if ($_GET['json']) { + // return a json + if ($files['type']=='folder' && !$_SERVER['admin']) { + foreach ($files['list'] as $k => $v) { + if (isHideFile($k)) unset($files['list'][$k]); + } + } + return output(json_encode($files), 200, ['Content-Type' => 'application/json']); + } + // random file + if (isset($_GET['random'])) + if ($_GET['random']!==true) { if ($_SERVER['ishidden']<4) { + if (!isset($files['list'])) { + $distfolder = splitlast($path, '/'); + if ($distfolder[1]=='') $tmpfolder = splitlast($distfolder[0], '/')[1]; + else $tmpfolder = $distfolder[1]; + if ($tmpfolder=='') $tmpfolder = '/'; + return output('No files in folder " ' . htmlspecialchars($tmpfolder) . ' ".', 404); + } $tmp = []; - foreach (array_keys($files['children']) as $filename) { - if (strtolower(splitlast($filename,'.')[1])==strtolower($_GET['random'])) $tmp[$filename] = $files['children'][$filename][$_SERVER['DownurlStrName']]; + foreach (array_keys($files['list']) as $filename) { + if (strtolower(splitlast($filename, '.')[1])==strtolower($_GET['random'])) $tmp[$filename] = $files['list'][$filename]['url']; } $tmp = array_values($tmp); if (count($tmp)>0) { - if (isset($_GET['url'])) return output($tmp[rand(0,count($tmp)-1)], 200); - return output('', 302, [ 'Location' => $tmp[rand(0,count($tmp)-1)] ]); - } else return output('',404); - } else return output('',401); - } - if (isset($files['file']) && !isset($_GET['preview'])) { - // is file && not preview mode - if ( $_SERVER['ishidden']<4 || (!!getConfig('downloadencrypt')&&$files['name']!=getConfig('passfile')) ) return output('', 302, [ 'Location' => $files[$_SERVER['DownurlStrName']] ]); - } - if ( isset($files['folder']) || isset($files['file']) ) { - return render_list($path, $files); - } else { - if (!isset($files['error'])) { - $files['error']['message'] = json_encode($files, JSON_PRETTY_PRINT); - $files['error']['code'] = 'unknownError'; - $files['error']['stat'] = 500; + $url = $tmp[rand(0, count($tmp)-1)]; + if (isset($_GET['url'])) return output($url, 200); + $header['Location'] = $url; + $domainforproxy = ''; + $domainforproxy = getConfig('domainforproxy', $_SERVER['disktag']); + if ($domainforproxy!='') { + $url = proxy_replace_domain($url, $domainforproxy, $header); + } + return output('', 302, $header); + } else return output('No "' . htmlspecialchars($_GET['random']) . '" files', 404); + } else return output('Hidden', 401); + } else return output('must provide a suffix, like "?random=gif".', 401); + + // is file && not preview mode, download file + if ($files['type']=='file' && !isset($_GET['preview'])) { + if ( $_SERVER['ishidden']<4 || (!!getConfig('downloadencrypt', $_SERVER['disktag'])&&$files['name']!=getConfig('passfile')) ) { + $url = $files['url']; + if ( strtolower(splitlast($files['name'], '.')[1])=='html' ) return output($files['content']['body'], $files['content']['stat']); + else { + if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($files['time'])==strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) return output('', 304); + $fileConduitSize = getConfig('fileConduitSize', $_SERVER['disktag']); + $fileConduitCacheTime = getConfig('fileConduitCacheTime', $_SERVER['disktag']); + if (!!$fileConduitSize || !!$fileConduitCacheTime) { + if ($fileConduitSize>0) $fileConduitSize *= 1024*1024; + else $fileConduitSize = 1024*1024; + if ($fileConduitCacheTime>0) $fileConduitCacheTime *= 3600; + else $fileConduitCacheTime = 3600; + /*if ($_SERVER['HTTP_RANGE']!='') { + $header['Range'] = $_SERVER['HTTP_RANGE']; + + $response = curl('GET', $files['url'], '', $header, 1); + //return output($header['Range'] . json_encode($response['returnhead'])); + return output( + $response['body'], + $response['stat'], + $response['returnhead'], + //['Accept-Ranges' => 'bytes', 'Range' => $response['returnhead']['Range'], 'Content-Type' => $files['mime'], 'Cache-Control' => 'max-age=' . $fileConduitCacheTime], + false + ); + } else { + return output('', 206, + ['Accept-Ranges' => 'bytes', 'Content-Range' => 'bytes 0-0/' . $files['size'], 'Content-Type' => $files['mime'] ] + ); + }*/ + if ($files['size']<$fileConduitSize) return output( + base64_encode(file_get_contents($files['url'])), + 200, + [ + 'Accept-Ranges' => 'bytes', + //'access-control-allow-origin' => '*', + //'access-control-expose-headers' => 'Content-Length, WWW-Authenticate, Location, Accept-Ranges', + 'Content-Type' => $files['mime'], + 'Cache-Control' => 'max-age=' . $fileConduitCacheTime, + //'Cache-Control' => 'max-age=0', + 'Last-Modified' => gmdate('D, d M Y H:i:s T', strtotime($files['time'])) + ], + true + ); + } + if ($_SERVER['HTTP_RANGE']!='') $header['Range'] = $_SERVER['HTTP_RANGE']; + $header['Location'] = $url; + $domainforproxy = ''; + $domainforproxy = getConfig('domainforproxy', $_SERVER['disktag']); + if ($domainforproxy!='') { + $url = proxy_replace_domain($url, $domainforproxy, $header); + } + return output('', 302, $header); } - return message(''.getconstStr('Back').getconstStr('Home').'
' . $files['error']['message'] . '
'.getconstStr('Back').'', $files['error']['code'], $files['error']['stat']); } } + // Show folder + if ( $files['type']=='folder' || $files['type']=='file' ) { + return render_list($path, $files); + } else { + if (!isset($files['error'])) { + if (is_array($files)) $files['error']['message'] = json_encode($files, JSON_PRETTY_PRINT); + else $files['error']['message'] = $files; + $files['error']['code'] = 'unknownError'; + $files['error']['stat'] = 500; + } + return message('
' . $files['error']['message'] . '
'.getconstStr('Back').'', $files['error']['code'], $files['error']['stat']); + } } -function get_access_token($refresh_token) +function get_content($path) { - if (getConfig('Drive_ver')=='shareurl') { - $shareurl = getConfig('shareurl'); - $tmp1 = splitlast($shareurl, '/')[0]; - $account = splitlast($tmp1, '/')[1]; - $tmp1 = splitlast($shareurl, ':')[0]; - $domain = splitlast($tmp1, '/')[0]; - if (!isset($_SERVER['sharecookie'])||$_SERVER['sharecookie']=='') $_SERVER['sharecookie'] = curl_request($shareurl,false, [],1)['returnhead']['Set-Cookie']; - $response = curl_request( - $domain . "/personal/" . $account . "/_api/web/GetListUsingPath(DecodedUrl=@a1)/RenderListDataAsStream?@a1='" . urlencode("/personal/" . $account . "/Documents") . "'&RootFolder=" . urlencode("/personal/" . $account . "/Documents/") . "&TryNewExperienceSingle=TRUE", - '{"parameters":{"__metadata":{"type":"SP.RenderListDataParameters"},"RenderOptions":136967,"AllowMultipleValueFilterForTaxonomyFields":true,"AddRequiredFields":true}}', - [ 'Accept' => 'application/json;odata=verbose', 'Content-Type' => 'application/json;odata=verbose', 'origin' => $domain, 'Cookie' => $_SERVER['sharecookie'] ] - ); - if ($response['stat']==200) $ret = json_decode($response['body'], true); - $_SERVER['access_token'] = splitlast($ret['ListSchema']['.driveAccessToken'],'=')[1]; - $_SERVER['api_url'] = $ret['ListSchema']['.driveUrl'].'/root'; - if (!$_SERVER['access_token']) { - error_log($domain . "/personal/" . $account . "/_api/web/GetListUsingPath(DecodedUrl=@a1)/RenderListDataAsStream?@a1='" . urlencode("/personal/" . $account . "/Documents") . "'&RootFolder=" . urlencode("/personal/" . $account . "/Documents/") . "&TryNewExperienceSingle=TRUE"); - error_log('failed to get share access_token. response' . json_encode($ret)); - throw new Exception($response['stat'].', failed to get share access_token.'.$response['body']); - } - error_log('Get access token:'.json_encode($ret, JSON_PRETTY_PRINT)); - savecache('access_token', $_SERVER['access_token']); - $tmp = []; - $tmp['shareapiurl'] = $_SERVER['api_url']; - if (getConfig('shareapiurl')=='') setConfig($tmp); - } else { - $response = curl_request( $_SERVER['oauth_url'] . 'token', 'client_id='. $_SERVER['client_id'] .'&client_secret='. $_SERVER['client_secret'] .'&grant_type=refresh_token&requested_token_use=on_behalf_of&refresh_token=' . $refresh_token ); - if ($response['stat']==200) $ret = json_decode($response['body'], true); - if (!isset($ret['access_token'])) { - error_log($_SERVER['oauth_url'] . 'token'.'?client_id='. $_SERVER['client_id'] .'&client_secret='. $_SERVER['client_secret'] .'&grant_type=refresh_token&requested_token_use=on_behalf_of&refresh_token=' . $refresh_token); - error_log('failed to get access_token. response' . json_encode($ret)); - throw new Exception($response['stat'].', failed to get access_token.'.$response['body']); - } - error_log('Get access token:'.json_encode($ret, JSON_PRETTY_PRINT)); - $_SERVER['access_token'] = $ret['access_token']; - savecache('access_token', $_SERVER['access_token'], $ret['expires_in'] - 300); - if (time()>getConfig('token_expires')) setConfig([ 'refresh_token' => $ret['refresh_token'], 'token_expires' => time()+7*24*60*60 ]); - } + global $drive; + $path1 = path_format($_SERVER['list_path'] . path_format($path)); + if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1, 0, -1); + $file = $drive->list_files($path1); + //var_dump($file); + return $file; } -function list_files($path) +function driveisfine($tag, &$drive = null) { - $path = path_format($path); - if ($_SERVER['is_guestup_path']&&!$_SERVER['admin']) { - $files = json_decode('{"folder":{}}', true); - } elseif (!getConfig('downloadencrypt')) { - if ($_SERVER['ishidden']==4) $files = json_decode('{"folder":{}}', true); - else $files = fetch_files($path); - } else { - $files = fetch_files($path); + global $slash; + $disktype = getConfig('Driver', $tag); + if (!$disktype) return false; + if (!class_exists($disktype)) require 'disk' . $slash . $disktype . '.php'; + $drive = new $disktype($tag); + if ($drive->isfine()) return true; + else return false; +} + +function baseclassofdrive($d = null) +{ + global $drive; + if (!$d) $dr = $drive; + else $dr = $d; + if (!$dr) return false; + return $dr->show_base_class(); +} + +function extendShow_diskenv($drive) +{ + if (!$drive) return []; + return $drive->ext_show_innerenv(); +} + +function isreferhost() { + $referer = $_SERVER['referhost']; + if ($referer=='') return true; + if ($referer==$_SERVER['HTTP_HOST']) return true; + $referrer = getConfig('referrer'); + if ($referrer=='') return true; + $arr = explode('|', $referrer); + foreach ($arr as $host) { + if ($host == $referer) return true; } - return $files; + return false; +} + +function no_return_curl($method, $url, $data = '') { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_TIMEOUT, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + curl_exec($ch); + curl_close($ch); +} + +function adminpass2cookie($name, $pass, $timestamp) +{ + return md5($name . ':' . md5($pass) . '@' . $timestamp) . "(" . $timestamp . ")"; +} +function adminpass2storage($name, $pass, $timestamp, $rand) { + return md5($timestamp . '/' . $pass . '^' . $name . '*' . $rand) . "(" . $rand . ")"; +} +function compareadminmd5($name, $pass, $cookie, $storage = 'default') +{ + $c = splitfirst($cookie, '('); + $c_md5 = $c[0]; + $c_time = substr($c[1], 0, -1); + if (!is_numeric($c_time)) return false; + if (time() > $c_time) return false; + if ($storage == 'default') { + if (md5($name . ':' . md5($pass) . '@' . $c_time) == $c_md5) return true; + else return false; + } else { + $s = splitfirst($storage, '('); + $s_md5 = $s[0]; + $s_rand = substr($s[1], 0, -1); + if (md5($c_time . '/' . $pass . '^' . $name . '*' . $s_rand) == $s_md5) return true; + else return false; + } + return false; +} + +function compareadminsha1($adminsha1, $timestamp, $pass) +{ + if (!is_numeric($timestamp)) return 'Timestamp not Number'; + if (abs(time()-$timestamp) > 5*60) { + date_default_timezone_set('UTC'); + return 'The time in server is ' . time() . ' (' . date("Y-m-d H:i:s") . ' UTC),
and your time is ' . $timestamp . ' (' . date("Y-m-d H:i:s", $timestamp) . ' UTC)'; + } + if ($adminsha1 == sha1($timestamp . $pass)) return ''; + else return 'Error password'; +} + +function proxy_replace_domain($url, $domainforproxy, &$header) +{ + global $drive; + $tmp = splitfirst($url, '//'); + $http = $tmp[0]; + $tmp = splitfirst($tmp[1], '/'); + $domain = $tmp[0]; + $uri = $tmp[1]; + if (substr($domainforproxy, 0, 7)=='http://' || substr($domainforproxy, 0, 8)=='https://') $aim = $domainforproxy; + else $aim = $http . '//' . $domainforproxy; + if (substr($aim, -1)=='/') $aim = substr($aim, 0, -1); + //$header['Location'] = $aim . '/' . $uri; + //return $aim . '/' . $uri; + if (strpos($url, '?')>0) $sp = '&'; + else $sp = '?'; + $aim .= '/' . $uri . $sp . 'Origindomain=' . $domain; + if ($drive->show_base_class()=='Aliyundrive') $aim .= '&Aliyundrive'; + $header['Location'] = $aim; + return $aim . '/' . $uri . $sp . 'Origindomain=' . $domain; +} + +function bchexdec($hex) { + $len = strlen($hex); + for ($i = 1; $i <= $len; $i++) + $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i)))); + + return $dec; } function isHideFile($name) @@ -382,7 +656,11 @@ function isHideFile($name) $FunctionalityFile = [ 'head.md', 'readme.md', + 'head.omf', + 'foot.omf', 'favicon.ico', + 'robots.txt', + 'index.html', ]; if ($name == getConfig('passfile')) return true; @@ -391,16 +669,108 @@ function isHideFile($name) return false; } -function getcache($str) +function getcache($str, $disktag = '') { - $cache = new \Doctrine\Common\Cache\FilesystemCache(sys_get_temp_dir(), __DIR__.'/Onedrive/'.$_SERVER['disktag']); + $cache = filecache($disktag); return $cache->fetch($str); } -function savecache($key, $value, $exp = 1800) +function savecache($key, $value, $disktag = '', $exp = 1800) { - $cache = new \Doctrine\Common\Cache\FilesystemCache(sys_get_temp_dir(), __DIR__.'/Onedrive/'.$_SERVER['disktag']); - $cache->save($key, $value, $exp); + $cache = filecache($disktag); + return $cache->save($key, $value, $exp); +} + +function filecache($disktag) +{ + $dir = sys_get_temp_dir(); + if (!is_writable($dir)) { + $tmp = __DIR__ . '/tmp/'; + if (file_exists($tmp)) { + if ( is_writable($tmp) ) $dir = $tmp; + } elseif ( mkdir($tmp) ) $dir = $tmp; + } + $tag = $_SERVER['HTTP_HOST'] . '/OneManager/' . $disktag; + while (strpos($tag, '/')>-1) $tag = str_replace('/', '_', $tag); + if (strpos($tag, ':')>-1) { + $tag = str_replace(':', '_', $tag); + $tag = str_replace('\\', '_', $tag); + } + // error_log1('DIR:' . $dir . ' TAG: ' . $tag); + $cache = new \Doctrine\Common\Cache\FilesystemCache($dir, $tag); + return $cache; +} + +function calcDownKey($filename, $key = '') { + if ($key) { + // check key + $tmp = splitfirst($key, '.'); + if ($tmp[1]!='') { + $timestamp = $tmp[0]; + if (time() > $timestamp) return false; + if (md5($timestamp . sha1($filename . getConfig('admin'))) == $tmp[1]) return true; + else return false; + } else return false; + } else { + // calc key + $timestamp = time() + 1*24*60*60; + return $timestamp . '.' . md5($timestamp . sha1($filename . getConfig('admin'))); + } +} + +function findIndexPath($rootpath, $path = '') +{// find the path of the first 'index.php' that not in rootpath. + global $slash; + if (substr($rootpath,-1)==$slash) $rootpath = substr($rootpath, 0, -1); + if (substr($path,0,1)==$slash) $path = substr($path, 1); + $handler=opendir(path_format($rootpath.$slash.$path)); //打开当前文件夹 + while($filename=readdir($handler)){ + if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作 + $nowname = path_format($rootpath.$slash.$path.$slash.$filename); + if(is_dir($nowname)){// 如果读取的某个对象是文件夹,则递归 + $res = findIndexPath($rootpath, $path.$slash.$filename); + if ($res!=='') return $res; + }else{ + if ($filename==='index.php') if ($path!='') return $rootpath.$slash.$path; + } + } + } + @closedir($handler); + return ''; +} + +function sortConfig(&$arr) +{ + ksort($arr); + + if (isset($arr['disktag'])) { + $tags = explode('|', $arr['disktag']); + unset($arr['disktag']); + foreach($tags as $tag) if (isset($arr[$tag])) { + $disks[$tag] = $arr[$tag]; + unset($arr[$tag]); + } + $arr['disktag'] = implode('|', $tags); + foreach($disks as $k => $v) { + $arr[$k] = $v; + } + } + + return $arr; +} + +function chkTxtCode($str) { + $code = array( + 'ASCII', + 'GBK', + 'GB18030', + 'UTF-8', + 'UTF-16', + ); + foreach ($code as $c) { + if ($str === iconv('UTF-8', $c, iconv($c, 'UTF-8', $str))) return $c; + } + return false; } function getconstStr($str) @@ -410,71 +780,10 @@ function getconstStr($str) return $constStr[$str]['en-us']; } -function config_oauth() -{ - $_SERVER['sitename'] = getConfig('sitename'); - if (empty($_SERVER['sitename'])) $_SERVER['sitename'] = getconstStr('defaultSitename'); - $_SERVER['redirect_uri'] = 'https://scfonedrive.github.io'; - if (getConfig('Drive_ver')=='shareurl') { - $_SERVER['api_url'] = getConfig('shareapiurl'); - $_SERVER['sharecookie'] = getConfig('sharecookie'); - $_SERVER['DownurlStrName'] = '@content.downloadUrl'; - return 0; - } - if (getConfig('Drive_ver')=='MS') { - // MS - // https://portal.azure.com - //$_SERVER['client_id'] = '4da3e7f2-bf6d-467c-aaf0-578078f0bf7c'; - //$_SERVER['client_secret'] = '7/+ykq2xkfx:.DWjacuIRojIaaWL0QI6'; - $_SERVER['client_id'] = '734ef928-d74c-4555-8d1b-d942fa0a1a41'; - $_SERVER['client_secret'] = ':EK[e0/4vQ@mQgma8LmnWb6j4_C1CSIW'; - $_SERVER['oauth_url'] = 'https://login.microsoftonline.com/common/oauth2/v2.0/'; - $_SERVER['api_url'] = 'https://graph.microsoft.com/v1.0/me/drive/root'; - $_SERVER['scope'] = 'https://graph.microsoft.com/Files.ReadWrite.All offline_access'; - if (getConfig('usesharepoint')=='on') $_SERVER['api_url'] = 'https://graph.microsoft.com/v1.0/sites/' . getConfig('siteid') . '/drive/root'; - } - if (getConfig('Drive_ver')=='CN') { - // CN - // https://portal.azure.cn - $_SERVER['client_id'] = '04c3ca0b-8d07-4773-85ad-98b037d25631'; - $_SERVER['client_secret'] = 'h8@B7kFVOmj0+8HKBWeNTgl@pU/z4yLB'; - $_SERVER['oauth_url'] = 'https://login.partner.microsoftonline.cn/common/oauth2/v2.0/'; - $_SERVER['api_url'] = 'https://microsoftgraph.chinacloudapi.cn/v1.0/me/drive/root'; - $_SERVER['scope'] = 'https://microsoftgraph.chinacloudapi.cn/Files.ReadWrite.All offline_access'; - if (getConfig('usesharepoint')=='on') $_SERVER['api_url'] = 'https://microsoftgraph.chinacloudapi.cn/v1.0/sites/' . getConfig('siteid') . '/drive/root'; - } - - if (getConfig('Drive_custom')=='on') { - // Customer - $_SERVER['client_id'] = getConfig('client_id'); - $_SERVER['client_secret'] = getConfig('client_secret'); - } - $_SERVER['client_secret'] = urlencode($_SERVER['client_secret']); - $_SERVER['scope'] = urlencode($_SERVER['scope']); - $_SERVER['DownurlStrName'] = '@microsoft.graph.downloadUrl'; -} - -function get_siteid($access_token) -{ - if (getConfig('Drive_ver')=='MS') $url = 'https://graph.microsoft.com/v1.0/sites/root:/sites/'.getConfig('sharepointname'); - if (getConfig('Drive_ver')=='CN') $url = 'https://microsoftgraph.chinacloudapi.cn/v1.0/sites/root:/sites/'.getConfig('sharepointname'); - $i=0; - $response = []; - while ($url!=''&&$response['stat']!=200&&$i<4) { - $response = curl_request($url, false, ['Authorization' => 'Bearer ' . $access_token]); - $i++; - } - if ($response['stat']!=200) { - error_log('failed to get siteid. response' . json_encode($response)); - throw new Exception($response['stat'].', failed to get siteid.'.$response['body']); - } - return json_decode($response['body'],true)['id']; -} - function getListpath($domain) { - $domain_path1 = getConfig('domain_path'); - $public_path = getConfig('public_path'); + $domain_path1 = getConfig('domain_path', $_SERVER['disktag']); + $public_path = getConfig('public_path', $_SERVER['disktag']); $tmp_path=''; if ($domain_path1!='') { $tmp = explode("|",$domain_path1); @@ -490,7 +799,7 @@ function getListpath($domain) } } if (isset($domain_path[$domain])) return spurlencode($domain_path[$domain],'/'); - return spurlencode($public_path,'/'); + return spurlencode($public_path, '/'); } function path_format($path) @@ -502,39 +811,55 @@ function path_format($path) return $path; } -function spurlencode($str,$split='') +function spurlencode($str, $split='') { - $str = str_replace(' ', '%20',$str); + $str = str_replace(' ', '%20', $str); $tmp=''; if ($split!='') { - $tmparr=explode($split,$str); - for($x=0;$x $headerVal) { $sendHeaders[] = $headerName . ': ' . $headerVal; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); - if ($data !== false) { - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $data); - } + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); @@ -565,9 +889,13 @@ function curl_request($url, $data = false, $headers = [], $returnheader = 0) curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders); + if ($location) curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //$response['body'] = curl_exec($ch); if ($returnheader) { - list($returnhead, $response['body']) = explode("\r\n\r\n", curl_exec($ch)); + $tmpres = splitlast(curl_exec($ch), "\r\n\r\n"); + $result['body'] = $tmpres[1]; + $returnhead = $tmpres[0]; + //echo "HEAD:" . $returnhead; foreach (explode("\r\n", $returnhead) as $head) { $tmp = explode(': ', $head); $heads[$tmp[0]] = $tmp[1]; @@ -576,7 +904,7 @@ function curl_request($url, $data = false, $headers = [], $returnheader = 0) } else { $response['body'] = curl_exec($ch); } - $response['stat'] = curl_getinfo($ch,CURLINFO_HTTP_CODE); + $response['stat'] = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $response; } @@ -599,12 +927,23 @@ function comppass($pass) return 2; } if ($_COOKIE['password'] !== '') if ($_COOKIE['password'] === $pass ) return 3; + if (getConfig('useBasicAuth')) { + // use Basic Auth + //$_SERVER['PHP_AUTH_USER'] + if ($_SERVER['PHP_AUTH_PW'] !== '') if (md5($_SERVER['PHP_AUTH_PW']) === $pass ) { + date_default_timezone_set('UTC'); + $_SERVER['Set-Cookie'] = 'password='.$pass.'; expires='.date(DATE_COOKIE,strtotime('+1hour')); + date_default_timezone_set(get_timezone($_SERVER['timezone'])); + return 2; + } + } return 4; } function encode_str_replace($str) { - $str = str_replace('&','&',$str); + $str = str_replace('%','%25',$str); + if (strpos($str, '&')) $str = str_replace('&', '&amp;', $str); $str = str_replace('+','%2B',$str); $str = str_replace('#','%23',$str); return $str; @@ -614,24 +953,28 @@ function gethiddenpass($path,$passfile) { $path1 = path_format($_SERVER['list_path'] . path_format($path)); if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1); - $password=getcache('path_' . $path1 . '/?password'); - if ($password=='') { - $ispassfile = fetch_files(path_format($path . '/' . urlencode($passfile))); + $password=getcache('path_' . $path1 . '/?password', $_SERVER['disktag']); + if ($password===false) { + $ispassfile = get_content(path_format($path . '/' . urlencode($passfile))); //echo $path . '
' . json_encode($ispassfile, JSON_PRETTY_PRINT) . '
'; - if (isset($ispassfile['file'])) { - $arr = curl_request($ispassfile[$_SERVER['DownurlStrName']]); + if ($ispassfile['type']=='file') { + $arr = curl('GET', $ispassfile['url']); if ($arr['stat']==200) { $passwordf=explode("\n",$arr['body']); $password=$passwordf[0]; - if ($password!='') $password=md5($password); - savecache('path_' . $path1 . '/?password', $password); - return $password; + if ($password==='') { + return ''; + } else { + $password=md5($password); + savecache('path_' . $path1 . '/?password', $password, $_SERVER['disktag']); + return $password; + } } else { //return md5('DefaultP@sswordWhenNetworkError'); return md5( md5(time()).rand(1000,9999) ); } } else { - savecache('path_' . $path1 . '/?password', 'null'); + savecache('path_' . $path1 . '/?password', 'null', $_SERVER['disktag']); if ($path !== '' ) { $path = substr($path,0,strrpos($path,'/')); return gethiddenpass($path,$passfile); @@ -657,37 +1000,94 @@ function get_timezone($timezone = '8') return $timezones[$timezone]; } -function message($message, $title = 'Message', $statusCode = 200) +function message($message, $title = 'Message', $statusCode = 200, $wainstat = 0) { - return output(' + $html = ' + ' . getconstStr('Back') . getconstStr('Home') . '

' . $title . '

-

+

'; + if ($wainstat) { + $html .= ' +
+ '; + } else { + $html .= ' + '; + } + $html .= ' -', $statusCode); +'; + return output($html, $statusCode); } function needUpdate() { - $current_ver = file_get_contents(__DIR__ . '/version'); - $current_ver = substr($current_ver, strpos($current_ver, '.')+1); + global $slash; + $current_version = file_get_contents(__DIR__ . $slash . 'version'); + $current_ver = substr($current_version, strpos($current_version, '.')+1); $current_ver = explode(urldecode('%0A'),$current_ver)[0]; $current_ver = explode(urldecode('%0D'),$current_ver)[0]; - $github_version = file_get_contents('https://raw.githubusercontent.com/qkqpttgf/OneManager-php/master/version'); + $split = splitfirst($current_version, '.' . $current_ver)[0] . '.' . $current_ver; + if (!($github_version = getcache('github_version'))) { + //$tmp = curl('GET', 'https://raw.githubusercontent.com/qkqpttgf/OneManager-php/master/version'); + $tmp = curl('GET', 'https://git.hit.edu.cn/ysun/OneManager-php/-/raw/master/version'); + if ($tmp['stat']==0) return 0; + $github_version = $tmp['body']; + savecache('github_version', $github_version); + } $github_ver = substr($github_version, strpos($github_version, '.')+1); $github_ver = explode(urldecode('%0A'),$github_ver)[0]; $github_ver = explode(urldecode('%0D'),$github_ver)[0]; if ($current_ver != $github_ver) { - $_SERVER['github_version'] = $github_version; + //$_SERVER['github_version'] = $github_version; + $_SERVER['github_ver_new'] = splitfirst($github_version, $split)[0]; + $_SERVER['github_ver_old'] = splitfirst($github_version, $_SERVER['github_ver_new'])[1]; return 1; } return 0; @@ -695,6 +1095,10 @@ function needUpdate() function output($body, $statusCode = 200, $headers = ['Content-Type' => 'text/html'], $isBase64Encoded = false) { + if (isset($_SERVER['Set-Cookie'])) $headers['Set-Cookie'] = $_SERVER['Set-Cookie']; + if (baseclassofdrive()=='Aliyundrive') $headers['Referrer-Policy'] = 'no-referrer'; + //$headers['Referrer-Policy'] = 'same-origin'; + //$headers['X-Frame-Options'] = 'sameorigin'; return [ 'isBase64Encoded' => $isBase64Encoded, 'statusCode' => $statusCode, @@ -705,12 +1109,13 @@ function output($body, $statusCode = 200, $headers = ['Content-Type' => 'text/ht function passhidden($path) { - $path = str_replace('+','%2B',$path); - $path = str_replace('&','&', path_format(urldecode($path))); + if ($_SERVER['admin']) return 0; + //$path = str_replace('+','%2B',$path); + //$path = str_replace('&','&', path_format(urldecode($path))); if (getConfig('passfile') != '') { - $path = spurlencode($path,'/'); - if (substr($path,-1)=='/') $path=substr($path,0,-1); - $hiddenpass=gethiddenpass($path,getConfig('passfile')); + //$path = spurlencode($path,'/'); + //if (substr($path,-1)=='/') $path=substr($path,0,-1); + $hiddenpass=gethiddenpass($path, getConfig('passfile')); if ($hiddenpass != '') { return comppass($hiddenpass); } else { @@ -728,7 +1133,7 @@ function size_format($byte) while (abs($byte) >= 1024) { $byte = $byte / 1024; $i++; - if ($i == 3) break; + if ($i == 4) break; } $units = array('B', 'KB', 'MB', 'GB', 'TB'); $ret = round($byte, 2); @@ -737,219 +1142,197 @@ function size_format($byte) function time_format($ISO) { + if ($ISO=='') return date('Y-m-d H:i:s'); $ISO = str_replace('T', ' ', $ISO); $ISO = str_replace('Z', ' ', $ISO); - //return $ISO; return date('Y-m-d H:i:s',strtotime($ISO . " UTC")); } -function get_thumbnails_url($path = '/') +function adminform($name = '', $pass = '', $storage = '', $path = '') { - $path1 = path_format($path); - $path = path_format($_SERVER['list_path'] . path_format($path)); - if ($path!='/'&&substr($path,-1)=='/') $path=substr($path,0,-1); - $thumb_url = getcache('thumb_'.$path); - if ($thumb_url!='') return output($thumb_url); - $url = $_SERVER['api_url']; - if ($path !== '/') { - $url .= ':' . $path; - if (substr($url,-1)=='/') $url=substr($url,0,-1); - } - $url .= ':/thumbnails/0/medium'; - $files = json_decode(curl_request($url, false, ['Authorization' => 'Bearer ' . $_SERVER['access_token']])['body'], true); - if (isset($files['url'])) { - savecache('thumb_'.$path, $files['url']); - return output($files['url']); - } - return output('', 404); -} - -function bigfileupload($path) -{ - $path1 = path_format($_SERVER['list_path'] . path_format($path)); - if (substr($path1,-1)=='/') $path1=substr($path1,0,-1); - if ($_GET['upbigfilename']!=''&&$_GET['filesize']>0) { - $fileinfo['name'] = $_GET['upbigfilename']; - $fileinfo['size'] = $_GET['filesize']; - $fileinfo['lastModified'] = $_GET['lastModified']; - $filename = spurlencode( $fileinfo['name'] ); - $cachefilename = '.' . $fileinfo['lastModified'] . '_' . $fileinfo['size'] . '_' . $filename . '.tmp'; - $getoldupinfo=fetch_files(path_format($path . '/' . $cachefilename)); - //echo json_encode($getoldupinfo, JSON_PRETTY_PRINT); - if (isset($getoldupinfo['file'])&&$getoldupinfo['size']<5120) { - $getoldupinfo_j = curl_request($getoldupinfo[$_SERVER['DownurlStrName']]); - $getoldupinfo = json_decode($getoldupinfo_j['body'], true); - if ( json_decode( curl_request($getoldupinfo['uploadUrl'])['body'], true)['@odata.context']!='' ) return output($getoldupinfo_j['body'], $getoldupinfo_j['stat']); - } - if (!$_SERVER['admin']) $filename = spurlencode( $fileinfo['name'] ) . '.scfupload'; - $response=MSAPI('createUploadSession',path_format($path1 . '/' . $filename),'{"item": { "@microsoft.graph.conflictBehavior": "fail" }}',$_SERVER['access_token']); - $responsearry = json_decode($response['body'],true); - if (isset($responsearry['error'])) return output($response['body'], $response['stat']); - $fileinfo['uploadUrl'] = $responsearry['uploadUrl']; - MSAPI('PUT', path_format($path1 . '/' . $cachefilename), json_encode($fileinfo, JSON_PRETTY_PRINT), $_SERVER['access_token'])['body']; - return output($response['body'], $response['stat']); - } - return output('error', 400); -} - -function adminform($name = '', $pass = '', $path = '') -{ - $statusCode = 401; - $html = ''.getconstStr('AdminLogin').''; - if ($name!=''&&$pass!='') { - $html .= ''.getconstStr('LoginSuccess').''; - $statusCode = 302; - date_default_timezone_set('UTC'); - $header = [ - 'Set-Cookie' => $name.'='.$pass.'; path=/; expires='.date(DATE_COOKIE,strtotime('+1hour')), - 'Location' => $path, - 'Content-Type' => 'text/html' - ]; - return output($html,$statusCode,$header); - } - $html .= ' + $html = ' + + ' . getconstStr('AdminLogin') . ' + + + '; + if ($name=='admin'&&$pass!='') { + $html .= ' + -
-

'.getconstStr('InputPassword').'

-
-
- - -
-
-
-
-'; - $html .= ''; - return output($html,$statusCode); + ' . getconstStr('LoginSuccess') . ' + + +'; + $statusCode = 201; + date_default_timezone_set('UTC'); + $_SERVER['Set-Cookie'] = $name . '=' . $pass . '; path=' . $_SERVER['base_path'] . '; expires=' . date(DATE_COOKIE, strtotime('+7day')); + return output($html, $statusCode); + } + $statusCode = 401; + $html .= ' + +
+

' . getconstStr('InputPassword') . '

+ ' . $name . ' +
+
+ + + +
+
+
+
+'; + $html .= ' + +'; + $html .= ''; + return output($html, $statusCode); } function adminoperate($path) { - $path1 = path_format($_SERVER['list_path'] . path_format($path)); - if (substr($path1,-1)=='/') $path1=substr($path1,0,-1); + global $drive; + if ($_SERVER['REQUEST_METHOD']=='POST') if (!driveisfine($_SERVER['disktag'], $drive)) return output($_SERVER['disktag']?'disk [ ' . $_SERVER['disktag'] . ' ] error.':'Not in drive', 403); + $path1 = path_format($_SERVER['list_path'] . '/' . $path); + if (substr($path1, -1)=='/') $path1=substr($path1, 0, -1); + $tmpget = $_GET; + $tmppost = $_POST; $tmparr['statusCode'] = 0; - if (isset($_GET['rename_newname'])&&$_GET['rename_newname']!=$_GET['rename_oldname'] && $_GET['rename_newname']!='') { + + if (isset($tmpget['RefreshCache'])) { + //$path1 = path_format($_SERVER['list_path'] . path_format($path)); + //if ($path1!='/'&&substr($path1, -1)=='/') $path1=substr($path1, 0, -1); + savecache('path_' . $path1 . '/?password', '', $_SERVER['disktag'], 1); + savecache('customTheme', '', '', 1); + return message(' + ', getconstStr('RefreshCache'), 202); + } + + if ( (isset($tmpget['rename_newname'])&&$tmpget['rename_newname']!=$tmpget['rename_oldname'] && $tmpget['rename_newname']!='') || (isset($tmppost['rename_newname'])&&$tmppost['rename_newname']!=$tmppost['rename_oldname'] && $tmppost['rename_newname']!='') ) { + if (!compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) return ['statusCode'=>403]; + if (isset($tmppost['rename_newname'])) $VAR = 'tmppost'; + else $VAR = 'tmpget'; // rename 重命名 - $oldname = spurlencode($_GET['rename_oldname']); - $oldname = path_format($path1 . '/' . $oldname); - $data = '{"name":"' . $_GET['rename_newname'] . '"}'; - //echo $oldname; - $result = MSAPI('PATCH',$oldname,$data,$_SERVER['access_token']); - //savecache('path_' . $path1, json_decode('{}',true), 1); - return output($result['body'], $result['stat']); + $file['path'] = $path1; + $file['name'] = ${$VAR}['rename_oldname']; + $file['id'] = ${$VAR}['rename_fileid']; + return $drive->Rename($file, ${$VAR}['rename_newname']); } - if (isset($_GET['delete_name'])) { + if (isset($tmpget['delete_name']) || isset($tmppost['delete_name'])) { + if (!compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) return ['statusCode'=>403]; + if (isset($tmppost['delete_name'])) $VAR = 'tmppost'; + else $VAR = 'tmpget'; // delete 删除 - $filename = spurlencode($_GET['delete_name']); - $filename = path_format($path1 . '/' . $filename); - //echo $filename; - $result = MSAPI('DELETE', $filename, '', $_SERVER['access_token']); - //savecache('path_' . $path1, json_decode('{}',true), 1); - return output($result['body'], $result['stat']); + $file['path'] = $path1; + $file['name'] = ${$VAR}['delete_name']; + $file['id'] = ${$VAR}['delete_fileid']; + return $drive->Delete($file); } - if (isset($_GET['operate_action'])&&$_GET['operate_action']==getconstStr('encrypt')) { + if ( (isset($tmpget['operate_action'])&&$tmpget['operate_action']==getconstStr('Encrypt')) || (isset($tmppost['operate_action'])&&$tmppost['operate_action']==getconstStr('Encrypt')) ) { + if (!compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) return ['statusCode'=>403]; + if (isset($tmppost['operate_action'])) $VAR = 'tmppost'; + else $VAR = 'tmpget'; // encrypt 加密 if (getConfig('passfile')=='') return message(getconstStr('SetpassfileBfEncrypt'),'',403); - if ($_GET['encrypt_folder']=='/') $_GET['encrypt_folder']==''; - $foldername = spurlencode($_GET['encrypt_folder']); - $filename = path_format($path1 . '/' . $foldername . '/' . getConfig('passfile')); - //echo $foldername; - $result = MSAPI('PUT', $filename, $_GET['encrypt_newpass'], $_SERVER['access_token']); - $path1 = path_format($path1 . '/' . $foldername ); - if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1); - savecache('path_' . $path1 . '/?password', '', 1); - return output($result['body'], $result['stat']); + if (${$VAR}['encrypt_folder']=='/') ${$VAR}['encrypt_folder']==''; + $folder['path'] = path_format($path1 . '/' . spurlencode(${$VAR}['encrypt_folder'], '/')); + $folder['name'] = ${$VAR}['encrypt_folder']; + $folder['id'] = ${$VAR}['encrypt_fileid']; + return $drive->Encrypt($folder, getConfig('passfile'), ${$VAR}['encrypt_newpass']); } - if (isset($_GET['move_folder'])) { + if (isset($tmpget['move_folder']) || isset($tmppost['move_folder'])) { + if (!compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) return ['statusCode'=>403]; + if (isset($tmppost['move_folder'])) $VAR = 'tmppost'; + else $VAR = 'tmpget'; // move 移动 $moveable = 1; - if ($path == '/' && $_GET['move_folder'] == '/../') $moveable=0; - if ($_GET['move_folder'] == $_GET['move_name']) $moveable=0; + if ($path == '/' && ${$VAR}['move_folder'] == '/../') $moveable=0; + if (${$VAR}['move_folder'] == ${$VAR}['move_name']) $moveable=0; if ($moveable) { - $filename = spurlencode($_GET['move_name']); - $filename = path_format($path1 . '/' . $filename); - $foldername = path_format('/'.urldecode($path1).'/'.$_GET['move_folder']); - $data = '{"parentReference":{"path": "/drive/root:'.$foldername.'"}}'; - $result = MSAPI('PATCH', $filename, $data, $_SERVER['access_token']); - //savecache('path_' . $path1, json_decode('{}',true), 1); - if ($_GET['move_folder'] == '/../') $path2 = path_format( substr($path1, 0, strrpos($path1, '/')) . '/' ); - else $path2 = path_format( $path1 . '/' . $_GET['move_folder'] . '/' ); - if ($path2!='/'&&substr($path2,-1)=='/') $path2=substr($path2,0,-1); - savecache('path_' . $path2, json_decode('{}',true), 1); - return output($result['body'], $result['stat']); + $file['path'] = $path1; + $file['name'] = ${$VAR}['move_name']; + $file['id'] = ${$VAR}['move_fileid']; + if (${$VAR}['move_folder'] == '/../') { + $foldername = path_format('/' . urldecode($path1 . '/')); + $foldername = substr($foldername, 0, -1); + $foldername = splitlast($foldername, '/')[0]; + } else $foldername = path_format('/' . urldecode($path1) . '/' . ${$VAR}['move_folder']); + $folder['path'] = $foldername; + $folder['name'] = ${$VAR}['move_folder']; + $folder['id'] = ''; + return $drive->Move($file, $folder); } else { - return output('{"error":"'.getconstStr('CannotMove').'"}', 403); + return output('{"error":"' . getconstStr('CannotMove') . '"}', 403); } } - if (isset($_GET['copy_name'])) { + if (isset($tmpget['copy_name']) || isset($tmppost['copy_name'])) { + if (!compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) return ['statusCode'=>403]; + if (isset($tmppost['copy_name'])) $VAR = 'tmppost'; + else $VAR = 'tmpget'; // copy 复制 - $filename = spurlencode($_GET['copy_name']); - $filename = path_format($path1 . '/' . $filename); - $namearr = splitlast($_GET['copy_name'], '.'); - if ($namearr[0]!='') { - $newname = $namearr[0] . ' (' . getconstStr('Copy') . ')'; - if ($namearr[1]!='') $newname .= '.' . $namearr[1]; - } else { - $newname = '.' . $namearr[1] . ' (' . getconstStr('Copy') . ')'; - } - //$newname = spurlencode($newname); - //$foldername = path_format('/'.urldecode($path1).'/./'); - //$data = '{"parentReference":{"path": "/drive/root:'.$foldername.'"}}'; - $data = '{ "name": "' . $newname . '" }'; - $result = MSAPI('copy', $filename, $data, $_SERVER['access_token']); - $num = 0; - while ($result['stat']==409 && json_decode($result['body'], true)['error']['code']=='nameAlreadyExists') { - $num++; - if ($namearr[0]!='') { - $newname = $namearr[0] . ' (' . getconstStr('Copy') . ' ' . $num . ')'; - if ($namearr[1]!='') $newname .= '.' . $namearr[1]; - } else { - $newname = '.' . $namearr[1] . ' ('.getconstStr('Copy'). ' ' . $num .')'; - } - //$newname = spurlencode($newname); - $data = '{ "name": "' . $newname . '" }'; - $result = MSAPI('copy', $filename, $data, $_SERVER['access_token']); - } - //echo $result['stat'].$result['body']; - //savecache('path_' . $path1, json_decode('{}',true), 1); - //if ($_GET['move_folder'] == '/../') $path2 = path_format( substr($path1, 0, strrpos($path1, '/')) . '/' ); - //else $path2 = path_format( $path1 . '/' . $_GET['move_folder'] . '/' ); - //savecache('path_' . $path2, json_decode('{}',true), 1); - return output($result['body'], $result['stat']); + $file['path'] = $path1; + $file['name'] = ${$VAR}['copy_name']; + $file['id'] = ${$VAR}['copy_fileid']; + return $drive->Copy($file); } - if (isset($_POST['editfile'])) { + if (isset($tmppost['editfile'])) { + if (!compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) return ['statusCode'=>403]; // edit 编辑 - $data = $_POST['editfile']; - /*TXT一般不会超过4M,不用二段上传 - $filename = $path1 . ':/createUploadSession'; - $response=MSAPI('POST',$filename,'{"item": { "@microsoft.graph.conflictBehavior": "replace" }}',$_SERVER['access_token']); - $uploadurl=json_decode($response,true)['uploadUrl']; - echo MSAPI('PUT',$uploadurl,$data,$_SERVER['access_token']);*/ - $result = MSAPI('PUT', $path1, $data, $_SERVER['access_token'])['body']; - //echo $result; - $resultarry = json_decode($result,true); - if (isset($resultarry['error'])) return message($resultarry['error']['message']. '
'.getconstStr('Back').'','Error',403); + $file['path'] = $path1; + $file['name'] = ''; + $file['id'] = ''; + return $drive->Edit($file, $tmppost['editfile']); } - if (isset($_GET['create_name'])) { + if (isset($tmpget['create_name']) || isset($tmppost['create_name'])) { + if (!compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) return ['statusCode'=>403]; + if (isset($tmppost['create_name'])) $VAR = 'tmppost'; + else $VAR = 'tmpget'; // create 新建 - if ($_GET['create_type']=='file') { - $filename = spurlencode($_GET['create_name']); - $filename = path_format($path1 . '/' . $filename); - $result = MSAPI('PUT', $filename, $_GET['create_text'], $_SERVER['access_token']); - } - if ($_GET['create_type']=='folder') { - $data = '{ "name": "' . $_GET['create_name'] . '", "folder": { }, "@microsoft.graph.conflictBehavior": "rename" }'; - $result = MSAPI('children', $path1, $data, $_SERVER['access_token']); - } - //savecache('path_' . $path1, json_decode('{}',true), 1); - return output($result['body'], $result['stat']); - } - if (isset($_GET['RefreshCache'])) { - $path1 = path_format($_SERVER['list_path'] . path_format($path)); - if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1); - savecache('path_' . $path1 . '/?password', '', 1); - return message('', getconstStr('RefreshCache'), 302); + $parent['path'] = $path1; + $parent['name'] = ''; + $parent['id'] = ${$VAR}['create_fileid']; + return $drive->Create($parent, ${$VAR}['create_type'], ${$VAR}['create_name'], ${$VAR}['create_text']); } return $tmparr; } @@ -968,6 +1351,7 @@ function splitfirst($str, $split) $tmp[0] = ''; $tmp[1] = substr($str, $len); } + if ($tmp[1]===false) $tmp[1] = ''; return $tmp; } @@ -985,163 +1369,10 @@ function splitlast($str, $split) $tmp[0] = ''; $tmp[1] = substr($str, $len); } + if ($tmp[1]===false) $tmp[1] = ''; return $tmp; } -function MSAPI($method, $path, $data = '', $access_token) -{ - if (substr($path,0,7) == 'http://' or substr($path,0,8) == 'https://') { - $url=$path; - $lenth=strlen($data); - $headers['Content-Length'] = $lenth; - $lenth--; - $headers['Content-Range'] = 'bytes 0-' . $lenth . '/' . $headers['Content-Length']; - } else { - $url = $_SERVER['api_url']; - if ($path=='' or $path=='/') { - $url .= '/'; - } else { - $url .= ':' . $path; - if (substr($url,-1)=='/') $url=substr($url,0,-1); - } - if ($method=='PUT') { - if ($path=='' or $path=='/') { - $url .= 'content'; - } else { - $url .= ':/content'; - } - $headers['Content-Type'] = 'text/plain'; - } elseif ($method=='PATCH') { - $headers['Content-Type'] = 'application/json'; - } elseif ($method=='POST') { - $headers['Content-Type'] = 'application/json'; - } elseif ($method=='DELETE') { - $headers['Content-Type'] = 'application/json'; - } else { - if ($path=='' or $path=='/') { - $url .= $method; - } else { - $url .= ':/' . $method; - } - $method='POST'; - $headers['Content-Type'] = 'application/json'; - } - } - $headers['Authorization'] = 'Bearer ' . $access_token; - if (!isset($headers['Accept'])) $headers['Accept'] = '*/*'; - //if (!isset($headers['Referer'])) $headers['Referer'] = $url;* - $sendHeaders = array(); - foreach ($headers as $headerName => $headerVal) { - $sendHeaders[] = $headerName . ': ' . $headerVal; - } - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST,$method); - curl_setopt($ch, CURLOPT_POSTFIELDS,$data); - curl_setopt($ch, CURLOPT_TIMEOUT, 5); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); - curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders); - $response['body'] = curl_exec($ch); - $response['stat'] = curl_getinfo($ch,CURLINFO_HTTP_CODE); - //$response['Location'] = curl_getinfo($ch); - curl_close($ch); - error_log($response['stat'].' -'.$response['body'].' -'); - return $response; -} - -function fetch_files($path = '/') -{ - global $exts; - $path1 = path_format($path); - $path = path_format($_SERVER['list_path'] . path_format($path)); - if ($path!='/'&&substr($path,-1)=='/') $path=substr($path,0,-1); - if (!($files = getcache('path_' . $path))) { - // https://docs.microsoft.com/en-us/graph/api/driveitem-get?view=graph-rest-1.0 - // https://docs.microsoft.com/zh-cn/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http - // https://developer.microsoft.com/zh-cn/graph/graph-explorer - $pos = splitlast($path, '/'); - $parentpath = $pos[0]; - if ($parentpath=='') $parentpath = '/'; - $filename = $pos[1]; - if ($parentfiles = getcache('path_' . $parentpath)) { - if (isset($parentfiles['children'][$filename][$_SERVER['DownurlStrName']])) { - if (in_array(splitlast($filename,'.')[1], $exts['txt'])) { - if (!(isset($parentfiles['children'][$filename]['content'])&&$parentfiles['children'][$filename]['content']['stat']==200)) { - $content1 = curl_request($parentfiles['children'][$filename][$_SERVER['DownurlStrName']]); - $parentfiles['children'][$filename]['content'] = $content1; - savecache('path_' . $parentpath, $parentfiles); - } - } - return $parentfiles['children'][$filename]; - } - } - - $url = $_SERVER['api_url']; - if ($path !== '/') { - $url .= ':' . $path; - if (substr($url,-1)=='/') $url=substr($url,0,-1); - } - $url .= '?expand=children(select=name,size,file,folder,parentReference,lastModifiedDateTime,'.$_SERVER['DownurlStrName'].')'; - $retry = 0; - $arr = []; - while ($retry<3&&!$arr['stat']) { - $arr = curl_request($url, false, ['Authorization' => 'Bearer ' . $_SERVER['access_token']],1); - $retry++; - } - if ($arr['stat']<500) { - $files = json_decode($arr['body'], true); - //echo $path . '
' . json_encode($arr, JSON_PRETTY_PRINT) . '
'; - if (isset($files['folder'])) { - if ($files['folder']['childCount']>200) { - // files num > 200 , then get nextlink - $page = $_POST['pagenum']==''?1:$_POST['pagenum']; - if ($page>1) $files=fetch_files_children($files, $path1, $page); - $files['children'] = children_name($files['children']); - } else { - // files num < 200 , then cache - //if (isset($files['children'])) { - $files['children'] = children_name($files['children']); - //} - savecache('path_' . $path, $files); - } - } - if (isset($files['file'])) { - if (in_array(splitlast($files['name'],'.')[1], $exts['txt'])) { - if (!(isset($files['content'])&&$files['content']['stat']==200)) { - $content1 = curl_request($files[$_SERVER['DownurlStrName']]); - $files['content'] = $content1; - savecache('path_' . $path, $files); - } - } - } - if (isset($files['error'])) { - $files['error']['stat'] = $arr['stat']; - } - } else { - //error_log($arr['body']); - $files = json_decode($arr['body'], true); - if (isset($files['error'])) { - $files['error']['stat'] = $arr['stat']; - } else { - $files['error']['stat'] = 503; - $files['error']['code'] = 'unknownError'; - $files['error']['message'] = 'unknownError'; - } - //$files = json_decode( '{"unknownError":{ "stat":'.$arr['stat'].',"message":"'.$arr['body'].'"}}', true); - //error_log(json_encode($files, JSON_PRETTY_PRINT)); - } - } - - return $files; -} - function children_name($children) { $tmp = []; @@ -1151,379 +1382,58 @@ function children_name($children) return $tmp; } -function fetch_files_children($files, $path, $page) -{ - $path1 = path_format($path); - $path = path_format($_SERVER['list_path'] . path_format($path)); - if ($path!='/'&&substr($path,-1)=='/') $path=substr($path,0,-1); - $cachefilename = '.SCFcache_'.$_SERVER['function_name']; - $maxpage = ceil($files['folder']['childCount']/200); - if (!($files['children'] = getcache('files_' . $path . '_page_' . $page))) { - // down cache file get jump info. 下载cache文件获取跳页链接 - $cachefile = fetch_files(path_format($path1 . '/' .$cachefilename)); - if ($cachefile['size']>0) { - $pageinfo = curl_request($cachefile[$_SERVER['DownurlStrName']])['body']; - $pageinfo = json_decode($pageinfo,true); - for ($page4=1;$page4<$maxpage;$page4++) { - savecache('nextlink_' . $path . '_page_' . $page4, $pageinfo['nextlink_' . $path . '_page_' . $page4]); - $pageinfocache['nextlink_' . $path . '_page_' . $page4] = $pageinfo['nextlink_' . $path . '_page_' . $page4]; - } - } - $pageinfochange=0; - for ($page1=$page;$page1>=1;$page1--) { - $page3=$page1-1; - $url = getcache('nextlink_' . $path . '_page_' . $page3); - if ($url == '') { - if ($page1==1) { - $url = $_SERVER['api_url']; - if ($path !== '/') { - $url .= ':' . $path; - if (substr($url,-1)=='/') $url=substr($url,0,-1); - $url .= ':/children?$select=name,size,file,folder,parentReference,lastModifiedDateTime,'.$_SERVER['DownurlStrName']; - } else { - $url .= '/children?$select=name,size,file,folder,parentReference,lastModifiedDateTime,'.$_SERVER['DownurlStrName']; - } - $children = json_decode(curl_request($url, false, ['Authorization' => 'Bearer ' . $_SERVER['access_token']])['body'], true); - // echo $url . '
' . json_encode($children, JSON_PRETTY_PRINT) . '
'; - savecache('files_' . $path . '_page_' . $page1, $children['value']); - $nextlink=getcache('nextlink_' . $path . '_page_' . $page1); - if ($nextlink!=$children['@odata.nextLink']) { - savecache('nextlink_' . $path . '_page_' . $page1, $children['@odata.nextLink']); - $pageinfocache['nextlink_' . $path . '_page_' . $page1] = $children['@odata.nextLink']; - $pageinfocache = clearbehindvalue($path,$page1,$maxpage,$pageinfocache); - $pageinfochange = 1; - } - $url = $children['@odata.nextLink']; - for ($page2=$page1+1;$page2<=$page;$page2++) { - sleep(1); - $children = json_decode(curl_request($url, false, ['Authorization' => 'Bearer ' . $_SERVER['access_token']])['body'], true); - savecache('files_' . $path . '_page_' . $page2, $children['value']); - $nextlink=getcache('nextlink_' . $path . '_page_' . $page2); - if ($nextlink!=$children['@odata.nextLink']) { - savecache('nextlink_' . $path . '_page_' . $page2, $children['@odata.nextLink']); - $pageinfocache['nextlink_' . $path . '_page_' . $page2] = $children['@odata.nextLink']; - $pageinfocache = clearbehindvalue($path,$page2,$maxpage,$pageinfocache); - $pageinfochange = 1; - } - $url = $children['@odata.nextLink']; - } - //echo $url . '
' . json_encode($children, JSON_PRETTY_PRINT) . '
'; - $files['children'] = $children['value']; - $files['folder']['page']=$page; - $pageinfocache['filenum'] = $files['folder']['childCount']; - $pageinfocache['dirsize'] = $files['size']; - $pageinfocache['cachesize'] = $cachefile['size']; - $pageinfocache['size'] = $files['size']-$cachefile['size']; - if ($pageinfochange == 1) MSAPI('PUT', path_format($path.'/'.$cachefilename), json_encode($pageinfocache, JSON_PRETTY_PRINT), $_SERVER['access_token'])['body']; - return $files; - } - } else { - for ($page2=$page3+1;$page2<=$page;$page2++) { - sleep(1); - $children = json_decode(curl_request($url, false, ['Authorization' => 'Bearer ' . $_SERVER['access_token']])['body'], true); - savecache('files_' . $path . '_page_' . $page2, $children['value'], 3300); - $nextlink=getcache('nextlink_' . $path . '_page_' . $page2); - if ($nextlink!=$children['@odata.nextLink']) { - savecache('nextlink_' . $path . '_page_' . $page2, $children['@odata.nextLink'], 3300); - $pageinfocache['nextlink_' . $path . '_page_' . $page2] = $children['@odata.nextLink']; - $pageinfocache = clearbehindvalue($path,$page2,$maxpage,$pageinfocache); - $pageinfochange = 1; - } - $url = $children['@odata.nextLink']; - } - //echo $url . '
' . json_encode($children, JSON_PRETTY_PRINT) . '
'; - $files['children'] = $children['value']; - $files['folder']['page']=$page; - $pageinfocache['filenum'] = $files['folder']['childCount']; - $pageinfocache['dirsize'] = $files['size']; - $pageinfocache['cachesize'] = $cachefile['size']; - $pageinfocache['size'] = $files['size']-$cachefile['size']; - if ($pageinfochange == 1) MSAPI('PUT', path_format($path.'/'.$cachefilename), json_encode($pageinfocache, JSON_PRETTY_PRINT), $_SERVER['access_token'])['body']; - return $files; - } - } - } else { - $files['folder']['page']=$page; - for ($page4=1;$page4<=$maxpage;$page4++) { - if (!($url = getcache('nextlink_' . $path . '_page_' . $page4))) { - if ($files['folder'][$path.'_'.$page4]!='') savecache('nextlink_' . $path . '_page_' . $page4, $files['folder'][$path.'_'.$page4]); - } else { - $files['folder'][$path.'_'.$page4] = $url; - } - } - } - return $files; -} - -function render_list($path = '', $files = '') -{ - global $exts; - global $constStr; - - if (isset($files['children']['index.html']) && !$_SERVER['admin']) { - $htmlcontent = fetch_files(spurlencode(path_format(urldecode($path) . '/index.html'),'/'))['content']; - return output($htmlcontent['body'], $htmlcontent['stat']); - } - $path = str_replace('%20','%2520',$path); - $path = str_replace('+','%2B',$path); - $path = str_replace('&','&',path_format(urldecode($path))) ; - $path = str_replace('%20',' ',$path); - $path = str_replace('#','%23',$path); - $p_path=''; - if ($path !== '/') { - if (isset($files['file'])) { - $pretitle = str_replace('&','&', $files['name']); - $n_path = $pretitle; - $tmp = splitlast(splitlast($path,'/')[0],'/'); - if ($tmp[1]=='') { - $p_path = $tmp[0]; - } else { - $p_path = $tmp[1]; - } - } else { - if (substr($path,0,1)=='/') $pretitle = substr($path,1); - if (substr($path,-1)=='/') $pretitle = substr($path,0,-1); - $tmp=splitlast($pretitle,'/'); - if ($tmp[1]=='') { - $n_path = $tmp[0]; - } else { - $n_path = $tmp[1]; - $tmp = splitlast($tmp[0],'/'); - if ($tmp[1]=='') { - $p_path = $tmp[0]; - } else { - $p_path = $tmp[1]; - } - } - } - } else { - $pretitle = getconstStr('Home'); - $n_path=$pretitle; - } - $n_path=str_replace('&','&',$n_path); - $p_path=str_replace('&','&',$p_path); - $pretitle = str_replace('%23','#',$pretitle); - $statusCode=200; - date_default_timezone_set(get_timezone($_SERVER['timezone'])); - @ob_start(); - - $theme = getConfig('theme'); - if ( $theme=='' || !file_exists('theme/'.$theme) ) $theme = 'classic.php'; - include 'theme/'.$theme; - - $html = '' . ob_get_clean(); - //if (isset($htmlpage['statusCode'])) return $htmlpage; - if (isset($_SERVER['Set-Cookie'])) return output($html, $statusCode, [ 'Set-Cookie' => $_SERVER['Set-Cookie'], 'Content-Type' => 'text/html' ]); - return output($html,$statusCode); -} - -function get_refresh_token() -{ - global $constStr; - global $CommonEnv; - $envs = ''; - foreach ($CommonEnv as $env) $envs .= '\'' . $env . '\', '; - $url = path_format($_SERVER['PHP_SELF'] . '/'); - if (isset($_GET['authorization_code']) && isset($_GET['code'])) { - $_SERVER['disktag'] = $_COOKIE['disktag']; - config_oauth(); - $tmp = curl_request($_SERVER['oauth_url'] . 'token', 'client_id=' . $_SERVER['client_id'] .'&client_secret=' . $_SERVER['client_secret'] . '&grant_type=authorization_code&requested_token_use=on_behalf_of&redirect_uri=' . $_SERVER['redirect_uri'] .'&code=' . $_GET['code']); - if ($tmp['stat']==200) $ret = json_decode($tmp['body'], true); - if (isset($ret['refresh_token'])) { - $refresh_token = $ret['refresh_token']; - $str = ' - refresh_token :
'; - $str .= ' -

- '.getconstStr('SavingToken').' - '; - $tmptoken['refresh_token'] = $refresh_token; - $tmptoken['token_expires'] = time()+7*24*60*60; - if (getConfig('usesharepoint')=='on') $tmptoken['siteid'] = get_siteid($ret['access_token']); - setConfig($tmptoken, $_COOKIE['disktag']); - savecache('access_token', $ret['access_token'], $ret['expires_in'] - 60); - //WaitSCFStat(); - $str .= ' - '; - return message($str, getconstStr('WaitJumpIndex')); - } - return message('
' . json_encode(json_decode($tmp['body']), JSON_PRETTY_PRINT) . '
', $tmp['stat']); - //return message('
' . json_encode($ret, JSON_PRETTY_PRINT) . '
', 500); - } - if (isset($_GET['install1'])) { - $_SERVER['disktag'] = $_COOKIE['disktag']; - config_oauth(); - if (getConfig('Drive_ver')=='MS' || getConfig('Drive_ver')=='CN') { - return message(' - '.getconstStr('JumptoOffice').' - - ', getconstStr('Wait').' 1s', 201); - } else { - return message('something error, try after a few seconds.', 'retry', 201); - } - } - if (isset($_GET['install0'])) { - if ($_POST['disktag_add']!='') { - if (in_array($_COOKIE['disktag'], $CommonEnv)) { - return message('Do not input ' . $envs . '
', 'Error', 201); - } - $_SERVER['disktag'] = $_COOKIE['disktag']; - $tmp['disktag_add'] = $_POST['disktag_add']; - $tmp['diskname'] = $_POST['diskname']; - $tmp['Drive_ver'] = $_POST['Drive_ver']; - if ($_POST['Drive_ver']=='shareurl') { - $tmp['shareurl'] = $_POST['shareurl']; - $tmp['refresh_token'] = 1; - } else { - if ($_POST['Drive_custom']=='on') { - $tmp['Drive_custom'] = $_POST['Drive_custom']; - $tmp['client_id'] = $_POST['client_id']; - $tmp['client_secret'] = $_POST['client_secret']; - } - if ($_POST['usesharepoint']=='on') { - $tmp['usesharepoint'] = $_POST['usesharepoint']; - $tmp['sharepointname'] = $_POST['sharepointname']; - } - } - $response = setConfigResponse( setConfig($tmp, $_COOKIE['disktag']) ); - if (api_error($response)) { - $html = api_error_msg($response); - $title = 'Error'; - } else { - $title = getconstStr('MayinEnv'); - $html = getconstStr('Wait') . ' 3s'; - if ($_POST['Drive_ver']=='shareurl') $html = getconstStr('Wait') . ' 3s'; - } - return message($html, $title, 201); - } - } - - if ($constStr['language']!='zh-cn') { - $linklang='en-us'; - } else $linklang='zh-cn'; - $ru = "https://developer.microsoft.com/".$linklang."/graph/quick-start?appID=_appId_&appName=_appName_&redirectUrl=".$_SERVER['redirect_uri']."&platform=option-php"; - $deepLink = "/quickstart/graphIO?publicClientSupport=false&appName=OneManager&redirectUrl=".$_SERVER['redirect_uri']."&allowImplicitFlow=false&ru=".urlencode($ru); - $app_url = "https://apps.dev.microsoft.com/?deepLink=".urlencode($deepLink); - $html = ' -
-
- '.getconstStr('OnedriveDiskTag').': ('.getConfig('disktag').')
- '.getconstStr('OnedriveDiskName').':
-
-
-
-
-
-
-
- -
-
- -
- -
-
- -
-
- '; - $title = 'Bind Disk'; - return message($html, $title, 201); -} - function EnvOpt($needUpdate = 0) { global $constStr; - global $ShowedCommonEnv; - global $ShowedInnerEnv; + global $EnvConfigs; global $timezones; - asort($ShowedCommonEnv); - asort($ShowedInnerEnv); + global $slash; + global $drive; + ksort($EnvConfigs); + $disktags = explode('|', getConfig('disktag')); + $envs = ''; + //foreach ($EnvConfigs as $env => $v) if (isCommonEnv($env)) $envs .= '\'' . $env . '\', '; + $envs = substr(json_encode(array_keys ($EnvConfigs)), 1, -1); + $html = 'OneManager '.getconstStr('Setup').''; - if (isset($_POST['updateProgram'])&&$_POST['updateProgram']==getconstStr('updateProgram')) { - $response = OnekeyUpate($_POST['auth'], $_POST['project'], $_POST['branch']); + if (isset($_POST['updateProgram'])&&$_POST['updateProgram']==getconstStr('updateProgram')) if (compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) { + $response = setConfigResponse(OnekeyUpate($_POST['GitSource'], $_POST['auth'], $_POST['project'], $_POST['branch'])); if (api_error($response)) { $html = api_error_msg($response); $title = 'Error'; + return message($html, $title, 400); } else { //WaitSCFStat(); - $html .= getconstStr('UpdateSuccess') . '
-'; + $html .= getconstStr('UpdateSuccess') . '
' . getconstStr('Back') . ''; $title = getconstStr('Setup'); + return message($html, $title, 202, 1); } - return message($html, $title); - } - if (isset($_POST['submit1'])) { + } else return message('please login again', 'Need login', 403); + if (isset($_POST['submit1'])) if (compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) { $_SERVER['disk_oprating'] = ''; foreach ($_POST as $k => $v) { - if (in_array($k, $ShowedCommonEnv)||in_array($k, $ShowedInnerEnv)||$k=='disktag_del' || $k=='disktag_add') { + if (isShowedEnv($k) || $k=='disktag_del' || $k=='disktag_add' || $k=='disktag_rename' || $k=='disktag_copy') { $tmp[$k] = $v; } + if ($k=='disktag_newname') { + $v = preg_replace('/[^0-9a-zA-Z|_]/i', '', $v); + $f = substr($v, 0, 1); + if (strlen($v)==1) $v .= '_'; + if (isCommonEnv($v)) { + return message('Do not input ' . $envs . '
' . getconstStr('Back') . '', 'Error', 400); + } elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) { + return message('' . getconstStr('Back') . '', 'Please start with letters', 400); + } elseif (getConfig($v)) { + return message('' . getconstStr('Back') . '', 'Same tag', 400); + } else { + $tmp[$k] = $v; + } + } + if ($k=='disktag_sort') { + $td = implode('|', json_decode($v)); + if (strlen($td)==strlen(getConfig('disktag'))) $tmp['disktag'] = $td; + else return message('Something wrong.', 'ERROR', 400); + } if ($k == 'disk') $_SERVER['disk_oprating'] = $v; } /*if ($tmp['domain_path']!='') { @@ -1537,63 +1447,172 @@ function EnvOpt($needUpdate = 0) }*/ $response = setConfigResponse( setConfig($tmp, $_SERVER['disk_oprating']) ); if (api_error($response)) { - $html = api_error_msg($response); - $title = 'Error'; - } else { - //WaitSCFStat(); - //sleep(3); + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 409); + } else { $html .= getconstStr('Success') . '!
-'; + ' . getconstStr('Back') . ' + '; $title = getconstStr('Setup'); + return message($html, $title, 200, 1); } - return message($html, $title); - } - if (isset($_GET['preview'])) { - $preurl = $_SERVER['PHP_SELF'] . '?preview'; - } else { - $preurl = path_format($_SERVER['PHP_SELF'] . '/'); - } - $html .= ' -'.getconstStr('Back').'   '.getconstStr('Back').getconstStr('Home').'
-Github
'; + } else return message('please login again', 'Need login', 403); + if (isset($_POST['config_b'])) if (compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) { + if (!$_POST['pass']) return output("{\"Error\": \"No admin pass\"}", 403); + if (!is_numeric($_POST['timestamp'])) return output("{\"Error\": \"Error time\"}", 403); + if (abs(time() - $_POST['timestamp']/1000) > 5*60) return output("{\"Error\": \"Timeout\"}", 403); + + if ($_POST['pass']==sha1(getConfig('admin') . $_POST['timestamp'])) { + if ($_POST['config_b'] == 'export') { + foreach ($EnvConfigs as $env => $v) { + if (isCommonEnv($env)) { + $value = getConfig($env); + if ($value) $tmp[$env] = $value; + } + } + foreach ($disktags as $disktag) { + $d = getConfig($disktag); + if ($d == '') { + $d = ''; + } elseif (gettype($d)=='array') { + $tmp[$disktag] = $d; + } else { + $tmp[$disktag] = json_decode($d, true); + } + } + unset($tmp['admin']); + return output(json_encode($tmp, JSON_PRETTY_PRINT)); + } + if ($_POST['config_b'] == 'import') { + if (!$_POST['config_t']) return output("{\"Error\": \"Empty config.\"}", 403); + $c = '{' . splitfirst($_POST['config_t'], '{')[1]; + $c = splitlast($c, '}')[0] . '}'; + $tmp = json_decode($c, true); + if (!!!$tmp) return output("{\"Error\": \"Config input error. " . $c . "\"}", 403); + if (isset($tmp['disktag'])) $tmptag = $tmp['disktag']; + foreach ($EnvConfigs as $env => $v) { + if (isCommonEnv($env)) { + if (isShowedEnv($env)) { + if (getConfig($env)!=''&&!isset($tmp[$env])) $tmp[$env] = ''; + } else { + unset($tmp[$env]); + } + } + } + if ($disktags) foreach ($disktags as $disktag) { + if ($disktag!=''&&!isset($tmp[$disktag])) $tmp[$disktag] = ''; + } + if ($tmptag) $tmp['disktag'] = $tmptag; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + return output("{\"Error\": \"" . api_error_msg($response) . "\"}", 500); + } else { + return output("{\"Success\": \"Success\"}", 200); + } + } + return output(json_encode($_POST), 500); + } else { + return output("{\"Error\": \"Admin pass error\"}", 403); + } + } else return message('please login again', 'Need login', 403); + if (isset($_POST['changePass'])) if (compareadminmd5('admin', getConfig('admin'), $_COOKIE['admin'], $_POST['_admin'])) { + if (!is_numeric($_POST['timestamp'])) return message("Error time" . getconstStr('Back') . "", "Error", 403); + if (abs(time() - $_POST['timestamp']/1000) > 5*60) return message("Timeout" . getconstStr('Back') . "", "Error", 403); + if ($_POST['newPass1']==''||$_POST['newPass2']=='') return message("Empty new pass" . getconstStr('Back') . "", "Error", 403); + if ($_POST['newPass1']!==$_POST['newPass2']) return message("Twice new pass not the same" . getconstStr('Back') . "", "Error", 403); + if ($_POST['newPass1']==getConfig('admin')) return message("New pass same to old one" . getconstStr('Back') . "", "Error", 403); + if ($_POST['oldPass']==sha1(getConfig('admin') . $_POST['timestamp'])) { + $tmp['admin'] = $_POST['newPass1']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + return message(api_error_msg($response) . "" . getconstStr('Back') . "", "Error", 403); + } else { + return message("Success" . getconstStr('Back') . "", "Success", 200, 1); + } + } else { + return message("Old pass error" . getconstStr('Back') . "", "Error", 403); + } + } else return message('please login again', 'Need login', 403); $html .= ' +' . getconstStr('Back') . '
+ +'; + if ($_GET['setup']==='cmd') { + $statusCode = 200; + $html .= ' +OneManager DIR: ' . __DIR__ . ' +
+
+ +
'; + if ($_POST['cmd']!='') { + $html .= ' +
';
+            @ob_start();
+            passthru($_POST['cmd'], $cmdstat);
+            $html .= '
+stat: ' . $cmdstat . '
+output:
+
+';
+            if ($cmdstat>0) $statusCode = 400;
+            if ($cmdstat===1) $statusCode = 403;
+            if ($cmdstat===127) $statusCode = 404;
+            $html .= htmlspecialchars(ob_get_clean());
+            $html .= '
'; + } + $html .= ' +'; + return message($html, 'Run cmd', $statusCode); + } + if ($_GET['setup']==='auth') { + return changeAuthKey(); + } + if ($_GET['setup']==='platform') { + $frame .= ' - - - '; - foreach ($ShowedCommonEnv as $key) { - if ($key=='timezone') { - $html .= ' + '; + foreach ($EnvConfigs as $key => $val) if (isCommonEnv($key) && isShowedEnv($key)) { + $frame .= ' - - '; + ' . getconstStr('EnvironmentsDescription')[$key]; } elseif ($key=='theme') { - $theme_arr = scandir('theme'); - $html .= ' - - - - '; + ' . getconstStr('EnvironmentsDescription')[$key]; } /*elseif ($key=='domain_path') { $tmp = getConfig($key); $domain_path = ''; @@ -1601,86 +1620,303 @@ function EnvOpt($needUpdate = 0) $domain_path .= $k1 . ':' . $v1 . '|'; } $domain_path = substr($domain_path, 0, -1); - $html .= ' + $frame .= ' '; - }*/ else $html .= ' - - - + }*/ else $frame .= ' + '; + $frame .= ' + '; } - $html .= ' - + $frame .= ' +
'.getconstStr('PlatformConfig').'
+ '; + if ($key=='timezone') { + $frame .= ' -
+ $theme_arr = scandir(__DIR__ . $slash . 'theme'); + $frame .= ' -

'; - foreach (explode("|",getConfig('disktag')) as $disktag) { - if ($disktag!='') { - $html .= ' + } elseif (isset($_GET['disktag'])&&$_GET['disktag']!==true&&in_array($_GET['disktag'], $disktags)) { + $disktag = $_GET['disktag']; + $disk_tmp = null; + $diskok = driveisfine($disktag, $disk_tmp); + $frame .= ' + + + + +
+
+ + + + +
+

+ + + + + +
+
+ + + +
+
+
+ + + +
+
- - - - - '; - if (getConfig('refresh_token', $disktag)!='') { - $html .= ' - - '; - foreach ($ShowedInnerEnv as $key) { - $html .= ' - - - - '; - } - $html .= ' - - '; + + + + '; + if ($diskok) { + $frame .= ' + + + '; + foreach (extendShow_diskenv($disk_tmp) as $ext_env) { + $frame .= ' + + + + '; } - $html .= ' -
'.$disktag.': - - -
Driver' . getConfig('Driver', $disktag); + if ($diskok) $frame .= ' ' . getconstStr('ChangeDrivetype') . ''; + $frame .= '
diskSpace' . $disk_tmp->getDiskSpace() . '
' . $ext_env . '' . getConfig($ext_env, $disktag) . '

'; + + $frame .= ' +
+ + '; + foreach ($EnvConfigs as $key => $val) if (isInnerEnv($key) && isShowedEnv($key)) { + $frame .= ' + + + + '; + } + $frame .= ' + +
'; + } else { + $frame .= ' + + ' . ($disk_tmp->error['body']?$disk_tmp->error['stat'] . '
' . $disk_tmp->error['body']:'Add this disk again.') . ' +'; } + $frame .= ' + + +'; } else { - $html .= ' + if (count($disktags)>1) { + $frame .= ' + + +' . getconstStr('DragSort') . ': +
+ + + '; + $num = 0; + foreach ($disktags as $disktag) { + if ($disktag!='') { + $num++; + $frame .= ' + '; + } + } + $frame .= ' + + +
' . $num . ' ' . $disktag . '
+ +
+ +
'; + } + $Driver_arr = scandir(__DIR__ . $slash . 'disk'); + $frame .= ' + +' . getconstStr('AddDisk') . '

+'; + + $canOneKeyUpate = 0; + if (isset($_SERVER['USER'])&&$_SERVER['USER']==='qcloud') { + $canOneKeyUpate = 1; + } elseif (isset($_SERVER['HEROKU_APP_DIR'])&&$_SERVER['HEROKU_APP_DIR']==='/app') { + $canOneKeyUpate = 1; + } elseif (isset($_SERVER['FC_FUNC_CODE_PATH'])) { + $canOneKeyUpate = 1; + } elseif (isset($_SERVER['BCE_CFC_RUNTIME_NAME'])&&$_SERVER['BCE_CFC_RUNTIME_NAME']=='php7') { + $canOneKeyUpate = 1; + } elseif (isset($_SERVER['_APP_SHARE_DIR'])&&$_SERVER['_APP_SHARE_DIR']==='/var/share/CFF/processrouter') { + $canOneKeyUpate = 1; + } elseif (isset($_SERVER['DOCUMENT_ROOT'])&&$_SERVER['DOCUMENT_ROOT']==='/var/task/user') { + $canOneKeyUpate = 1; + } else { + $tmp = time(); + if ( mkdir(''.$tmp, 0777) ) { + rmdir(''.$tmp); + $canOneKeyUpate = 1; + } + } + $frame .= ' + Github +HIT Gitlab

+'; + if (!$canOneKeyUpate) { + $frame .= ' +' . getconstStr('CannotOneKeyUpate') . '
'; + } else { + $frame .= '
- - - - + + Update from + + + + - +
+ '; - } - if ($needUpdate) { - $html .= '
- ' . str_replace("\r", '
',$_SERVER['github_version']) . ' + } + if ($needUpdate) { + $frame .= '
+ ' . str_replace("\n", '
', $_SERVER['github_ver_new']) . ' +
+ +'; - } else { - $html .= getconstStr('NotNeedUpdate'); + }/* else { + $frame .= getconstStr('NotNeedUpdate'); + }*/ + $frame .= '

+ + + + + + + + + + + + + + + + + +
' . getconstStr('OldPassword') . ': +
' . getconstStr('NewPassword') . ':
' . getconstStr('ReInput') . ':

+ + + + + + + + + +
' . getconstStr('AdminPassword') . ': +
' . getconstStr('config') . ': +

+'; + } + $html .= ' + +
'; + if ($_GET['disktag']==''||$_GET['disktag']===true||!in_array($_GET['disktag'], $disktags)) { + if ($_GET['setup']==='platform') $html .= ' + ' . getconstStr('Home') . ' + ' . getconstStr('PlatformConfig') . ''; + else $html .= ' + ' . getconstStr('Home') . ' + ' . getconstStr('PlatformConfig') . ''; + } else $html .= ' + ' . getconstStr('Home') . ' + ' . getconstStr('PlatformConfig') . ''; + foreach ($disktags as $disktag) { + if ($disktag!='') { + if ($_GET['disktag']===$disktag) $html .= ' + ' . $disktag . ''; + else $html .= ' + ' . $disktag . ''; + } + } + $html .= ' +

'; + $html .= $frame; + $html .= ''; return message($html, getconstStr('Setup')); } + +function render_list($path = '', $files = []) +{ + global $exts; + global $constStr; + global $slash; + + if (isset($files['list']['index.html']) && !$_SERVER['admin']) { + $htmlcontent = get_content(path_format($path . '/index.html'))['content']; + return output($htmlcontent['body'], $htmlcontent['stat']); + } + //$path = str_replace('%20','%2520',$path); + //$path = str_replace('+','%2B',$path); + $path1 = path_format(urldecode($path)); + //$path = str_replace('&','&', $path) ; + //$path = str_replace('%20',' ',$path); + //$path = str_replace('#','%23',$path); + $p_path=''; + if ($path1 !== '/') { + if ($files['type']=='file') { + if (isset($files['name'])) { + $pretitle = str_replace('&','&', $files['name']); + } else { + if (substr($path1, 0, 1)=='/') $pretitle = substr($path1, 1); + if (substr($path1, -1)=='/') $pretitle = substr($pretitle, 0, -1); + $pretitle = str_replace('&','&', $pretitle); + } + $n_path = $pretitle; + $tmp = splitlast(splitlast($path1,'/')[0],'/'); + if ($tmp[1]=='') { + $p_path = $tmp[0]; + } else { + $p_path = $tmp[1]; + } + } else { + if (substr($path1, 0, 1)=='/') $pretitle = substr($path1, 1); + if (substr($path1, -1)=='/') $pretitle = substr($pretitle, 0, -1); + $pretitle = str_replace('&','&', $pretitle); + $tmp = splitlast($pretitle, '/'); + if ($tmp[1]=='') { + $n_path = $tmp[0]; + } else { + $n_path = $tmp[1]; + $tmp = splitlast($tmp[0],'/'); + if ($tmp[1]=='') { + $p_path = $tmp[0]; + } else { + $p_path = $tmp[1]; + } + } + } + } else { + $pretitle = getconstStr('Home'); + $n_path = $pretitle; + } + $n_path = str_replace('&','&',$n_path); + $p_path = str_replace('&','&',$p_path); + //$pretitle = str_replace('%23','#',$pretitle); + $statusCode = 200; + date_default_timezone_set(get_timezone($_SERVER['timezone'])); + $authinfo = ' +'; + //$authinfo = $path . '
' . json_encode($files, JSON_PRETTY_PRINT) . '
'; + + //if (isset($_COOKIE['theme'])&&$_COOKIE['theme']!='') $theme = $_COOKIE['theme']; + //if ( !file_exists(__DIR__ . $slash .'theme' . $slash . $theme) ) $theme = ''; + if ($_SERVER['admin']) $theme = 'classic.html'; + if ( $theme=='' ) { + $tmp = getConfig('customTheme'); + if ( $tmp!='' ) $theme = $tmp; + } + if ( $theme=='' ) { + $theme = getConfig('theme'); + if ( $theme=='' || !file_exists(__DIR__ . $slash .'theme' . $slash . $theme) ) $theme = 'classic.html'; + } + if (substr($theme,-4)=='.php') { + @ob_start(); + include 'theme/' . $theme; + $html = ob_get_clean(); + } else { + if (file_exists(__DIR__ . $slash .'theme' . $slash . $theme)) { + $file_path = __DIR__ . $slash .'theme' . $slash . $theme; + $html = file_get_contents($file_path); + } else { + if (!($html = getcache('customTheme'))) { + $file_path = $theme; + $tmp = curl('GET', $file_path, '', [], 1); + if ($tmp['stat']==302) { + error_log1(json_encode($tmp)); + $tmp = curl('GET', $tmp["returnhead"]["Location"]); + } + if (!!$tmp['body']) $html = $tmp['body']; + savecache('customTheme', $html, '', 9999); + } + + } + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $IconValues = json_decode($tmp[0], true); + $html .= $tmp[1]; + + if (!$files) { + //$html = '
'.json_encode($files, JSON_PRETTY_PRINT).'
' . $html; + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + if ($_SERVER['admin']) { + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + while (strpos($html, '')) $html = str_replace('', getconstStr('Operate'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Create'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Encrypt'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('RefreshCache'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Setup'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Logout'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Rename'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Submit'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Delete'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Copy'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Move'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Folder'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('File'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Name'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Content'), $html); + + } else { + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + if (getConfig('adminloginpage')=='') { + while (strpos($html, '')) $html = str_replace('', '', $html); + while (strpos($html, '')) $html = str_replace('', '', $html); + } else { + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + while (strpos($html, '')) $html = str_replace('', '', $html); + while (strpos($html, '')) $html = str_replace('', '', $html); + } + + if ($_SERVER['ishidden']<4 || ($files['type']=='file'&&getConfig('downloadencrypt', $_SERVER['disktag']))) { + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + } else { + // 加密状态 + if (getConfig('useBasicAuth')) { + // use Basic Auth + return output('Need password.', 401, ['WWW-Authenticate'=>'Basic realm="Secure Area"']); + } + /*$tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + }*/ + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + while (strpos($html, '')) $html = str_replace('', getconstStr('Download'), $html); + + if ($_SERVER['is_guestup_path']&&!$_SERVER['admin']) { + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } else { + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + } + $DriverFile = scandir(__DIR__ . $slash . 'disk'); + $Driver_arr = null; + foreach ($DriverFile as $v1) { + if ($v1!='.' && $v1!='..') { + $v1 = splitlast($v1, '.php')[0]; + $Driver_arr[] = $v1; + } + } + if ($_SERVER['is_guestup_path']||( $_SERVER['admin']&&$files['type']=='folder'&&$_SERVER['ishidden']<4 )) { + $now_driver = baseclassofdrive(); + if ($now_driver) { + while (strpos($html, '')) $html = str_replace('', '', $html); + while (strpos($html, '')) $html = str_replace('', '', $html); + unset($Driver_arr[$now_driver]); + while (strpos($html, '')) $html = str_replace('', '', $html); + while (strpos($html, '')) $html = str_replace('', '', $html); + } else { + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + foreach ($Driver_arr as $driver) { + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + while (strpos($html, '')) $html = str_replace('', getconstStr('Calculate'), $html); + } else { + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + foreach ($Driver_arr as $driver) { + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + } + + if ($files['type']=='file') { + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + //$html = str_replace('', encode_str_replace(path_format($_SERVER['base_disk_path'] . '/' . $path)), $html); + $html = str_replace('', encode_str_replace(splitlast($path1, '/')[1]), $html); + $html = str_replace('', (path_format($_SERVER['base_disk_path'] . '/' . $path1)), $html); + + $ext = strtolower(substr($path, strrpos($path, '.') + 1)); + if (in_array($ext, $exts['img'])) $ext = 'img'; + elseif (in_array($ext, $exts['video'])) $ext = 'video'; + elseif (in_array($ext, $exts['music'])) $ext = 'music'; + //elseif (in_array($ext, $exts['pdf'])) $ext = 'pdf'; + elseif ($ext=='pdf') $ext = 'pdf'; + elseif (in_array($ext, $exts['office'])) $ext = 'office'; + elseif (in_array($ext, $exts['txt'])) $ext = 'txt'; + else $ext = 'Other'; + $previewext = ['img', 'video', 'music', 'pdf', 'office', 'txt', 'Other']; + $previewext = array_diff($previewext, [ $ext ]); + foreach ($previewext as $ext1) { + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + //while (strpos($html, '')) $html = str_replace('', $files['url'], $html); + //while (strpos($html, '')) $html = str_replace('', (path_format($_SERVER['base_disk_path'] . '/' . $path)), $html); + while (strpos($html, '')) $html = str_replace('', encode_str_replace(splitlast($path1, '/')[1]), $html); + //echo $path . "
\n"; + //while (strpos($html, '')) $html = str_replace('', (path_format($_SERVER['base_disk_path'] . '/' . str_replace('&', '&', $path))), $html); + while (strpos($html, '')) $html = str_replace('', encode_str_replace(splitlast($path1, '/')[1]), $html); + while (strpos($html, '')) $html = str_replace('', $files['name'], $html); + while (strpos($html, '')) $html = str_replace('', urlencode($files['url']), $html); + //while (strpos($html, '')) $html = str_replace('', urlencode($_SERVER['host'] . path_format($_SERVER['base_disk_path'] . '/' . $path)), $html); + $html = str_replace('', getconstStr('ClicktoEdit'), $html); + $html = str_replace('', getconstStr('CancelEdit'), $html); + $html = str_replace('', getconstStr('Save'), $html); + if (strpos($html, '')) { + //$tmp_content = get_content(spurlencode(path_format(urldecode($path)), '/'))['content']['body']; + $tmp_content = $files['content']['body']; + //if (strlen($tmp_content)==$files['size']) + $html = str_replace('', htmlspecialchars($tmp_content), $html); + //else $html = str_replace('', $files['size']<1024*1024?htmlspecialchars(curl('GET', $files['url'], '', [], 0, 1)['body']):"File too large: " . $files['size'] . " B.", $html); + } + $html = str_replace('', getconstStr('FileNotSupport'), $html); + + //$html = str_replace('', getconstStr('File'), $html); + } elseif ($files['type']=='folder') { + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + $html = str_replace('', getconstStr('File'), $html); + while (strpos($html, '')) $html = str_replace('', $files['id'], $html); + $html = str_replace('', getconstStr('ShowThumbnails'), $html); + $html = str_replace('', getconstStr('CopyAllDownloadUrl'), $html); + $html = str_replace('', getconstStr('EditTime'), $html); + $html = str_replace('', getconstStr('Size'), $html); + + $filenum = 0; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $FolderList = $tmp[0]; + foreach ($files['list'] as $file) { + if ($file['type']=='folder') { + if ($_SERVER['admin'] or !isHideFile($file['name'])) { + $filenum++; + //$FolderListStr = str_replace('', encode_str_replace(path_format($_SERVER['base_disk_path'] . '/' . str_replace('&', '&', $path) . '/' . $file['name'])), $FolderList); + $FolderListStr = str_replace('', encode_str_replace($file['name']), $FolderList); + $FolderListStr = str_replace('', $file['id'], $FolderListStr); + $FolderListStr = str_replace('', str_replace('&','&', $file['showname']?$file['showname']:$file['name']), $FolderListStr); + $FolderListStr = str_replace('', time_format($file['time']), $FolderListStr); + $FolderListStr = str_replace('', size_format($file['size']), $FolderListStr); + while (strpos($FolderListStr, '')) $FolderListStr = str_replace('', $filenum, $FolderListStr); + $html .= $FolderListStr; + } + } + } + $html .= $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $FolderList = $tmp[0]; + foreach ($files['list'] as $file) { + if ($file['type']=='file') { + if ($_SERVER['admin'] or !isHideFile($file['name'])) { + $filenum++; + $ext = strtolower(substr($file['name'], strrpos($file['name'], '.') + 1)); + $FolderListStr = $FolderList; + //while (strpos($FolderListStr, '')) $FolderListStr = str_replace('', encode_str_replace(path_format($_SERVER['base_disk_path'] . '/' . str_replace('&', '&', $path) . '/' . $file['name'])), $FolderListStr); + while (strpos($FolderListStr, '')) $FolderListStr = str_replace('', encode_str_replace($file['name']), $FolderListStr); + $FolderListStr = str_replace('', $ext, $FolderListStr); + if (in_array($ext, $exts['music'])) $FolderListStr = str_replace('', 'audio', $FolderListStr); + elseif (in_array($ext, $exts['video'])) $FolderListStr = str_replace('', 'iframe', $FolderListStr); + else $FolderListStr = str_replace('', '', $FolderListStr); + $FolderListStr = str_replace('', str_replace('&','&', $file['name']), $FolderListStr); + $FolderListStr = str_replace('', $file['id'], $FolderListStr); + //$FolderListStr = str_replace('', path_format($_SERVER['base_disk_path'] . '/' . $path . '/' . str_replace('&','&', $file['name'])), $FolderListStr); + $FolderListStr = str_replace('', time_format($file['time']), $FolderListStr); + $FolderListStr = str_replace('', size_format($file['size']), $FolderListStr); + if (!!$IconValues) { + foreach ($IconValues as $key1 => $value1) { + if (isset($exts[$key1])&&in_array($ext, $exts[$key1])) { + $FolderListStr = str_replace('', $value1, $FolderListStr); + } + if ($ext==$key1) { + $FolderListStr = str_replace('', $value1, $FolderListStr); + } + //error_log1('file:'.$file['name'].':'.$key1); + if (!strpos($FolderListStr, '')) break; + } + if (strpos($FolderListStr, '')) $FolderListStr = str_replace('', $IconValues['default'], $FolderListStr); + } + while (strpos($FolderListStr, '')) $FolderListStr = str_replace('', $filenum, $FolderListStr); + $html .= $FolderListStr; + } + } + } + $html .= $tmp[1]; + while (strpos($html, '')) $html = str_replace('', $filenum, $html); + + if ($files['childcount']>200) { + while (strpos($html, '')) $html = str_replace('', '', $html); + while (strpos($html, '')) $html = str_replace('', '', $html); + + $pagenum = $files['page']; + if ($pagenum=='') $pagenum = 1; + $maxpage = ceil($files['childcount']/200); + + if ($pagenum!=1) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + $html = str_replace('', getconstStr('PrePage'), $html); + $html = str_replace('', $pagenum-1, $html); + } else { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + //$html .= json_encode($files['folder']); + if ($pagenum!=$maxpage) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + $html = str_replace('', getconstStr('NextPage'), $html); + $html = str_replace('', $pagenum+1, $html); + } else { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $MorePageListNow = str_replace('', $pagenum, $tmp[0]); + $html .= $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $MorePageList = $tmp[0]; + for ($page=1;$page<=$maxpage;$page++) { + if ($page == $pagenum) { + $MorePageListStr = $MorePageListNow; + } else { + $MorePageListStr = str_replace('', $page, $MorePageList); + $MorePageListStr = str_replace('', $page, $MorePageListStr); + } + $html .= $MorePageListStr; + } + $html .= $tmp[1]; + + while (strpos($html, '')) $html = str_replace('', $maxpage, $html); + + } else { + while (strpos($html, '')) { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + + } + + $html = str_replace('', $constStr['language'], $html); + + $title = $pretitle; + if ($_SERVER['base_disk_path']!=$_SERVER['base_path']) { + if (getConfig('diskname')!='') $diskname = getConfig('diskname'); + else $diskname = $_SERVER['disktag']; + $title .= ' - ' . $diskname; + } + $title .= ' - ' . $_SERVER['sitename']; + $html = str_replace('', $title, $html); + + $keywords = $n_path; + if ($p_path!='') $keywords .= ', ' . $p_path; + if ($_SERVER['sitename']!='OneManager') $keywords .= ', ' . $_SERVER['sitename'] . ', OneManager'; + else $keywords .= ', OneManager'; + $html = str_replace('', $keywords, $html); + + if ($_GET['preview']) { + $description = $n_path.', '.getconstStr('Preview');//'Preview of '. + } elseif ($files['type']=='folder') { + $description = $n_path.', '.getconstStr('List');//'List of '.$n_path.'. '; + } + //$description .= 'In '.$_SERVER['sitename']; + $html = str_replace('', $description, $html); + + while (strpos($html, '')) $html = str_replace('', (substr($_SERVER['base_disk_path'],-1)=='/'?substr($_SERVER['base_disk_path'],0,-1):$_SERVER['base_disk_path']), $html); + while (strpos($html, '')) $html = str_replace('', $_SERVER['base_path'], $html); + $html = str_replace('', str_replace('\'', '\\\'', str_replace('%23', '#', str_replace('&','&', path_format($path1.'/')))), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Home'), $html); + + $html = str_replace('', getConfig('customCss'), $html); + $html = str_replace('', getConfig('customScript'), $html); + + while (strpos($html, '')) $html = str_replace('', getconstStr('Login'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Close'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('InputPassword'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('InputPasswordUWant'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Submit'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Success'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('GetUploadLink'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('UpFileTooLarge'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('UploadStart'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('UploadStartAt'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('LastUpload'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('ThisTime'), $html); + + while (strpos($html, '')) $html = str_replace('', getconstStr('Upload'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('AverageSpeed'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('CurrentSpeed'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('Expect'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('UploadErrorUpAgain'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('EndAt'), $html); + + while (strpos($html, '')) $html = str_replace('', getconstStr('UploadComplete'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('CopyUrl'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('UploadFail23'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('GetFileNameFail'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('UploadFile'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('UploadFolder'), $html); + while (strpos($html, '')) $html = str_replace('', getconstStr('FileSelected'), $html); + while (strpos($html, '')) $html = str_replace('', (isset($_GET['preview'])?'?preview&':'?'), $html); + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + if (getConfig('background')) { + $html .= str_replace('', getConfig('background'), $tmp[0]); + } + $html .= $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + if (getConfig('backgroundm')) { + $html .= str_replace('', getConfig('backgroundm'), $tmp[0]); + } + $html .= $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + if ($tmp[1]!='') { + $tmp = splitfirst($tmp[1], ''); + $PathArrayStr = $tmp[0]; + $tmp_url = $_SERVER['base_disk_path']; + $tmp_path = str_replace('&','&', substr(urldecode($_SERVER['PHP_SELF']), strlen($tmp_url))); + while ($tmp_path!='') { + $tmp1 = splitfirst($tmp_path, '/'); + $folder1 = str_replace('&', '&', $tmp1[0]); + if ($folder1!='') { + $tmp_url .= $folder1 . '/'; + $PathArrayStr1 = str_replace('', encode_str_replace($folder1==$files['name']?'':$tmp_url), $PathArrayStr); + $PathArrayStr1 = str_replace('', str_replace('&', '&', $folder1), $PathArrayStr1); + $html .= $PathArrayStr1; + } + $tmp_path = $tmp1[1]; + } + $html .= $tmp[1]; + } + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + if ($tmp[1]!='') { + $tmp = splitfirst($tmp[1], ''); + $PathArrayStr = $tmp[0]; + $tmp_url = $_SERVER['base_path']; + $tmp_path = str_replace('&','&', substr(urldecode($_SERVER['PHP_SELF']), strlen($tmp_url))); + while ($tmp_path!='') { + $tmp1 = splitfirst($tmp_path, '/'); + $folder1 = str_replace('&', '&', $tmp1[0]); + if ($folder1!='') { + $tmp_url .= $folder1 . '/'; + $PathArrayStr1 = str_replace('', encode_str_replace($folder1==$files['name']?'':$tmp_url), $PathArrayStr); + $PathArrayStr1 = str_replace('', str_replace('&', '&', $folder1==$_SERVER['disktag']?(getConfig('diskname')==''?$_SERVER['disktag']:getConfig('diskname')):$folder1), $PathArrayStr1); + $html .= $PathArrayStr1; + } + $tmp_path = $tmp1[1]; + } + $html .= $tmp[1]; + } + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $SelectLanguage = $tmp[0]; + foreach ($constStr['languages'] as $key1 => $value1) { + $SelectLanguageStr = str_replace('', $key1, $SelectLanguage); + $SelectLanguageStr = str_replace('', $value1, $SelectLanguageStr); + $SelectLanguageStr = str_replace('', ($key1==$constStr['language']?'selected="selected"':''), $SelectLanguageStr); + $html .= $SelectLanguageStr; + } + $html .= $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $NeedUpdateStr = $tmp[0]; + if (isset($_SERVER['needUpdate'])&&$_SERVER['needUpdate']) $NeedUpdateStr = str_replace('', getconstStr('NeedUpdate'), $NeedUpdateStr); + else $NeedUpdateStr =''; + $html .= $NeedUpdateStr . $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $current_url = path_format($_SERVER['PHP_SELF'] . '/'); + if ($current_url !== $_SERVER['base_path']) { + while (substr($current_url, -1) === '/') { + $current_url = substr($current_url, 0, -1); + } + if (strpos($current_url, '/') !== FALSE) { + $parent_url = substr($current_url, 0, strrpos($current_url, '/')); + } else { + $parent_url = $current_url; + } + $BackArrow = str_replace('', $parent_url.'/', $tmp[0]); + } + $html .= $BackArrow . $tmp[1]; + + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + //if (!(isset($_SERVER['USER'])&&$_SERVER['USER']=='qcloud')) { + if (!getConfig('disableShowThumb')) { + $html .= str_replace('', getconstStr('OriginalPic'), $tmp[0]) . $tmp[1]; + } else $html .= $tmp[1]; + } + $imgextstr = ''; + foreach ($exts['img'] as $imgext) $imgextstr .= '\''.$imgext.'\', '; + $html = str_replace('', $imgextstr, $html); + + + $html = str_replace('', $_SERVER['sitename'], $html); + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $disktags = explode("|",getConfig('disktag')); + if (count($disktags)>1) { + $tmp1 = $tmp[1]; + $tmp = splitfirst($tmp[0], ''); + $MultiDiskArea = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $MultiDisks = $tmp[0]; + foreach ($disktags as $disk) { + $diskname = getConfig('diskname', $disk); + if ($diskname=='') $diskname = $disk; + $MultiDisksStr = str_replace('', path_format($_SERVER['base_path'].'/'.$disk.'/'), $MultiDisks); + $MultiDisksStr = str_replace('', ($_SERVER['disktag']==$disk?' now':''), $MultiDisksStr); + $MultiDisksStr = str_replace('', $diskname, $MultiDisksStr); + $MultiDiskArea .= $MultiDisksStr; + } + $MultiDiskArea .= $tmp[1]; + $tmp[1] = $tmp1; + } + $html .= $MultiDiskArea . $tmp[1]; + $diskname = getConfig('diskname', $_SERVER['disktag']); + if ($diskname=='') $diskname = $_SERVER['disktag']; + //if (strlen($diskname)>15) $diskname = substr($diskname, 0, 12).'...'; + while (strpos($html, '')) $html = str_replace('', $diskname, $html); + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + if (isset($files['list']['head.omf'])) { + $headomf = str_replace('', get_content(path_format($path . '/' . $files['list']['head.omf']['name']))['content']['body'], $tmp[0]); + } elseif (getConfig('globalHeadOmfUrl')) { + if (!$headomfcontent = getcache('HeadomfContent')) { + $headomfres = curl('GET', getConfig('globalHeadOmfUrl'), '', [], 0, 1); + if ($headomfres['stat']==200) { + $headomfcontent = $headomfres['body']; + savecache('HeadomfContent', $headomfcontent); + } else $headomfcontent = $headomfres['stat']; + } + $headomf = str_replace('', $headomfcontent, $tmp[0]); + } + $html .= $headomf . $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + if (isset($files['list']['head.md'])) { + $headmd = str_replace('', get_content(path_format($path . '/' . $files['list']['head.md']['name']))['content']['body'], $tmp[0]); + $html .= $headmd . $tmp[1]; + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + } elseif (getConfig('globalHeadMdUrl')) { + if (!$headmdcontent = getcache('HeadmdContent')) { + $headmdres = curl('GET', getConfig('globalHeadMdUrl'), '', [], 0, 1); + if ($headmdres['stat']==200) { + $headmdcontent = $headmdres['body']; + savecache('HeadmdContent', $headmdcontent); + } else $headmdcontent = $headmdres['stat']; + } + $headmd = str_replace('', $headmdcontent, $tmp[0]); + $html .= $headmd . $tmp[1]; + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + } else { + $html .= $tmp[1]; + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html_aft = $tmp[1]; + if ($files) { + $listarea = $tmp[0]; + } + $html .= $listarea . $html_aft; + } + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + if (isset($files['list']['readme.md'])) { + //$Readmemd = str_replace('', get_content(spurlencode(path_format($path1 . '/' . $files['list']['readme.md']['name']),'/'))['content']['body'], $tmp[0]); + $Readmemd = str_replace('', get_content(path_format($path . '/' . $files['list']['readme.md']['name']))['content']['body'], $tmp[0]); + $html .= $Readmemd . $tmp[1]; + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + } elseif (getConfig('globalReadmeMdUrl')) { + if (!$readmemdcontent = getcache('ReadmemdContent')) { + $readmemdres = curl('GET', getConfig('globalReadmeMdUrl'), '', [], 0, 1); + if ($readmemdres['stat']==200) { + $readmemdcontent = $readmemdres['body']; + savecache('ReadmemdContent', $readmemdcontent); + } else $readmemdcontent = $readmemdres['stat']; + } + $Readmemd = str_replace('', $readmemdcontent, $tmp[0]); + $html .= $Readmemd . $tmp[1]; + while (strpos($html, '')) { + $html = str_replace('', '', $html); + $html = str_replace('', '', $html); + } + } else { + $html .= $tmp[1]; + $tmp[1] = 'a'; + while ($tmp[1]!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + } + + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + if (isset($files['list']['foot.omf'])) { + $Footomf = str_replace('', get_content(path_format($path . '/' . $files['list']['foot.omf']['name']))['content']['body'], $tmp[0]); + } elseif (getConfig('globalFootOmfUrl')) { + if (!$footomfcontent = getcache('FootomfContent')) { + $footres = curl('GET', getConfig('globalFootOmfUrl'), '', [], 0, 1); + if ($footres['stat']==200) { + $footomfcontent = $footres['body']; + savecache('FootomfContent', $footomfcontent); + } else $footomfcontent = $footres['stat']; + } + $Footomf = str_replace('', $footomfcontent, $tmp[0]); + } + $html .= $Footomf . $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + if (isset($files['list']['head.md'])||isset($files['list']['readme.md'])||getConfig('globalHeadMdUrl')||getConfig('globalReadmeMdUrl')) { + $html .= $tmp[0] . $tmp[1]; + } else $html .= $tmp[1]; + + if (getConfig('passfile')!='') { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= str_replace('', getconstStr('Encrypt'), $tmp[0]) . $tmp[1]; + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } else { + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= str_replace('', getconstStr('SetpassfileBfEncrypt'), $tmp[0]) . $tmp[1]; + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $html .= $tmp[1]; + } + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + if ($path != '/') { + $html .= str_replace('', getconstStr('ParentDir'), $tmp[0]) . $tmp[1]; + } else $html .= $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + $MoveDirs = $tmp[0]; + if ($files['type']=='folder') { + foreach ($files['list'] as $file) { + if ($file['type']=='folder') { + $MoveDirsStr = str_replace('', str_replace('&','&', $file['name']), $MoveDirs); + $MoveDirsStr = str_replace('', str_replace('&','&', $file['name']), $MoveDirsStr); + $html .= $MoveDirsStr; + } + } + } + $html .= $tmp[1]; + + $tmp = splitfirst($html, ''); + $html = $tmp[0]; + $tmp = splitfirst($tmp[1], ''); + if (!isset($_COOKIE['timezone'])) $html .= str_replace('', $_SERVER['timezone'], $tmp[0]); + $html .= $tmp[1]; + while (strpos($html, '')) $html = str_replace('', $_SERVER['timezone'], $html); + + while (strpos($html, '{{.RawData}}')) { + $str = '['; + $i = 0; + foreach ($files['list'] as $file) if ($_SERVER['admin'] or !isHideFile($file['name'])) { + $tmp = []; + $tmp['name'] = $file['name']; + $tmp['size'] = size_format($file['size']); + $tmp['date'] = time_format($file['lastModifiedDateTime']); + $tmp['@time'] = $file['date']; + $tmp['@type'] = ($file['type']=='folder')?'folder':'file'; + $str .= json_encode($tmp).','; + } + if ($str == '[') { + $str = ''; + } else $str = substr($str, 0, -1).']'; + $html = str_replace('{{.RawData}}', base64_encode($str), $html); + } + + // 最后清除换行 + //while (strpos($html, "\r\n\r\n")) $html = str_replace("\r\n\r\n", "\r\n", $html); + //while (strpos($html, "\r\r")) $html = str_replace("\r\r", "\r", $html); + //while (strpos($html, "\n\n")) $html = str_replace("\n\n", "\n", $html); + //while (strpos($html, PHP_EOL.PHP_EOL)) $html = str_replace(PHP_EOL.PHP_EOL, PHP_EOL, $html); + + $exetime = round(microtime(true)-$_SERVER['php_starttime'],3); + //$ip2city = json_decode(curl('GET', 'http://ip.taobao.com/outGetIpInfo?ip=' . $_SERVER['REMOTE_ADDR'] . '&accessKey=alibaba-inc')['body'], true); + //if ($ip2city['code']===0) $city = ' ' . $ip2city['data']['city']; + $html = str_replace('', date("Y-m-d H:i:s") . " " . getconstStr('Week')[date("w")] . " " . $_SERVER['REMOTE_ADDR'] . $city . ' Runningtime:' . $exetime . 's Mem:' . size_format(memory_get_usage()), $html); + } + + /*if ($_SERVER['admin']||!getConfig('disableChangeTheme')) { + $theme_arr = scandir(__DIR__ . $slash . 'theme'); + $selecttheme = ' +
+ +
+'; + $selectthemescript =' +'; + $tmp = splitfirst($html, ''); + $html = $tmp[0] . $selecttheme . '' . $selectthemescript . $tmp[1]; + }*/ + + $tmp = splitfirst($html, ''); + $html = $tmp[0] . '' . $authinfo . $tmp[1]; + //if (isset($_SERVER['Set-Cookie'])) return output($html, $statusCode, [ 'Set-Cookie' => $_SERVER['Set-Cookie'], 'Content-Type' => 'text/html' ]); + return output($html, $statusCode); +} diff --git a/conststr.php b/conststr.php index f5312b9..403f5d1 100644 --- a/conststr.php +++ b/conststr.php @@ -1,19 +1,24 @@ [ 'en-us' => 'English', - 'zh-cn' => '中文', + 'zh-tw' => '繁體中文', + 'zh-cn' => '简体中文', 'ja' => '日本語', 'ko-kr' => '한국어', 'fa' => 'فارسی', + 'ar-sa' => 'السعودية', ], 'Week' => [ 'en-us' => [ @@ -34,6 +39,15 @@ $constStr = [ 5 => '星期五', 6 => '星期六', ], + 'zh-tw' => [ + 0 => '星期日', + 1 => '星期一', + 2 => '星期二', + 3 => '星期三', + 4 => '星期四', + 5 => '星期五', + 6 => '星期六', + ], 'ja' => [ 0 => '日曜日', 1 => '月曜日', @@ -61,69 +75,164 @@ $constStr = [ 5 => 'جمعه', 6 => 'شنبه', ], + 'ar-sa' => [ + 6 => 'بيوم الأحد', + 0 => 'الإثنين', + 1 => 'الثلاثاء', + 2 => 'الأربعاء', + 3 => 'الخميس', + 4 => 'يوم الجمعة', + 5 => 'في. يوم السبت', + ], ], 'EnvironmentsDescription' => [ 'en-us' => [ 'admin' => 'The admin password, Login button will not show when empty', - 'adminloginpage' => 'if set, the Login button will not display, and the login page no longer \'?admin\', it is \'?{this value}\'.', + 'adminloginpage' => 'if set, the Login button will not display, and the login page no longer \'?login=admin\', it is \'?login={this value}\'.', + 'autoJumpFirstDisk' => 'a switch used in multy disks, if 1, auto jump to first disk', + 'customScript' => ''; + return message($str, getconstStr('WaitJumpIndex'), 201, 1); + } + } + if (isset($_GET['SelectDrive'])) { + if ($this->access_token == '') { + if (isset($_POST['refresh_token'])) { + $res = curl('POST', $this->auth_url, json_encode([ 'refresh_token' => $_POST['refresh_token'], 'grant_type' => 'refresh_token' ]), ["content-type"=>"application/json; charset=utf-8"]); + //return output($res['body']); + if ($res['stat']!=200) { + return message($res['body'], $res['stat'], $res['stat']); + } + //var_dump($res['body']); + $result = json_decode($res['body'], true); + + $tmp = null; + $tmp['refresh_token'] = $result['refresh_token']; + $tmp['token_expires'] = time()+3*24*60*60; + $tmp['Driver'] = 'Aliyundrive'; + //error_log(json_encode($tmp)); + + $response = setConfigResponse( setConfig($tmp, $this->disktag) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } + savecache('access_token', $result['access_token'], $this->disktag, $result['expires_in'] - 60); + } else { + $refresh_token = getConfig('refresh_token', $this->disktag); + if (!$refresh_token) { + $html = 'No refresh_token config, please AddDisk again or wait minutes.
' . $this->disktag; + $title = 'Error'; + return message($html, $title, 201); + } + $response = $this->get_access_token($refresh_token); + if (!$response) return message($this->error['body'], 'Error', $this->error['stat']); + } + } + if (!isset($result['default_drive_id'])) { + $res = curl('POST', $this->auth_url, json_encode([ 'refresh_token' => getConfig('refresh_token', $this->disktag), 'grant_type' => 'refresh_token' ]), ["content-type"=>"application/json; charset=utf-8"]); + //return output($res['body']); + if ($res['stat']!=200) { + return message($res['body'], $res['stat'], $res['stat']); + } + //var_dump($res['body']); + $result = json_decode($res['body'], true); + } + + //$tmp = null; + //$tmp['driveId'] = $result['default_drive_id']; + //$tmp['default_sbox_drive_id'] = $result['default_sbox_drive_id']; + $title = 'Select Driver'; + $html = ' +
+
+
+
+ +
+
+ + '; + return message($html, $title, 201, 1); + } + if (isset($_GET['install0']) && $_POST['disktag_add']!='') { + $_POST['disktag_add'] = preg_replace('/[^0-9a-zA-Z|_]/i', '', $_POST['disktag_add']); + $f = substr($_POST['disktag_add'], 0, 1); + if (strlen($_POST['disktag_add'])==1) $_POST['disktag_add'] .= '_'; + if (isCommonEnv($_POST['disktag_add'])) { + return message('Do not input ' . $envs . '
+ ', 'Error', 201); + } elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) { + return message('Please start with letters
+ ', 'Error', 201); + } + + $tmp = null; + foreach ($EnvConfigs as $env => $v) if (isInnerEnv($env)) $tmp[$env] = ''; + + $tmp['Driver'] = 'Aliyundrive'; + $tmp['disktag_add'] = $_POST['disktag_add']; + $tmp['diskname'] = $_POST['diskname']; + //error_log(json_encode($tmp)); + + $response = setConfigResponse( setConfig($tmp, $this->disktag) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $title = 'Refresh token'; + $html = ' +
+
填入refresh_token: +
+

+ + + + '; + return message($html, $title, 201, 1); + } + } + + $html = ' +
+ + ' . getconstStr('DiskTag') . ': (' . getConfig('disktag') . ') +
+ ' . getconstStr('DiskName') . ': +
+
+ + + +
+ '; + $title = 'Select Account Type'; + return message($html, $title, 201); + } + protected function get_access_token($refresh_token) { + if (!$refresh_token) { + $tmp['stat'] = 0; + $tmp['body'] = 'No refresh_token'; + $this->error = $tmp; + return false; + } + if (!($this->access_token = getcache('access_token', $this->disktag))) { + $p=0; + $tmp1['refresh_token'] = $refresh_token; + $tmp1['grant_type'] = 'refresh_token'; + while ($response['stat']==0&&$p<3) { + $response = curl('POST', $this->auth_url, json_encode($tmp1), ["content-type"=>"application/json; charset=utf-8"]); + $p++; + } + //error_log1(json_encode($response)); + if ($response['stat']==200) $ret = json_decode($response['body'], true); + if (!isset($ret['access_token'])) { + error_log1('failed to get [' . $this->disktag . '] access_token. response: ' . $response['stat'] . $response['body']); + //$response['body'] = json_encode(json_decode($response['body']), JSON_PRETTY_PRINT); + $response['body'] .= 'failed to get [' . $this->disktag . '] access_token.'; + $this->error = $response; + return false; + } + $tmp = $ret; + $tmp['access_token'] = substr($tmp['access_token'], 0, 10) . '******'; + $tmp['refresh_token'] = substr($tmp['refresh_token'], 0, 10) . '******'; + error_log1('[' . $this->disktag . '] Get access token:' . json_encode($tmp, JSON_PRETTY_PRINT)); + $this->access_token = $ret['access_token']; + savecache('access_token', $this->access_token, $this->disktag, $ret['expires_in'] - 300); + if (time()>getConfig('token_expires', $this->disktag)) setConfig([ 'refresh_token' => $ret['refresh_token'], 'token_expires' => time()+3*24*60*60 ], $this->disktag); + return true; + } + return true; + } + public function getDiskSpace() { + if (!($diskSpace = getcache('diskSpace', $this->disktag))) { + $url = $this->api_url . '/databox/get_personal_info'; + $header["content-type"] = "application/json; charset=utf-8"; + $header['authorization'] = 'Bearer ' . $this->access_token; + $response = curl('POST', $url, '', $header); + //error_log1(json_encode($response)); + $res = json_decode($response['body'], true)['personal_space_info']; + $used = size_format($res['used_size']); + $total = size_format($res['total_size']); + $diskSpace = $used . ' / ' . $total; + savecache('diskSpace', $diskSpace, $this->disktag); + } + return $diskSpace; + } +} diff --git a/disk/Googledrive.php b/disk/Googledrive.php new file mode 100644 index 0000000..abba215 --- /dev/null +++ b/disk/Googledrive.php @@ -0,0 +1,865 @@ +disktag = $tag; + $this->redirect_uri = 'https://scfonedrive.github.io'; + if (getConfig('client_id', $tag) && getConfig('client_secret', $tag)) { + $this->client_id = getConfig('client_id', $tag); + $this->client_secret = getConfig('client_secret', $tag); + } else { + $this->client_id = '106151778902-ajieetaab5ondhbvia97n4tr5k0cg8eo.apps.googleusercontent.com'; + $this->client_secret = 'LlCV-rQClzYIKCEqiVddh68G'; + } + //$this->oauth_url = 'https://www.googleapis.com/oauth2/v4/'; + $this->oauth_url = 'https://accounts.google.com/o/oauth2/'; + $this->api_url = 'https://www.googleapis.com/drive/v3'; + $this->scope = 'https://www.googleapis.com/auth/drive'; + + $this->client_secret = urlencode($this->client_secret); + $this->scope = urlencode($this->scope); + //$this->DownurlStrName = '@microsoft.graph.downloadUrl'; + //$this->ext_api_url = '/me/drive/root'; + $this->driveId = getConfig('driveId', $tag); + $res = $this->get_access_token(getConfig('refresh_token', $tag)); + } + + public function isfine() + { + if (!$this->access_token) return false; + else return true; + } + public function show_base_class() + { + return get_class(); + //$tmp[0] = get_class(); + //$tmp[1] = get_class($this); + //return $tmp; + } + + public function ext_show_innerenv() + { + return ['driveId']; + } + + public function list_files($path = '/') + { + $files = $this->list_path($path); + + return $this->files_format($files); + } + + protected function files_format($files) + { + if (isset($files['files']) || (isset($files['mimeType'])&&$files['mimeType']=='application/vnd.google-apps.folder') ) { + $tmp['type'] = 'folder'; + $tmp['id'] = $files['id']; + $tmp['name'] = $files['name']; + $tmp['time'] = $files['modifiedTime']; + $tmp['size'] = $files['size']; + $tmp['childcount'] = $files['folder']['childCount']; + $tmp['page'] = $files['folder']['page']; + foreach ($files['files'] as $file) { + $filename = strtolower($file['name']); + if ($file['mimeType']=='application/vnd.google-apps.folder') { + $tmp['list'][$filename]['type'] = 'folder'; + } else { + $tmp['list'][$filename]['type'] = 'file'; + //var_dump($file); + //echo $file['name'] . ':' . $this->DownurlStrName . ':' . $file[$this->DownurlStrName] . PHP_EOL; + $tmp['list'][$filename]['url'] = ($file['downUrl']?$file['downUrl']:$file['webContentLink']); + $tmp['list'][$filename]['mime'] = $file['mimeType']; + } + $tmp['list'][$filename]['id'] = $file['id']; + $tmp['list'][$filename]['name'] = $file['name']; + $tmp['list'][$filename]['time'] = $file['modifiedTime']; + $tmp['list'][$filename]['size'] = $file['size']; + } + } elseif (isset($files['mimeType'])) { + $tmp['type'] = 'file'; + $tmp['id'] = $files['id']; + $tmp['name'] = $files['name']; + $tmp['time'] = $files['modifiedTime']; + $tmp['size'] = $files['size']; + $tmp['mime'] = $files['mimeType']; + $tmp['url'] = ($files['downUrl']?$files['downUrl']:$files['webContentLink']); + $tmp['content'] = $files['content']; + } else/*if (isset($files['error']))*/ { + return $files; + } + //error_log1(json_encode($tmp)); + return $tmp; + } + + protected function list_path($path = '/') + { + global $exts; + while (substr($path, -1)=='/') $path = substr($path, 0, -1); + if ($path == '') $path = '/'; + + if (!($files = getcache('path_' . $path, $this->disktag))) { + //$response = curl('GET', $this->api_url . '/drives', '', ['Authorization' => 'Bearer ' . $this->access_token]); + //$response = curl('GET', $this->api_url . '/files?fields=*,files(id,name,mimeType,size,modifiedTime,parents,webContentLink,thumbnailLink),nextPageToken' . (($this->driveId!='')?'&driveId=' . $this->driveId . '&corpora=teamDrive&includeItemsFromAllDrives=true&supportsAllDrives=true':''), '', ['Authorization' => 'Bearer ' . $this->access_token]); + if ($path == '/' || $path == '') { + $files = $this->fileList(); + //error_log1('root_id' . $files['id']); + //$files['id'] = 'root'; + //$files['type'] = 'folder'; + } else { + $tmp = splitlast($path, '/'); + $parent_path = $tmp[0]; + $filename = urldecode($tmp[1]); + $parent_folder = $this->list_path($parent_path); + $i = 0; + foreach ($parent_folder['files'] as $item) { + if ($item['name']==$filename) { + if ($item['mimeType']=='application/vnd.google-apps.folder') { + $files = $this->fileList($item['id']); + $files['type'] = 'folder'; + $files['id'] = $item['id']; + $files['name'] = $item['name']; + $files['time'] = $item['modifiedTime']; + $files['size'] = $item['size']; + } else { + if (isset($item['id'])&&$item['shared']!==true) $this->permission('create', $item['id']); + //$this->permission('delete', $files['id']); + + //if (isset($item['mimeType']) && $item['mimeType']!='application/vnd.google-apps.folder') { + if (in_array(strtolower(splitlast($item['name'],'.')[1]), $exts['txt'])) { + if ($files['size']<1024*1024) { + if (!(isset($item['content'])&&$item['content']['stat']==200)) { + //if (!isset($item['downUrl'])) { + $res = curl('GET', $item['webContentLink'], '', [], 1); + $weblink = $res['returnhead']['Location']; + //if ($weblink!==null) $item['downUrl'] = $weblink; + //else error_log1('Cant get link:' . json_encode($res, JSON_PRETTY_PRINT)); + //} + if ($res['stat']==302) { + $content1 = curl('GET', $weblink, '', ["User-Agent"=>"qkqpttgf/OneManager 3.0.0", "Accept"=>"*/*"]); + $tmp = null; + $tmp = json_decode(json_encode($content1), true); + if ($tmp['body']===null) { + $tmp['body'] = iconv("GBK", 'UTF-8//TRANSLIT', $content1['body']); + $tmp = json_decode(json_encode($tmp), true); + if ($tmp['body']!==null) $content1['body'] = $tmp['body']; + } + $item['content'] = $content1; + }// else $content1 = $res; + //error_log1($item['name'] . '~' . json_encode($content1, JSON_PRETTY_PRINT) . PHP_EOL); + $parent_folder['files'][$i] = $item; + savecache('path_' . $path, $parent_folder, $this->disktag); + } + } else { + $files['content']['stat'] = 202; + $files['content']['body'] = 'File too large.'; + } + } + //} + + //error_log1(json_encode($item, JSON_PRETTY_PRINT)); + $files = $item; + } + } + $i++; + } + //echo $files['name']; + } + + if (!$files) { + $files['error']['code'] = 'Not Found'; + $files['error']['message'] = 'Not Found'; + $files['error']['stat'] = 404; + } elseif (isset($files['stat'])) { + $files['error']['stat'] = $files['stat']; + $files['error']['code'] = 'Error'; + $files['error']['message'] = $files['body']; + } else { + savecache('path_' . $path, $files, $this->disktag, 600); + } + } + //error_log1('path:' . $path . ', files:' . json_encode($files, JSON_PRETTY_PRINT)); + //error_log1('path:' . $path . ', files:' . substr(json_encode($files), 0, 150)); + return $files; + } + protected function fileList($parent_file_id = '') + { + $url = $this->api_url . '/files'; + + $url .= '?fields=files(id,name,mimeType,size,modifiedTime,parents,webContentLink,thumbnailLink,shared,permissions,permissionIds),nextPageToken'; + //$url .= '?fields=files(*),nextPageToken'; + //$url .= '?q=mimeType=\'application/vnd.google-apps.folder\''; + if ($parent_file_id!='') { + $q = $parent_file_id; + } else { + $q = $this->driveId; + } + $q = '\'' . $q . '\' in parents and trashed = false'; + $q = urlencode($q); + $url .= '&q=' . $q; + if ($this->driveId!='root') $url .= '&driveId=' . $this->driveId . '&corpora=teamDrive&includeItemsFromAllDrives=true&supportsAllDrives=true'; + + $header['Authorization'] = 'Bearer ' . $this->access_token; + + $res = curl('GET', $url, '', $header); + if ($res['stat']==200) return json_decode($res['body'], true); + else return $res; + } + protected function permission($op, $fileId) + { + $url = $this->api_url . '/files/' . $fileId . '/permissions'; + if ($op=='create') { + $method = 'POST'; + $header['Content-Type'] = 'application/json'; + $tmp['role'] = 'reader'; + $tmp['type'] = 'anyone'; + $data = json_encode($tmp); + } elseif ($op=='delete') { + $url .= '/anyoneWithLink'; + $method = 'DELETE'; + $data = ''; + } else { + return false; + } + $url .= '?supportsAllDrives=true'; + $header['Authorization'] = 'Bearer ' . $this->access_token; + + $res = curl($method, $url, $data, $header); + //error_log1('Set Share' . json_encode($res, JSON_PRETTY_PRINT)); + return $res; + } + + public function Rename($file, $newname) { + $url = $this->api_url . '/files/' . $file['id'] . '?supportsAllDrives=true'; + $tmp['name'] = $newname; + $result = $this->GDAPI('PATCH', $url, json_encode($tmp)); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + } + public function Delete($file) { + $url = $this->api_url . '/files/' . $file['id'] . '?supportsAllDrives=true'; + $result = $this->GDAPI('DELETE', $url); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + } + public function Encrypt($folder, $passfilename, $pass) { + $existfile = $this->list_path($folder['path'] . '/' . $passfilename); + if (isset($existfile['name'])) { + if ($pass==='') { + // 如果为空,删除 + $this->Delete(['id'=>$existfile['id']]); + return output('Success', 200); + } else { + $result = $this->editFile($existfile['id'], $pass); + } + } else { + if (!$folder['id']) { + $res = $this->list_path($folder['path']); + //error_log1('res:' . json_encode($res)); + $folder['id'] = $res['id']; + } + if (!$folder['id']) { + $folder['id'] = $this->driveId; + } + $result = $this->createFile_c($folder['id'], $passfilename, $pass); + } + + //error_log1('2,url:' . $url .' res:' . json_encode($result)); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + } + public function Move($file, $folder) { + $nowParentId = $this->list_path($file['path'])['id']; + if (!$nowParentId) { + $nowParentId = $this->driveId; + } + if (!$folder['id']) { + $res = $this->list_path($folder['path']); + //error_log1('res:' . json_encode($res)); + $folder['id'] = $res['id']; + } + if (!$folder['id']) { + $folder['id'] = $this->driveId; + } + $url = $this->api_url . '/files/' . $file['id'] . '?removeParents=' . $nowParentId . '&addParents=' . $folder['id'] . '&supportsAllDrives=true'; + //$tmp['name'] = $newname; + $result = $this->GDAPI('PATCH', $url); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + } + public function Copy($file) { + $url = $this->api_url . '/files/' . $file['id'] . '/copy?supportsAllDrives=true'; + $namearr = splitlast($file['name'], '.'); + date_default_timezone_set('UTC'); + if ($namearr[0]!='') { + $newname = $namearr[0] . '_' . date("Ymd\_His"); + if ($namearr[1]!='') $newname .= '.' . $namearr[1]; + } else { + $newname = '.' . $namearr[1] . '_' . date("Ymd\_His"); + } + $tmp['name'] = $newname; + $result = $this->GDAPI('POST', $url, json_encode($tmp)); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + } + public function Edit($file, $content) { + $tmp = splitlast($file['path'], '/'); + $folderpath = $tmp[0]; + $filename = $tmp[1]; + $existfile = $this->list_path($file['path']); + if (isset($existfile['name'])) { + $result = $this->editFile($existfile['id'], $content); + } else { + $result = $this->createFile_c($this->list_path($folderpath)['id'], $filename, $content); + } + //error_log1('edit: ' . json_encode($result, JSON_PRETTY_PRINT)); + if ($result['stat']==200) return output('success', 0); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + } + public function Create($parent, $type, $name, $content = '') { + $filename = spurlencode($name); + $filename = path_format($parent['path'] . '/' . $filename); + $res = $this->list_path($filename); + //error_log1($filename . '查重:' . json_encode($res, JSON_PRETTY_PRINT) . PHP_EOL); + if (isset($res['name'])) { + $tmp['error']['code'] = 'File exist'; + $tmp['error']['message'] = $res; + $tmp['error']['stat'] = 409; + return output(json_encode($this->files_format($tmp), JSON_PRETTY_PRINT), $tmp['error']['stat']); + } + if (!$parent['id']) { + $res = $this->list_path($parent['path']); + //error_log1('找ID:' . json_encode($res)); + $parent['id'] = $res['id']; + } + if (!$parent['id']) { + $parent['id'] = $this->driveId; + } + + if ($type=='file') { + $result = $this->createFile_c($parent['id'], $name, $content); + } + if ($type=='folder') { + $result = $this->createFolder($parent['id'], $name); + } + //error_log1('data:' . $data . ' res:' . json_encode($result, JSON_PRETTY_PRINT)); + //savecache('path_' . $path1, json_decode('{}',true), $_SERVER['disktag'], 1); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + } + public function get_thumbnails_url($path = '/') { + $res = $this->list_path($path); + $thumb_url = $res['thumbnailLink']; + return $thumb_url; + } + public function bigfileupload($path) { + return output('Stop!\nCan not upload form explorer without token.', 403); + + // https://developers.google.com/drive/api/v3/manage-uploads#http---multiple-requests + + if ($_POST['upbigfilename']=='') return output('error: no file name', 400); + if (!is_numeric($_POST['filesize'])) return output('error: no file size', 400); + if (!$_SERVER['admin']) if (!isset($_POST['filemd5'])) return output('error: no file md5', 400); + $filename = $_POST['upbigfilename']; + $filename = path_format($path . '/' . $filename); + $res = $this->list_path($filename); + //error_log1($filename . '查重:' . json_encode($res, JSON_PRETTY_PRINT) . PHP_EOL); + if (isset($res['name'])) { + $tmp['error']['code'] = 'File exist'; + $tmp['error']['message'] = json_encode($res); + $tmp['error']['stat'] = 409; + return output(json_encode($this->files_format($tmp), JSON_PRETTY_PRINT), $tmp['error']['stat']); + } + $tmp = splitlast($_POST['upbigfilename'], '/'); + if ($tmp[1]!='') { + $fileinfo['name'] = $tmp[1]; + if ($_SERVER['admin']) $fileinfo['path'] = $tmp[0]; + } else { + $fileinfo['name'] = $_POST['upbigfilename']; + } + $fileinfo['size'] = $_POST['filesize']; + $fileinfo['filelastModified'] = $_POST['filelastModified']; + if ($_SERVER['admin']) { + $filename = $fileinfo['name']; + } else { + $tmp1 = splitlast($fileinfo['name'], '.'); + if ($tmp1[0]==''||$tmp1[1]=='') $filename = $_POST['filemd5']; + else $filename = $_POST['filemd5'] . '.' . $tmp1[1]; + } + $parent = $this->list_path($path . '/' . $fileinfo['path']); + if (isset($parent['id'])) { + $parent_file_id = $parent['id']; + } else { + $res = $this->createFolder($this->list_path($path)['id'], $fileinfo['path']); + //error_log1($res['body']); + $parent_file_id = json_decode($res['body'], true)['id']; + } + $url = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable'; + $res = $this->list_path($path); + //error_log1('找ID:' . json_encode($res)); + $parentId = $res['id']; + if (!$parentId) { + $parentId = $this->driveId; + } + $tmp['name'] = $_POST['upbigfilename']; + $tmp['parents'][0] = $parentId; + + $header['Authorization'] = 'Bearer ' . $this->access_token; + $header['Content-Type'] = 'application/json; charset=UTF-8'; + //$header['Content-Length'] = ''; + //$header['X-Upload-Content-Type'] = ''; + //$header['X-Upload-Content-Length'] = $_POST['filesize']; + + $response = curl('POST', $url, json_encode($tmp), $header, 1); + return output($response['returnhead']['Location'], $response['stat']); + } + + protected function editFile($id, $content) { + $url = 'https://www.googleapis.com/upload/drive/v3/files/' . $id . '?uploadType=multipart&supportsAllDrives=true'; + + $boundary = md5($id . date()); + $header['Content-Type'] = 'multipart/related; boundary=' . $boundary; + $header['Authorization'] = 'Bearer ' . $this->access_token; + $data = '--' . $boundary . "\r\n"; + $data .= 'Content-Type: application/json; charset=UTF-8' . "\r\n"; + $data .= "\r\n"; + $data .= "\r\n"; + $data .= "\r\n"; + $data .= '--' . $boundary . "\r\n"; + $data .= 'Content-Type: text/plain' . "\r\n"; + $data .= "\r\n"; + $data .= $content . "\r\n"; + $data .= '--' . $boundary . "--"; + + $result = curl('PATCH', $url, $data, $header); + //error_log1('url: ' . $url . ' data: ' . $data . ' result: ' . json_encode($result, JSON_PRETTY_PRINT)); + return $result; + } + protected function createFile_c($parentId, $name, $content) { + while (substr($name, 0, 1)=='/') $name = substr($name, 1); + while (substr($name, -1)=='/') $name = substr($name, 0, -1); + if (strpos($name, '/')>0) { + $p = splitlast($name, '/'); + $res = $this->createFolder($parentId, $p[0]); + $parentId = json_decode($res['body'], true)['id']; + $name = $p[1]; + } + + $url = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true'; + $tmp['name'] = $name; + $tmp['parents'][0] = $parentId; + + $boundary = md5($name . date()); + $header['Content-Type'] = 'multipart/related; boundary=' . $boundary; + $header['Authorization'] = 'Bearer ' . $this->access_token; + $data = '--' . $boundary . "\r\n"; + $data .= 'Content-Type: application/json; charset=UTF-8' . "\r\n"; + $data .= "\r\n"; + $data .= json_encode($tmp, JSON_PRETTY_PRINT) . "\r\n"; + $data .= "\r\n"; + $data .= '--' . $boundary . "\r\n"; + $data .= 'Content-Type: text/plain' . "\r\n"; + $data .= "\r\n"; + $data .= $content . "\r\n"; + $data .= '--' . $boundary . "--"; + + $result = curl('POST', $url, $data, $header); + return $result; + } + protected function createFolder($parentId, $name) { + while (substr($name, 0, 1)=='/') $name = substr($name, 1); + while (substr($name, -1)=='/') $name = substr($name, 0, -1); + if (strpos($name, '/')>0) { + $p = splitlast($name, '/'); + $res = $this->createFolder($parentId, $p[0]); + $parentId = json_decode($res['body'], true)['id']; + $name = $p[1]; + } + + $url = $this->api_url . '/files?&supportsAllDrives=true'; + + $tmp['name'] = $name; + $tmp['parents'][0] = $parentId; + $tmp['mimeType'] = 'application/vnd.google-apps.folder'; + $data = json_encode($tmp); + + $header['Content-Type'] = 'application/json; charset=UTF-8'; + $header['Authorization'] = 'Bearer ' . $this->access_token; + + $result = curl('POST', $url, $data, $header); + return $result; + } + + public function AddDisk() { + global $constStr; + global $EnvConfigs; + + $envs = ''; + foreach ($EnvConfigs as $env => $v) if (isCommonEnv($env)) $envs .= '\'' . $env . '\', '; + $url = path_format($_SERVER['PHP_SELF'] . '/'); + + if (isset($_GET['Finish'])) { + if ($this->access_token == '') { + $refresh_token = getConfig('refresh_token', $this->disktag); + if (!$refresh_token) { + $html = 'No refresh_token config, please AddDisk again or wait minutes.
' . $this->disktag; + $title = 'Error'; + return message($html, $title, 201); + } + $response = $this->get_access_token($refresh_token); + if (!$response) return message($this->error['body'], 'Error', $this->error['stat']); + } + + $tmp = null; + if ($_POST['DriveType']=='Googledrive') { + $tmp['driveId'] = 'root'; + } else { + // 直接是id + $tmp['driveId'] = $_POST['DriveType']; + } + + $response = setConfigResponse( setConfig($tmp, $this->disktag) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + $str .= ''; + return message($str, getconstStr('WaitJumpIndex'), 201); + } + } + + if (isset($_GET['SelectDrive'])) { + if ($this->access_token == '') { + $refresh_token = getConfig('refresh_token', $this->disktag); + if (!$refresh_token) { + $html = 'No refresh_token config, please AddDisk again or wait minutes.
' . $this->disktag; + $title = 'Error'; + return message($html, $title, 201); + } + $response = $this->get_access_token($refresh_token); + if (!$response) return message($this->error['body'], 'Error', $this->error['stat']); + } + + $api = $this->api_url . '/drives'; + $arr = curl('GET', $api, '', [ 'Authorization' => 'Bearer ' . $this->access_token ]); + //if (!($arr['stat']==200||$arr['stat']==403||$arr['stat']==400||$arr['stat']==404)) + if ($arr['stat']!=200) return message($arr['stat'] . json_encode(json_decode($arr['body']), JSON_PRETTY_PRINT), 'Get followedSites', $arr['stat']); + error_log1($arr['body']); + $drives = json_decode($arr['body'], true)['drives']; + + $title = 'Select Driver'; + $html = ' +
+
+
'; + if ($drives[0]!='') foreach ($drives as $k => $v) { + $html .= ' + '; + } + $html .= ' + +
+
+ + '; + return message($html, $title, 201); + } + + if (isset($_GET['install2']) && isset($_GET['code'])) { + $data['client_id'] = $this->client_id; + $data['client_secret'] = $this->client_secret; + $data['grant_type'] = 'authorization_code'; + $data['redirect_uri'] = $this->redirect_uri; + $data['code'] = $_GET['code']; + $api = $this->oauth_url . 'token'; + //$api = 'https://www.googleapis.com/oauth2/v4/token'; + $tmp = curl('POST', + $api, + json_encode($data) + ); + if ($tmp['stat']==200) $ret = json_decode($tmp['body'], true); + if (isset($ret['refresh_token'])) { + $refresh_token = $ret['refresh_token']; + $str = ' + refresh_token :
'; + $str .= ' +

+ ' . getconstStr('SavingToken') . ' + '; + $tmptoken['refresh_token'] = $refresh_token; + //$tmptoken['token_expires'] = time()+7*24*60*60; + $response = setConfigResponse( setConfig($tmptoken, $this->disktag) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + savecache('access_token', $ret['access_token'], $this->disktag, $ret['expires_in'] - 60); + $str .= ' + '; + return message($str, getconstStr('Wait') . ' 3s', 201); + } + } + return message('
' . $tmp['body'] . '
', $tmp['stat']); + //return message('
' . json_encode($ret, JSON_PRETTY_PRINT) . '
', 500); + } + + if (isset($_GET['install1'])) { + if (get_class($this)=='Googledrive') { + return message(' + ' . getconstStr('JumptoOffice') . ' + + ', getconstStr('Wait') . ' 1s', 201); + } else { + return message('Something error, retry after a few seconds.', 'Retry', 201); + } + } + + if (isset($_GET['install0'])) { + if ($_POST['disktag_add']!='') { + $_POST['disktag_add'] = preg_replace('/[^0-9a-zA-Z|_]/i', '', $_POST['disktag_add']); + $f = substr($_POST['disktag_add'], 0, 1); + if (strlen($_POST['disktag_add'])==1) $_POST['disktag_add'] .= '_'; + if (isCommonEnv($_POST['disktag_add'])) { + return message('Do not input ' . $envs . '
', 'Error', 201); + } elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) { + return message('Please start with letters
+ ', 'Error', 201); + } + + $tmp = null; + // clear envs + foreach ($EnvConfigs as $env => $v) if (isInnerEnv($env)) $tmp[$env] = ''; + + //$this->disktag = $_POST['disktag_add']; + $tmp['disktag_add'] = $_POST['disktag_add']; + $tmp['diskname'] = $_POST['diskname']; + $tmp['Driver'] = 'Googledrive'; + + if ($_POST['NT_Drive_custom']=='on') { + $tmp['client_id'] = $_POST['NT_client_id']; + $tmp['client_secret'] = $_POST['NT_client_secret']; + } + + $response = setConfigResponse( setConfig($tmp, $this->disktag) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + } else { + $title = getconstStr('MayinEnv'); + $html = getconstStr('Wait') . ' 3s'; + } + return message($html, $title, 201); + } + } + + $html = ' +
+
+ ' . getconstStr('DiskTag') . ': (' . getConfig('disktag') . ') +
+ ' . getconstStr('DiskName') . ': +
+
+
+
+ +
+
'; + if ($_SERVER['language']=='zh-cn') $html .= '你要理解 scfonedrive.github.io 是github上的静态网站,
除非github真的挂掉了,
不然,稍后你如果连不上,请检查你的运营商或其它“你懂的”问题!
'; + $html .=' + +
+
+ '; + $title = 'Select Account Type'; + return message($html, $title, 201); + } + + protected function get_access_token($refresh_token) { + if (!$refresh_token) { + $tmp['stat'] = 0; + $tmp['body'] = 'No refresh_token'; + $this->error = $tmp; + return false; + } + if (!($this->access_token = getcache('access_token', $this->disktag))) { + $p=0; + $data['client_id'] = $this->client_id; + $data['client_secret'] = $this->client_secret; + $data['grant_type'] = 'refresh_token'; + //$data['redirect_uri'] = $this->redirect_uri; + $data['refresh_token'] = $refresh_token; + while ($response['stat']==0&&$p<3) { + //$response = curl('POST', 'https://www.googleapis.com/oauth2/v4/token', json_encode($data)); + $response = curl('POST', $this->oauth_url . 'token', json_encode($data)); + $p++; + } + if ($response['stat']==200) $ret = json_decode($response['body'], true); + if (!isset($ret['access_token'])) { + error_log1($this->oauth_url . 'token' . '?client_id=' . $this->client_id . '&client_secret=' . $this->client_secret . '&grant_type=refresh_token&refresh_token=' . substr($refresh_token, 0, 20) . '******' . substr($refresh_token, -20)); + error_log1('failed to get [' . $this->disktag . '] access_token. response: ' . $response['body']); + $response['body'] = json_encode(json_decode($response['body']), JSON_PRETTY_PRINT); + $response['body'] .= '\nfailed to get [' . $this->disktag . '] access_token.'; + $this->error = $response; + return false; + //throw new Exception($response['stat'].', failed to get ['.$this->disktag.'] access_token.'.$response['body']); + } + $tmp = $ret; + $tmp['access_token'] = substr($tmp['access_token'], 0, 10) . '******'; + //$tmp['refresh_token'] = substr($tmp['refresh_token'], 0, 10) . '******'; + error_log1('[' . $this->disktag . '] Get access token:' . json_encode($tmp, JSON_PRETTY_PRINT)); + $this->access_token = $ret['access_token']; + savecache('access_token', $this->access_token, $this->disktag, $ret['expires_in'] - 300); + //if (time()>getConfig('token_expires', $this->disktag)) setConfig([ 'refresh_token' => $ret['refresh_token'], 'token_expires' => time()+7*24*60*60 ], $this->disktag); + return true; + } + return true; + } + public function getDiskSpace() { + if ($this->driveId!='root') return '0 / 0'; + if (!($diskSpace = getcache('diskSpace', $this->disktag))) { + $url = $this->api_url . '/about?fields=storageQuota'; + $response = $this->GDAPI('GET', $url); + if ($response['stat']==200) { + $res = json_decode($response['body'], true)['storageQuota']; + $used = size_format($res['usage']); + $total = size_format($res['limit']); + $diskSpace = $used . ' / ' . $total; + savecache('diskSpace', $diskSpace, $this->disktag); + } else return json_encode($response); + } + return $diskSpace; + } + + protected function GDAPI($method, $url, $data = '') + { + /*if (substr($path,0,7) == 'http://' or substr($path,0,8) == 'https://') { + $url = $path; + } else { + $url = $this->api_url; + if ($path=='' or $path=='/') { + $url .= '/'; + } else { + $url .= ':' . $path; + if (substr($url,-1)=='/') $url=substr($url,0,-1); + } + if ($method=='PUT') { + if ($path=='' or $path=='/') { + $url .= 'content'; + } else { + $url .= ':/content'; + } + $headers['Content-Type'] = 'text/plain'; + } elseif ($method=='PATCH') { + $headers['Content-Type'] = 'application/json'; + } elseif ($method=='POST') { + $headers['Content-Type'] = 'application/json'; + } elseif ($method=='DELETE') { + $headers['Content-Type'] = 'application/json'; + } else { + if ($path=='' or $path=='/') { + $url .= $method; + } else { + $url .= ':/' . $method; + } + $method='POST'; + $headers['Content-Type'] = 'application/json'; + } + }*/ + $headers['Authorization'] = 'Bearer ' . $this->access_token; + if (!isset($headers['Accept'])) $headers['Accept'] = '*/*'; + $headers['Content-Type'] = 'application/json'; + //if (!isset($headers['Referer'])) $headers['Referer'] = $url;* + $sendHeaders = array(); + foreach ($headers as $headerName => $headerVal) { + $sendHeaders[] = $headerName . ': ' . $headerVal; + } + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_TIMEOUT, 5); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders); + $response['body'] = curl_exec($ch); + $response['stat'] = curl_getinfo($ch, CURLINFO_HTTP_CODE); + //$response['Location'] = curl_getinfo($ch); + curl_close($ch); + /*error_log1($response['stat'].' + ' . $response['body'].' + ' . $url.' + ' . $data);*/ + return $response; + } + +} diff --git a/disk/Onedrive.php b/disk/Onedrive.php new file mode 100644 index 0000000..52df104 --- /dev/null +++ b/disk/Onedrive.php @@ -0,0 +1,1141 @@ +disktag = $tag; + $this->redirect_uri = 'https://scfonedrive.github.io'; + if (getConfig('client_id', $tag) && getConfig('client_secret', $tag)) { + $this->client_id = getConfig('client_id', $tag); + $this->client_secret = getConfig('client_secret', $tag); + } else { + $this->client_id = '734ef928-d74c-4555-8d1b-d942fa0a1a41'; + $this->client_secret = '_I5gOpmG5vTC2Ts_K._wCW4nN1km~4Pk52'; + } + $this->oauth_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/'; + $this->api_url = 'https://graph.microsoft.com/v1.0'; + $this->scope = 'https://graph.microsoft.com/Files.ReadWrite.All https://graph.microsoft.com/Sites.ReadWrite.All offline_access'; + $this->client_secret = urlencode($this->client_secret); + $this->scope = urlencode($this->scope); + $this->DownurlStrName = '@microsoft.graph.downloadUrl'; + $this->ext_api_url = '/me/drive/root'; + $res = $this->get_access_token(getConfig('refresh_token', $tag)); + } + + public function isfine() + { + if (!$this->access_token) return false; + else return true; + } + public function show_base_class() + { + return get_class(); + //$tmp[0] = get_class(); + //$tmp[1] = get_class($this); + //return $tmp; + } + + public function ext_show_innerenv() + { + return []; + } + + public function list_files($path = '/') + { + global $exts; + if (!($files = getcache('path_' . $path, $this->disktag))) { + $pos = splitlast($path, '/'); + $parentpath = $pos[0]; + if ($parentpath=='') $parentpath = '/'; + $filename = strtolower($pos[1]); + if ($parentfiles = getcache('path_' . $parentpath, $this->disktag)) { + if (isset($parentfiles['children'][$filename][$this->DownurlStrName])) { + if (in_array(splitlast($filename,'.')[1], $exts['txt'])) { + if (!(isset($parentfiles['children'][$filename]['content'])&&$parentfiles['children'][$filename]['content']['stat']==200)) { + //$content1 = curl('GET', $parentfiles['children'][$filename][$this->DownurlStrName]); + //$parentfiles['children'][$filename]['content'] = $content1; + //savecache('path_' . $parentpath, $parentfiles, $this->disktag); + if ($parentfiles['children'][$filename]['size']<1024*1024) { + if (!(isset($parentfiles['children'][$filename]['content'])&&$parentfiles['children'][$filename]['content']['stat']==200)) { + $content1 = curl('GET', $parentfiles['children'][$filename][$this->DownurlStrName]); + $tmp = null; + $tmp = json_decode(json_encode($content1), true); + if ($tmp['body']===null) { + $txtcode = chkTxtCode($content1['body']); + if ($txtcode!==false) $tmp['body'] = iconv($txtcode, 'UTF-8//TRANSLIT', $content1['body']); + $tmp = json_decode(json_encode($tmp), true); + if ($tmp['body']) $content1['body'] = $tmp['body']; + } + $parentfiles['children'][$filename]['content'] = $content1; + savecache('path_' . $path, $parentfiles['children'][$filename], $this->disktag); + } + } else { + $parentfiles['children'][$filename]['content']['stat'] = 202; + $parentfiles['children'][$filename]['content']['body'] = 'File too large.'; + } + } + } + return $this->files_format($parentfiles['children'][$filename]); + } + } + + $url = $this->api_url . $this->ext_api_url; + if ($path !== '/') { + $url .= ':' . $path; + if (substr($url,-1)=='/') $url=substr($url,0,-1); + } + $url .= '?expand=children(select=id,name,size,file,folder,parentReference,lastModifiedDateTime,'.$this->DownurlStrName.')'; + $arr = $this->MSAPI('GET', $url); + //echo $url . '
' . json_encode($arr, JSON_PRETTY_PRINT) . '
'; + if ($arr['stat']<500) { + $files = json_decode($arr['body'], true); + //echo '
' . json_encode($files, JSON_PRETTY_PRINT) . '
'; + if (isset($files['folder'])) { + if ($files['folder']['childCount']>200) { + // files num > 200 , then get nextlink + $page = $_POST['pagenum']==''?1:$_POST['pagenum']; + if ($page>1) + //if (!($files = getcache('path_1' . $path . '_' . $page, $this->disktag))) + { + $children = $this->fetch_files_children($path, $page); + //echo '
' . json_encode($children, JSON_PRETTY_PRINT) . '
'; + $files['children'] = $children['value']; + //$files['children'] = children_name($files['children']); + $files['folder']['page'] = $page; + //savecache('path_' . $path . '_' . $page, $files, $this->disktag); + } + } else { + // files num < 200 , then cache + if (isset($files['children'])) { + $files['children'] = children_name($files['children']); + } + savecache('path_' . $path, $files, $this->disktag); + } + } + if (isset($files['file'])) { + if (in_array(strtolower(splitlast($files['name'],'.')[1]), $exts['txt'])) { + if ($files['size']<1024*1024) { + if (!(isset($files['content'])&&$files['content']['stat']==200)) { + $content1 = curl('GET', $files[$this->DownurlStrName]); + $tmp = null; + $tmp = json_decode(json_encode($content1), true); + if ($tmp['body']===null) { + $txtcode = chkTxtCode($content1['body']); + if ($txtcode!==false) $tmp['body'] = iconv($txtcode, 'UTF-8//TRANSLIT', $content1['body']); + $tmp = json_decode(json_encode($tmp), true); + if ($tmp['body']) $content1['body'] = $tmp['body']; + } + $files['content'] = $content1; + savecache('path_' . $path, $files, $this->disktag); + } + } else { + $files['content']['stat'] = 202; + $files['content']['body'] = 'File too large.'; + } + } + } + if (isset($files['error'])) { + $files['error']['stat'] = $arr['stat']; + } + } else { + //error_log1($arr['body']); + $files = json_decode($arr['body'], true); + if (isset($files['error'])) { + $files['error']['stat'] = $arr['stat']; + } else { + $files['error']['stat'] = 503; + $files['error']['code'] = 'unknownError'; + $files['error']['message'] = 'unknownError ' . $arr['body'] . " ~"; + } + //$files = json_decode( '{"unknownError":{ "stat":'.$arr['stat'].',"message":"'.$arr['body'].'"}}', true); + //error_log1(json_encode($files, JSON_PRETTY_PRINT)); + } + } + //echo '
' . json_encode($files, JSON_PRETTY_PRINT) . '
'; + return $this->files_format($files); + } + + protected function files_format($files) + { + if (isset($files['file'])) { + $tmp['type'] = 'file'; + $tmp['id'] = $files['id']; + $tmp['name'] = $files['name']; + $tmp['time'] = $files['lastModifiedDateTime']; + $tmp['size'] = $files['size']; + $tmp['mime'] = $files['file']['mimeType']; + $tmp['url'] = $files[$this->DownurlStrName]; + $tmp['content'] = $files['content']; + } elseif (isset($files['folder'])) { + $tmp['type'] = 'folder'; + $tmp['id'] = $files['id']; + $tmp['name'] = $files['name']; + $tmp['time'] = $files['lastModifiedDateTime']; + $tmp['size'] = $files['size']; + $tmp['childcount'] = $files['folder']['childCount']; + $tmp['page'] = $files['folder']['page']; + foreach ($files['children'] as $file) { + $filename = strtolower($file['name']); + if (isset($file['file'])) { + $tmp['list'][$filename]['type'] = 'file'; + //var_dump($file); + //echo $file['name'] . ':' . $this->DownurlStrName . ':' . $file[$this->DownurlStrName] . PHP_EOL; + $tmp['list'][$filename]['url'] = $file[$this->DownurlStrName]; + $tmp['list'][$filename]['mime'] = $file['file']['mimeType']; + } elseif (isset($file['folder'])) { + $tmp['list'][$filename]['type'] = 'folder'; + } + $tmp['list'][$filename]['id'] = $file['id']; + $tmp['list'][$filename]['name'] = $file['name']; + $tmp['list'][$filename]['time'] = $file['lastModifiedDateTime']; + $tmp['list'][$filename]['size'] = $file['size']; + } + } elseif (isset($files['error'])) { + return $files; + } + //error_log1(json_encode($tmp)); + //echo '
' . json_encode($tmp, JSON_PRETTY_PRINT) . '
'; + return $tmp; + } + + protected function fetch_files_children($path, $page, $getNextlink = false) { + $children = getcache('files_' . $path . '_page_' . $page, $this->disktag); + if (!$children) { + $url = $this->api_url . $this->ext_api_url; + if ($path !== '/') { + $url .= ':' . $path; + if (substr($url,-1)=='/') $url=substr($url,0,-1); + $url .= ':'; + } + $url .= '/children?$top=' . ($page-1)*200 . '&$select=id,name,size,file,folder,parentReference,lastModifiedDateTime,' . $this->DownurlStrName; + $children_tmp = json_decode($this->MSAPI('GET', $url)['body'], true); + //echo $url . '
' . json_encode($children_tmp, JSON_PRETTY_PRINT) . '
'; + $p = 1; + $i = 0; + foreach ($children_tmp['value'] as $child) { + $i++; + $value_name = 'child_' . $p; + ${$value_name}['value'][] = $child; + if ($i==200) { + savecache('files_' . $path . '_page_' . $p, ${$value_name}, $this->disktag); + unset(${$value_name}); + $i = 0; + $p++; + } + } + + $url = $children_tmp['@odata.nextLink']; + $children_tmp = json_decode($this->MSAPI('GET', $url)['body'], true); + //echo $url . '
' . json_encode($children_tmp, JSON_PRETTY_PRINT) . '
'; + $p = $page; + $i = 0; + foreach ($children_tmp['value'] as $child) { + $i++; + $value_name = 'child_' . $p; + ${$value_name}['value'][] = $child; + if ($i==200) { + savecache('files_' . $path . '_page_' . $p, ${$value_name}, $this->disktag); + //unset(${$value_name}); + $i = 0; + $p++; + } + } + if ($i!=0) savecache('files_' . $path . '_page_' . $p, ${$value_name}, $this->disktag); + $value_name = 'child_' . $page; + return ${$value_name}; + } + return $children; + + /*if ($getNextlink) { + if (isset($children['@odata.nextLink'])) { + return $children; + } else { + if ($page*200>9800) { + $children_tmp = fetch_files_children($path, floor($page/49)*49, 1); + $url = $children_tmp['@odata.nextLink']; + $children = json_decode(curl('GET', $url, false, ['Authorization' => 'Bearer ' . $this->access_token])['body'], true); + } + } + }*/ + } + protected function fetch_files_children1($files, $path, $page) + { + $maxpage = ceil($files['folder']['childCount']/200); + if (!($children = getcache('files_' . $path . '_page_' . $page, $this->disktag))) { + $pageinfochange=0; + for ($page1=$page;$page1>=1;$page1--) { + $page3=$page1-1; + $url = getcache('nextlink_' . $path . '_page_' . $page3, $this->disktag); + if ($url == '') { + if ($page1==1) { + $url = $this->api_url . $this->ext_api_url; + if ($path !== '/') { + $url .= ':' . $path; + if (substr($url,-1)=='/') $url=substr($url,0,-1); + $url .= ':'; + } + $url .= '/children?$select=id,name,size,file,folder,parentReference,lastModifiedDateTime,'.$this->DownurlStrName; + $children = json_decode($this->MSAPI('GET', $url)['body'], true); + // echo $url . '
' . json_encode($children, JSON_PRETTY_PRINT) . '
'; + savecache('files_' . $path . '_page_' . $page1, $children, $this->disktag); + $nextlink=getcache('nextlink_' . $path . '_page_' . $page1, $this->disktag); + if ($nextlink!=$children['@odata.nextLink']) { + savecache('nextlink_' . $path . '_page_' . $page1, $children['@odata.nextLink'], $this->disktag); + $pageinfocache['nextlink_' . $path . '_page_' . $page1] = $children['@odata.nextLink']; + $pageinfocache = clearbehindvalue($path,$page1,$maxpage,$pageinfocache); + $pageinfochange = 1; + } + $url = $children['@odata.nextLink']; + for ($page2=$page1+1;$page2<=$page;$page2++) { + sleep(1); + $children = json_decode($this->MSAPI('GET', $url)['body'], true); + savecache('files_' . $path . '_page_' . $page2, $children, $this->disktag); + $nextlink=getcache('nextlink_' . $path . '_page_' . $page2, $this->disktag); + if ($nextlink!=$children['@odata.nextLink']) { + savecache('nextlink_' . $path . '_page_' . $page2, $children['@odata.nextLink'], $this->disktag); + $pageinfocache['nextlink_' . $path . '_page_' . $page2] = $children['@odata.nextLink']; + $pageinfocache = clearbehindvalue($path,$page2,$maxpage,$pageinfocache); + $pageinfochange = 1; + } + $url = $children['@odata.nextLink']; + } + //echo $url . '
' . json_encode($children, JSON_PRETTY_PRINT) . '
'; + return $children; + /* + $files['children'] = $children['value']; + $files['folder']['page']=$page; + $pageinfocache['filenum'] = $files['folder']['childCount']; + $pageinfocache['dirsize'] = $files['size']; + $pageinfocache['cachesize'] = $cachefile['size']; + $pageinfocache['size'] = $files['size']-$cachefile['size']; + if ($pageinfochange == 1) $this->MSAPI('PUT', path_format($path.'/'.$cachefilename), json_encode($pageinfocache, JSON_PRETTY_PRINT))['body']; + return $files;*/ + } + } else { + for ($page2=$page3+1;$page2<=$page;$page2++) { + sleep(1); + $children = json_decode($this->MSAPI('GET', $url)['body'], true); + savecache('files_' . $path . '_page_' . $page2, $children, $this->disktag, 3300); + $nextlink=getcache('nextlink_' . $path . '_page_' . $page2, $this->disktag); + if ($nextlink!=$children['@odata.nextLink']) { + savecache('nextlink_' . $path . '_page_' . $page2, $children['@odata.nextLink'], $this->disktag, 3300); + $pageinfocache['nextlink_' . $path . '_page_' . $page2] = $children['@odata.nextLink']; + $pageinfocache = clearbehindvalue($path,$page2,$maxpage,$pageinfocache); + $pageinfochange = 1; + } + $url = $children['@odata.nextLink']; + } + //echo $url . '
' . json_encode($children, JSON_PRETTY_PRINT) . '
'; + return $children; + + /*$files['children'] = $children['value']; + $files['folder']['page']=$page; + $pageinfocache['filenum'] = $files['folder']['childCount']; + $pageinfocache['dirsize'] = $files['size']; + $pageinfocache['cachesize'] = $cachefile['size']; + $pageinfocache['size'] = $files['size']-$cachefile['size']; + if ($pageinfochange == 1) $this->MSAPI('PUT', path_format($path.'/'.$cachefilename), json_encode($pageinfocache, JSON_PRETTY_PRINT))['body']; + return $files;*/ + } + } + }/* else { + $files['folder']['page']=$page; + for ($page4=1;$page4<=$maxpage;$page4++) { + if (!($url = getcache('nextlink_' . $path . '_page_' . $page4, $this->disktag))) { + if ($files['folder'][$path.'_'.$page4]!='') savecache('nextlink_' . $path . '_page_' . $page4, $files['folder'][$path.'_'.$page4], $this->disktag); + } else { + $files['folder'][$path.'_'.$page4] = $url; + } + } + }*/ + return $children; + //return $files; + } + + public function Rename($file, $newname) { + $oldname = spurlencode($file['name']); + $oldname = path_format($file['path'] . '/' . $oldname); + $data = '{"name":"' . $newname . '"}'; + //echo $oldname; + if ($file['id']) $result = $this->MSAPI('PATCH', "/items/" . $file['id'], $data); + else $result = $this->MSAPI('PATCH', $oldname, $data); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + } + public function Delete($file) { + $filename = spurlencode($file['name']); + $filename = path_format($file['path'] . '/' . $filename); + //echo $filename; + if ($file['id']) $result = $this->MSAPI('DELETE', "/items/" . $file['id']); + else $result = $this->MSAPI('DELETE', $filename); + if ($result['stat']!=204) $r_body = json_encode($this->files_format(json_decode($result['body'], true))); + return output($r_body, $result['stat']); + //return output($result['body'], $result['stat']); + } + public function Encrypt($folder, $passfilename, $pass) { + $filename = '/items/' . $folder['id'] . ':/' . urlencode($passfilename); + if ($pass==='') { + $result = $this->MSAPI('DELETE', $filename); + } else { + $result = $this->MSAPI('PUT', $filename, $pass); + } + $path1 = $folder['path']; + if ($path1!='/'&&substr($path1, -1)=='/') $path1 = substr($path1, 0, -1); + savecache('path_' . $path1 . '/?password', '', $this->disktag, 1); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + //return output($result['body'], $result['stat']); + } + public function Move($file, $folder) { + $filename = spurlencode($file['name']); + $filename = path_format($file['path'] . '/' . $filename); + $data = '{"parentReference":{"path": "/drive/root:' . $folder['path'] . '"}}'; + if ($file['id']) $result = $this->MSAPI('PATCH', "/items/" . $file['id'], $data); + else $result = $this->MSAPI('PATCH', $filename, $data); + $path2 = spurlencode($folder['path'], '/'); + if ($path2!='/'&&substr($path2, -1)=='/') $path2 = substr($path2, 0, -1); + savecache('path_' . $path2, json_decode('{}', true), $this->disktag, 1); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + //return output($result['body'], $result['stat']); + } + public function Copy($file) { + $filename = spurlencode($file['name']); + $filename = path_format($file['path'] . '/' . $filename); + $namearr = splitlast($file['name'], '.'); + date_default_timezone_set('UTC'); + if ($namearr[0]!='') { + $newname = $namearr[0] . ' (' . date("Ymd\THis\Z") . ')'; + if ($namearr[1]!='') $newname .= '.' . $namearr[1]; + } else { + $newname = '.' . $namearr[1] . ' (' . date("Ymd\THis\Z") . ')'; + } + $data = '{ "name": "' . $newname . '" }'; + if ($file['id']) $result = $this->MSAPI('copy', "/items/" . $file['id'], $data); + else $result = $this->MSAPI('copy', $filename, $data); + /*$num = 0; + while ($result['stat']==409 && json_decode($result['body'], true)['error']['code']=='nameAlreadyExists') { + $num++; + if ($namearr[0]!='') { + $newname = $namearr[0] . ' (' . getconstStr('Copy') . ' ' . $num . ')'; + if ($namearr[1]!='') $newname .= '.' . $namearr[1]; + } else { + $newname = '.' . $namearr[1] . ' ('.getconstStr('Copy'). ' ' . $num .')'; + } + //$newname = spurlencode($newname); + $data = '{ "name": "' . $newname . '" }'; + $result = $this->MSAPI('copy', $filename, $data); + }*/ + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + //return output($result['body'], $result['stat']); + } + public function Edit($file, $content) { + /*TXT一般不会超过4M,不用二段上传 + $filename = $path1 . ':/createUploadSession'; + $response=MSAPI('POST',$filename,'{"item": { "@microsoft.graph.conflictBehavior": "replace" }}',$_SERVER['access_token']); + $uploadurl=json_decode($response,true)['uploadUrl']; + echo MSAPI('PUT',$uploadurl,$data,$_SERVER['access_token']);*/ + $result = $this->MSAPI('PUT', $file['path'], $content); + //return output($result['body'], $result['stat']); + //echo $result; + $resultarry = json_decode($result['body'],true); + if (isset($resultarry['error'])) return message($resultarry['error']['message']. '
'.getconstStr('Back').'','Error', 403); + else return output('success', 0); + } + public function Create($parent, $type, $name, $content = '') { + if ($type=='file') { + $filename = spurlencode($name); + $filename = path_format($parent['path'] . '/' . $filename); + $result = $this->MSAPI('PUT', $filename, $content); + } + if ($type=='folder') { + $data = '{ "name": "' . $name . '", "folder": { }, "@microsoft.graph.conflictBehavior": "rename" }'; + $result = $this->MSAPI('children', $parent['path'], $data); + } + //savecache('path_' . $path1, json_decode('{}',true), $_SERVER['disktag'], 1); + return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']); + //return output($result['body'], $result['stat']); + } + + public function AddDisk() { + global $constStr; + global $EnvConfigs; + + $envs = ''; + foreach ($EnvConfigs as $env => $v) if (isCommonEnv($env)) $envs .= '\'' . $env . '\', '; + $url = $_SERVER['PHP_SELF']; + //$this->api_url = splitfirst($_SERVER['api_url'], '/v1.0')[0] . '/v1.0'; + + if (isset($_GET['Finish'])) { + if ($this->access_token == '') { + $refresh_token = getConfig('refresh_token', $this->disktag); + if (!$refresh_token) { + $html = 'No refresh_token config, please AddDisk again or wait minutes.
' . $this->disktag; + $title = 'Error'; + return message($html, $title, 201); + } + $response = $this->get_access_token($refresh_token); + if (!$response) return message($this->error['body'], $this->error['stat'] . ' Error', $this->error['stat']); + } + + $tmp = null; + $tmp['Driver'] = get_class($this); + if ($_POST['DriveType']=='Onedrive') { + /*$api = $this->api_url . '/me'; + $arr = curl('GET', $api, '', [ 'Authorization' => 'Bearer ' . $this->access_token ], 1); + if ($arr['stat']==200) { + $userid = json_decode($arr['body'], true)['id']; + $api = $this->api_url . '/users/' . $userid . '/drive'; + $arr = curl('GET', $api, '', [ 'Authorization' => 'Bearer ' . $this->access_token ], 1); + if ($arr['stat']!=200) return message($arr['stat'] . '
' . $api . '
' . $arr['body'], 'Get User Drive ID', $arr['stat']); + $tmp['DriveId'] = json_decode($arr['body'], true)['id']; + } elseif ($arr['stat']==403||$arr['stat']==401) { + // 403:世纪不让列me,401:个人也不给拿 + $api = $this->api_url . '/me/drive'; + } else { + return message($arr['stat'] . $arr['body'], 'Get User ID', $arr['stat']); + }*/ + if ($tmp['Driver']=='Sharepoint') $tmp['Driver'] = 'Onedrive'; + elseif ($tmp['Driver']=='SharepointCN') $tmp['Driver'] = 'OnedriveCN'; + $tmp['sharepointSite'] = ''; + $tmp['siteid'] = ''; + } elseif ($_POST['DriveType']=='Custom') { + // sitename计算siteid + $tmp1 = $this->get_siteid($_POST['sharepointSite']); + if (isset($tmp1['stat'])) return message($arr['stat'] . $tmp1['body'], 'Get Sharepoint Site ID ' . $_POST['sharepointSite'], $tmp1['stat']); + $siteid = $tmp1; + //$api = $this->api_url . '/sites/' . $siteid . '/drive/'; + //$arr = curl('GET', $api, '', [ 'Authorization' => 'Bearer ' . $this->access_token ], 1); + //if ($arr['stat']!=200) return message($arr['stat'] . $arr['body'], 'Get Sharepoint Drive ID ' . $_POST['DriveType'], $arr['stat']); + $tmp['siteid'] = $siteid; + $tmp['sharepointSite'] = $_POST['sharepointSite']; + if ($tmp['Driver']=='Onedrive') $tmp['Driver'] = 'Sharepoint'; + elseif ($tmp['Driver']=='OnedriveCN') $tmp['Driver'] = 'SharepointCN'; + } else { + // 直接是siteid + $tmp['siteid'] = $_POST['DriveType']; + $tmp['sharepointSite'] = $_POST['sharepointSiteUrl']; + if ($tmp['Driver']=='Onedrive') $tmp['Driver'] = 'Sharepoint'; + elseif ($tmp['Driver']=='OnedriveCN') $tmp['Driver'] = 'SharepointCN'; + } + + $response = setConfigResponse( setConfig($tmp, $this->disktag) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + $html .= ''; + return message($html, getconstStr('Wait'), 201, 1); + } + } + + if (isset($_GET['SelectDrive'])) { + if (get_class($this)=='Sharelink') return message('Can not change to other.', 'Back', 201); + if ($this->access_token == '') { + $refresh_token = getConfig('refresh_token', $this->disktag); + if (!$refresh_token) { + $html = 'No refresh_token config, please AddDisk again or wait minutes.
' . $this->disktag; + $title = 'Error'; + return message($html, $title, 201); + } + $response = $this->get_access_token($refresh_token); + if (!$response) return message($this->error['body'], $this->error['stat'] . ' Error', $this->error['stat']); + } + + $api = $this->api_url . '/sites/root'; + $arr = $this->MSAPI('GET', $api); + $Tenant = json_decode($arr['body'], true)['webUrl']; + + $api = $this->api_url . '/me/followedSites'; + $arr = $this->MSAPI('GET', $api); + if (!($arr['stat']==200||$arr['stat']==403||$arr['stat']==400||$arr['stat']==404)) return message($arr['stat'] . json_encode(json_decode($arr['body']), JSON_PRETTY_PRINT), 'Get followedSites', $arr['stat']); + error_log1($arr['body']); + $sites = json_decode($arr['body'], true)['value']; + + $title = 'Select Driver'; + $html = ' +
+
+
'; + if ($sites[0]!='') foreach ($sites as $k => $v) { + $html .= ' + '; + } + $html .= ' + +
+ '; + $html .= ' + +
+
+ +'; + return message($html, $title, 201); + } + + if (isset($_GET['install2']) && isset($_GET['code'])) { + $tmp = curl('POST', $this->oauth_url . 'token', 'client_id=' . $this->client_id .'&client_secret=' . $this->client_secret . '&grant_type=authorization_code&requested_token_use=on_behalf_of&redirect_uri=' . $this->redirect_uri . '&code=' . $_GET['code']); + if ($tmp['stat']==200) $ret = json_decode($tmp['body'], true); + if (isset($ret['refresh_token'])) { + $refresh_token = $ret['refresh_token']; + $str = ' + refresh_token :
'; + $str .= ' +

+ ' . getconstStr('SavingToken') . ' + '; + $tmptoken['Driver'] = $_GET['AddDisk']; + $tmptoken['refresh_token'] = $refresh_token; + $tmptoken['token_expires'] = time()+7*24*60*60; + $response = setConfigResponse( setConfig($tmptoken, $this->disktag) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + savecache('access_token', $ret['access_token'], $this->disktag, $ret['expires_in'] - 60); + $html .= ''; + return message($html, getconstStr('Wait') . ' 3s', 201, 1); + } + } + return message('
' . json_encode(json_decode($tmp['body']), JSON_PRETTY_PRINT) . '
', $tmp['stat']); + //return message('
' . json_encode($ret, JSON_PRETTY_PRINT) . '
', 500); + } + + if (isset($_GET['install1'])) { + //if (get_class($this)=='Onedrive' || get_class($this)=='OnedriveCN') { + return message(' + ' . getconstStr('JumptoOffice') . ' + + ', getconstStr('Wait') . ' 1s', 201); + //} else { + // return message('Something error, retry after a few seconds.', 'Retry', 201); + //} + } + + if (isset($_GET['install0'])) { + if ($_POST['disktag_add']!='') { + $_POST['disktag_add'] = preg_replace('/[^0-9a-zA-Z|_]/i', '', $_POST['disktag_add']); + $f = substr($_POST['disktag_add'], 0, 1); + if (strlen($_POST['disktag_add'])==1) $_POST['disktag_add'] .= '_'; + if (isCommonEnv($_POST['disktag_add'])) { + return message('Do not input ' . $envs . '
', 'Error', 400); + } elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) { + return message('Please start with letters
+ ', 'Error', 400); + } + + $tmp = null; + // clear envs + foreach ($EnvConfigs as $env => $v) if (isInnerEnv($env)) $tmp[$env] = ''; + + //$this->disktag = $_POST['disktag_add']; + $tmp['disktag_add'] = $_POST['disktag_add']; + $tmp['diskname'] = $_POST['diskname']; + //$tmp['Driver'] = $_POST['Drive_ver']; + $tmp['Driver'] = $_GET['AddDisk']; + if ($_POST['Drive_ver']=='Sharelink') { + $tmp['shareurl'] = $_POST['shareurl']; + } else { + if ($_POST['Drive_ver']=='Onedrive' && $_POST['NT_Drive_custom']=='on') { + $tmp['client_id'] = $_POST['NT_client_id']; + $tmp['client_secret'] = $_POST['NT_client_secret']; + } elseif ($_POST['Drive_ver']=='OnedriveCN' && $_POST['CN_Drive_custom']=='on') { + $tmp['client_id'] = $_POST['CN_client_id']; + $tmp['client_secret'] = $_POST['CN_client_secret']; + } + } + $response = setConfigResponse( setConfig($tmp, $this->disktag) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $title = getconstStr('MayinEnv'); + $html = getconstStr('Wait'); + if ($_POST['Drive_ver']!='Sharelink') $url .= '?install1&disktag=' . $_GET['disktag'] . '&AddDisk=' . $_GET['AddDisk']; + $html .= ''; + return message($html, $title, 201, 1); + } + + } + } + + $html = ' +
+
+ ' . getconstStr('DiskTag') . ': (' . getConfig('disktag') . ') +
+ ' . getconstStr('DiskName') . ': +
+
+
+
+
+
+
+
+ +
+
'; + if ($_SERVER['language']=='zh-cn') $html .= '你要理解 scfonedrive.github.io 是github上的静态网站,
除非github真的挂掉了,
不然,稍后你如果连不上,请检查你的运营商或其它“你懂的”问题!
'; + $html .=' + +
+
+ '; + $title = 'Select Account Type'; + return message($html, $title, 201); + } + + protected function get_access_token($refresh_token) { + if (!$refresh_token) { + $tmp['stat'] = 0; + $tmp['body'] = 'No refresh_token'; + $this->error = $tmp; + return false; + } + if (!($this->access_token = getcache('access_token', $this->disktag))) { + $p=0; + while ($response['stat']==0&&$p<3) { + $response = curl('POST', $this->oauth_url . 'token', 'client_id=' . $this->client_id . '&client_secret=' . $this->client_secret . '&grant_type=refresh_token&requested_token_use=on_behalf_of&refresh_token=' . $refresh_token ); + $p++; + } + if ($response['stat']==200) $ret = json_decode($response['body'], true); + if (!isset($ret['access_token'])) { + error_log1($this->oauth_url . 'token' . '?client_id=' . $this->client_id . '&client_secret=' . $this->client_secret . '&grant_type=refresh_token&requested_token_use=on_behalf_of&refresh_token=' . substr($refresh_token, 0, 20) . '******' . substr($refresh_token, -20)); + error_log1('failed to get [' . $this->disktag . '] access_token. response: ' . $response['body']); + $response['body'] = json_encode(json_decode($response['body']), JSON_PRETTY_PRINT); + $response['body'] .= '\nfailed to get [' . $this->disktag . '] access_token.'; + $this->error = $response; + return false; + //throw new Exception($response['stat'].', failed to get ['.$this->disktag.'] access_token.'.$response['body']); + } + $tmp = $ret; + $tmp['access_token'] = substr($tmp['access_token'], 0, 10) . '******'; + $tmp['refresh_token'] = substr($tmp['refresh_token'], 0, 10) . '******'; + error_log1('[' . $this->disktag . '] Get access token:' . json_encode($tmp, JSON_PRETTY_PRINT)); + $this->access_token = $ret['access_token']; + savecache('access_token', $this->access_token, $this->disktag, $ret['expires_in'] - 300); + if (time()>getConfig('token_expires', $this->disktag)) setConfig([ 'refresh_token' => $ret['refresh_token'], 'token_expires' => time()+7*24*60*60 ], $this->disktag); + return true; + } + return true; + } + + protected function get_siteid($sharepointSite) + { + //$sharepointSite = getConfig('sharepointSite', $this->disktag); + while (substr($sharepointSite, -1)=='/') $sharepointSite = substr($sharepointSite, 0, -1); + $tmp = splitlast($sharepointSite, '/'); + if ($tmp[1]==urldecode($tmp[1])) { + $sharepointname = urlencode($tmp[1]); + } else { + $sharepointname = $tmp[1]; + } + $tmp = splitlast($tmp[0], '/'); + //if (getConfig('Driver', $this->disktag)=='Onedrive') $url = 'https://graph.microsoft.com/v1.0/sites/root:/' . $tmp[1] . '/' . $sharepointname; + //if (getConfig('Driver', $this->disktag)=='OnedriveCN') $url = 'https://microsoftgraph.chinacloudapi.cn/v1.0/sites/root:/' . $tmp[1] . '/' . $sharepointname; + $url = $this->api_url . '/sites/root:/' . $tmp[1] . '/' . $sharepointname; + + $i=0; + $response = []; + while ($url!=''&&$response['stat']!=200&&$i<4) { + $response = $this->MSAPI('GET', $url); + $i++; + } + if ($response['stat']!=200) { + error_log1('failed to get siteid. response' . json_encode($response)); + $response['body'] .= '\nfailed to get siteid.'; + return $response; + //throw new Exception($response['stat'].', failed to get siteid.'.$response['body']); + } + return json_decode($response['body'],true)['id']; + } + + public function del_upload_cache($path) + { + error_log1('del.tmp:GET,'.json_encode($_GET,JSON_PRETTY_PRINT)); + $tmp = splitlast($_GET['filename'], '/'); + if ($tmp[1]!='') { + $filename = $tmp[0] . '/.' . $_GET['filelastModified'] . '_' . $_GET['filesize'] . '_' . $tmp[1] . '.tmp'; + } else { + $filename = '.' . $_GET['filelastModified'] . '_' . $_GET['filesize'] . '_' . $_GET['filename'] . '.tmp'; + } + $filename = path_format( path_format($_SERVER['list_path'] . path_format($path)) . '/' . spurlencode($filename, '/') ); + $tmp = $this->MSAPI('DELETE', $filename, ''); + $path1 = path_format($_SERVER['list_path'] . path_format($path)); + if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1); + savecache('path_' . $path1, json_decode('{}',true), $this->disktag, 1); + return output($tmp['body'],$tmp['stat']); + } + + public function get_thumbnails_url($path = '/') + { + $thumb_url = getcache('thumb_'.$path, $this->disktag); + if ($thumb_url=='') { + $url = $this->api_url . $this->ext_api_url; + if ($path !== '/') { + $url .= ':' . $path; + if (substr($url,-1)=='/') $url=substr($url,0,-1); + } + $url .= ':/thumbnails/0/medium'; + $files = json_decode($this->MSAPI('GET', $url)['body'], true); + if (isset($files['url'])) { + savecache('thumb_' . $path, $files['url'], $this->disktag); + $thumb_url = $files['url']; + } + } + return $thumb_url; + } + + public function smallfileupload($path, $tmpfile) { + if (!$_SERVER['admin']) { + $tmp1 = splitlast($tmpfile['name'], '.'); + if ($tmp1[0]==''||$tmp1[1]=='') $filename = md5_file($tmpfile['tmp_name']); + else $filename = md5_file($tmpfile['tmp_name']) . '.' . $tmp1[1]; + } else { + $filename = $tmpfile['name']; + } + $content = file_get_contents($tmpfile['tmp_name']); + $result = $this->MSAPI('PUT', path_format($_SERVER['list_path'] . '/' . $path . '/' . $filename), $content); + $res = $this->files_format(json_decode($result['body'], true)); + if (isset($res['url'])) $res['url'] = $_SERVER['host'] . path_format($_SERVER['base_disk_path'] . '/' . $path . '/' . $filename); + return output(json_encode($res, JSON_UNESCAPED_SLASHES), $result['stat']); + } + public function bigfileupload($path) + { + if ($_POST['upbigfilename']=='') return output('error: no file name', 400); + if (!is_numeric($_POST['filesize'])) return output('error: no file size', 400); + if (!$_SERVER['admin']) if (!isset($_POST['filemd5'])) return output('error: no file md5', 400); + + $tmp = splitlast($_POST['upbigfilename'], '/'); + if ($tmp[1]!='') { + $fileinfo['name'] = $tmp[1]; + if ($_SERVER['admin']) $fileinfo['path'] = $tmp[0]; + } else { + $fileinfo['name'] = $_POST['upbigfilename']; + } + $fileinfo['size'] = $_POST['filesize']; + $fileinfo['filelastModified'] = $_POST['filelastModified']; + if ($_SERVER['admin']) { + $filename = spurlencode($_POST['upbigfilename'], '/'); + } else { + $tmp1 = splitlast($fileinfo['name'], '.'); + if ($tmp1[0]==''||$tmp1[1]=='') $filename = $_POST['filemd5']; + else $filename = $_POST['filemd5'] . '.' . $tmp1[1]; + } + if ($fileinfo['size']>10*1024*1024) { + $cachefilename = spurlencode( $fileinfo['path'] . '/.' . $fileinfo['filelastModified'] . '_' . $fileinfo['size'] . '_' . $fileinfo['name'] . '.tmp', '/'); + $getoldupinfo = $this->list_files(path_format($path . '/' . $cachefilename)); + //error_log1(json_encode($getoldupinfo, JSON_PRETTY_PRINT)); + if (isset($getoldupinfo['url'])&&$getoldupinfo['size']<5120) { + $getoldupinfo_j = curl('GET', $getoldupinfo['url']); + $getoldupinfo = json_decode($getoldupinfo_j['body'], true); + if ( json_decode( curl('GET', $getoldupinfo['uploadUrl'])['body'], true)['@odata.context']!='' ) return output($getoldupinfo_j['body'], $getoldupinfo_j['stat']); + } + } + $response = $this->MSAPI('createUploadSession', path_format($path . '/' . $filename), '{"item": { "@microsoft.graph.conflictBehavior": "fail" }}'); + if ($response['stat']<500) { + $responsearry = json_decode($response['body'],true); + if (isset($responsearry['error'])) return output($response['body'], $response['stat']); + $fileinfo['uploadUrl'] = $responsearry['uploadUrl']; + if ($fileinfo['size']>10*1024*1024) $this->MSAPI('PUT', path_format($path . '/' . $cachefilename), json_encode($fileinfo, JSON_PRETTY_PRINT)); + } + return output($response['body'], $response['stat']); + } + public function getDiskSpace() { + if (!($diskSpace = getcache('diskSpace', $this->disktag))) { + $url = $this->api_url . $this->ext_api_url; + if (substr($url, -5)=='/root') $url = substr($url, 0, -5); + else return $url; + $response = json_decode($this->MSAPI('GET', $url)['body'], true)['quota']; + $used = size_format($response['used']); + $total = size_format($response['total']); + $diskSpace = $used . ' / ' . $total; + savecache('diskSpace', $diskSpace, $this->disktag); + } + return $diskSpace; + } + + protected function MSAPI($method, $path, $data = '', $headers = []) + { + $activeLimit = getConfig('activeLimit', $this->disktag); + if ($activeLimit!='') { + if ($activeLimit>time()) { + $tmp['error']['code'] = 'Retry-After'; + $tmp['error']['message'] = 'MS limit until ' . date('Y-m-d H:i:s', $activeLimit); + return [ 'stat' => 429, 'body' => json_encode($tmp) ]; + } else { + setConfig(['activeLimit' => ''], $this->disktag); + } + } + if (substr($path,0,7) == 'http://' or substr($path,0,8) == 'https://') { + $url = $path; + } else { + $url = $this->api_url . $this->ext_api_url; + if ($path=='' or $path=='/') { + $url .= '/'; + } elseif (substr($path, 0, 6)=="/items") { + $url = substr($url, 0, -5); + $url .= $path; + } else { + $url .= ':' . $path; + if (substr($url,-1)=='/') $url=substr($url,0,-1); + } + if ($method=='GET') { + $method = 'GET'; // do nothing + } elseif ($method=='PUT') { + if ($path=='' or $path=='/') { + $url .= 'content'; + } else { + $url .= ':/content'; + } + $headers['Content-Type'] = 'text/plain'; + } elseif ($method=='PATCH') { + $headers['Content-Type'] = 'application/json'; + } elseif ($method=='POST') { + $headers['Content-Type'] = 'application/json'; + } elseif ($method=='DELETE') { + $headers['Content-Type'] = 'application/json'; + } else { + if ($path=='' or $path=='/') { + $url .= $method; + } elseif (substr($path, 0, 6)=="/items") { + $url .= '/' . $method; + } else { + $url .= ':/' . $method; + } + $method='POST'; + $headers['Content-Type'] = 'application/json'; + } + } + $headers['Authorization'] = 'Bearer ' . $this->access_token; + if (!isset($headers['Accept'])) $headers['Accept'] = '*/*'; + //if (!isset($headers['Referer'])) $headers['Referer'] = $url;* + $sendHeaders = array(); + foreach ($headers as $headerName => $headerVal) { + $sendHeaders[] = $headerName . ': ' . $headerVal; + } + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_TIMEOUT, 5); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders); + $retry = 0; + $response = []; + while ($retry<3&&!$response['stat']) { + $response['body'] = curl_exec($ch); + $response['stat'] = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $retry++; + } + //$response['Location'] = curl_getinfo($ch); + if ($response['stat']==429) { + $res = json_decode($response['body'], true); + $retryAfter = $res['error']['retryAfterSeconds']; + $retryAfter_n = (int)$retryAfter; + if ($retryAfter_n>0) { + $tmp1['activeLimit'] = $retryAfter_n + time(); + setConfig($tmp1, $this->disktag); + } + } + curl_close($ch); + /*error_log1($response['stat'].' + '.$response['body'].' + '.$url.' + ');*/ + return $response; + } + +} diff --git a/disk/OnedriveCN.php b/disk/OnedriveCN.php new file mode 100644 index 0000000..c777c72 --- /dev/null +++ b/disk/OnedriveCN.php @@ -0,0 +1,26 @@ +disktag = $tag; + $this->redirect_uri = 'https://scfonedrive.github.io'; + if (getConfig('client_id', $tag) && getConfig('client_secret', $tag)) { + $this->client_id = getConfig('client_id', $tag); + $this->client_secret = getConfig('client_secret', $tag); + } else { + $this->client_id = '31f3bed5-b9d9-4173-86a4-72c73d278617'; + $this->client_secret = 'P5-ZNtFK-tT90J.We_-DcsuB8uV7AfjL8Y'; + } + $this->oauth_url = 'https://login.partner.microsoftonline.cn/common/oauth2/v2.0/'; + $this->api_url = 'https://microsoftgraph.chinacloudapi.cn/v1.0'; + $this->scope = 'https://microsoftgraph.chinacloudapi.cn/Files.ReadWrite.All https://microsoftgraph.chinacloudapi.cn/Sites.ReadWrite.All offline_access'; + $res = $this->get_access_token(getConfig('refresh_token', $tag)); + + $this->client_secret = urlencode($this->client_secret); + $this->scope = urlencode($this->scope); + $this->DownurlStrName = '@microsoft.graph.downloadUrl'; + $this->ext_api_url = '/me/drive/root'; + } +} diff --git a/disk/Sharelink.php b/disk/Sharelink.php new file mode 100644 index 0000000..84a122f --- /dev/null +++ b/disk/Sharelink.php @@ -0,0 +1,67 @@ +disktag = $tag; + $this->redirect_uri = 'https://scfonedrive.github.io'; + $this->api_url = getConfig('shareapiurl', $tag); + $res = $this->get_access_token(1); + //$this->ext_api_url = '/me/drive/root'; + $this->DownurlStrName = '@content.downloadUrl'; + } + + public function ext_show_innerenv() + { + return [ 'shareurl' ]; + } + + protected function get_access_token($refresh_token) { + if (!($this->access_token = getcache('access_token', $this->disktag))) { + $shareurl = getConfig('shareurl', $this->disktag); + if (!($this->sharecookie = getcache('sharecookie', $this->disktag))) { + $res = curl('GET', $shareurl, '', [], 1); + error_log1(json_encode($res, JSON_PRETTY_PRINT)); + if (isset($res['returnhead']['Set-Cookie'])) $this->sharecookie = $res['returnhead']['Set-Cookie']; + if (isset($res['returnhead']['set-cookie'])) $this->sharecookie = $res['returnhead']['set-cookie']; + if ($this->sharecookie=='') { + $this->error = $res; + return false; + } + savecache('sharecookie', $this->sharecookie, $this->disktag); + } + $tmp1 = splitlast($shareurl, '/')[0]; + $account = splitlast($tmp1, '/')[1]; + $domain = splitlast($shareurl, '/:')[0]; + $response = curl('POST', + $domain . "/personal/" . $account . "/_api/web/GetListUsingPath(DecodedUrl=@a1)/RenderListDataAsStream?@a1='" . urlencode("/personal/" . $account . "/Documents") . "'&RootFolder=" . urlencode("/personal/" . $account . "/Documents/") . "&TryNewExperienceSingle=TRUE", + '{"parameters":{"__metadata":{"type":"SP.RenderListDataParameters"},"RenderOptions":136967,"AllowMultipleValueFilterForTaxonomyFields":true,"AddRequiredFields":true}}', + [ 'Accept' => 'application/json;odata=verbose', 'Content-Type' => 'application/json;odata=verbose', 'origin' => $domain, 'Cookie' => $this->sharecookie ] + ); + if ($response['stat']==200) $ret = json_decode($response['body'], true); + $this->access_token = splitlast($ret['ListSchema']['.driveAccessToken'],'=')[1]; + $this->api_url = $ret['ListSchema']['.driveUrl'].'/root'; + if (!$this->access_token) { + error_log1($domain . "/personal/" . $account . "/_api/web/GetListUsingPath(DecodedUrl=@a1)/RenderListDataAsStream?@a1='" . urlencode("/personal/" . $account . "/Documents") . "'&RootFolder=" . urlencode("/personal/" . $account . "/Documents/") . "&TryNewExperienceSingle=TRUE"); + error_log1('failed to get share access_token. response' . json_encode($ret)); + //$response['body'] = json_encode(json_decode($response['body']), JSON_PRETTY_PRINT); + $response['body'] .= '
' .json_decode($response['body'], true)['error']['message']['value']; + $response['body'] .= '
failed to get shareurl access_token.'; + $this->error = $response; + return false; + //throw new Exception($response['stat'].', failed to get share access_token.'.$response['body']); + } + //$tmp = $ret; + //$tmp['access_token'] = '******'; + //error_log1('['.$this->disktag.'] Get access token:'.json_encode($tmp, JSON_PRETTY_PRINT)); + savecache('access_token', $this->access_token, $this->disktag); + $tmp1 = null; + if (getConfig('shareapiurl', $this->disktag)!=$this->api_url) $tmp1['shareapiurl'] = $this->api_url; + //if (getConfig('sharecookie', $this->disktag)!=$this->sharecookie) $tmp1['sharecookie'] = $this->sharecookie; + if (!!$tmp1) setConfig($tmp1, $this->disktag); + return true; + } + return true; + } +} diff --git a/disk/Sharepoint.php b/disk/Sharepoint.php new file mode 100644 index 0000000..61af00e --- /dev/null +++ b/disk/Sharepoint.php @@ -0,0 +1,31 @@ +disktag = $tag; + $this->redirect_uri = 'https://scfonedrive.github.io'; + if (getConfig('client_id', $tag) && getConfig('client_secret', $tag)) { + $this->client_id = getConfig('client_id', $tag); + $this->client_secret = getConfig('client_secret', $tag); + } else { + $this->client_id = '734ef928-d74c-4555-8d1b-d942fa0a1a41'; + $this->client_secret = '_I5gOpmG5vTC2Ts_K._wCW4nN1km~4Pk52'; + } + $this->oauth_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/'; + $this->api_url = 'https://graph.microsoft.com/v1.0'; + $this->scope = 'https://graph.microsoft.com/Files.ReadWrite.All https://graph.microsoft.com/Sites.ReadWrite.All offline_access'; + $res = $this->get_access_token(getConfig('refresh_token', $tag)); + + $this->client_secret = urlencode($this->client_secret); + $this->scope = urlencode($this->scope); + $this->DownurlStrName = '@microsoft.graph.downloadUrl'; + $this->ext_api_url = '/sites/' . getConfig('siteid', $tag) . '/drive/root'; + } + + public function ext_show_innerenv() + { + return [ 'sharepointSite', 'siteid' ]; + } +} diff --git a/disk/SharepointCN.php b/disk/SharepointCN.php new file mode 100644 index 0000000..d64fdaa --- /dev/null +++ b/disk/SharepointCN.php @@ -0,0 +1,31 @@ +disktag = $tag; + $this->redirect_uri = 'https://scfonedrive.github.io'; + if (getConfig('client_id', $tag) && getConfig('client_secret', $tag)) { + $this->client_id = getConfig('client_id', $tag); + $this->client_secret = getConfig('client_secret', $tag); + } else { + $this->client_id = '31f3bed5-b9d9-4173-86a4-72c73d278617'; + $this->client_secret = 'P5-ZNtFK-tT90J.We_-DcsuB8uV7AfjL8Y'; + } + $this->oauth_url = 'https://login.partner.microsoftonline.cn/common/oauth2/v2.0/'; + $this->api_url = 'https://microsoftgraph.chinacloudapi.cn/v1.0'; + $this->scope = 'https://microsoftgraph.chinacloudapi.cn/Files.ReadWrite.All https://microsoftgraph.chinacloudapi.cn/Sites.ReadWrite.All offline_access'; + $res = $this->get_access_token(getConfig('refresh_token', $tag)); + + $this->client_secret = urlencode($this->client_secret); + $this->scope = urlencode($this->scope); + $this->DownurlStrName = '@microsoft.graph.downloadUrl'; + $this->ext_api_url = '/sites/' . getConfig('siteid', $tag) . '/drive/root'; + } + + public function ext_show_innerenv() + { + return [ 'sharepointSite', 'siteid' ]; + } +} diff --git a/glitch.json b/glitch.json new file mode 100644 index 0000000..618456b --- /dev/null +++ b/glitch.json @@ -0,0 +1,3 @@ +{ + "start": "php -S 0.0.0.0:8080 index.php" +} diff --git a/index.php b/index.php index efc0ac1..807eed4 100644 --- a/index.php +++ b/index.php @@ -1,13 +1,26 @@ '. json_encode($_SERVER, JSON_PRETTY_PRINT).''; +//echo '
'. json_encode($_ENV, JSON_PRETTY_PRINT).'
'; if (isset($_SERVER['USER'])&&$_SERVER['USER']==='qcloud') { - include 'platform/scf.php'; + if (getenv('ONEMANAGER_CONFIG_SAVE')=='file') include 'platform/TencentSCF_file.php'; + else include 'platform/TencentSCF_env.php'; +} elseif (isset($_SERVER['FC_FUNC_CODE_PATH'])) { + include 'platform/AliyunFC.php'; +} elseif (isset($_SERVER['_APP_SHARE_DIR']) && $_SERVER['_APP_SHARE_DIR']=='/var/share/CFF/processrouter') { + //if (getenv('ONEMANAGER_CONFIG_SAVE')=='file') include 'platform/HuaweiFG_file.php'; + //else include 'platform/HuaweiFG_env.php'; + echo 'FG' . PHP_EOL; +} elseif (isset($_SERVER['BCE_CFC_RUNTIME_NAME']) && $_SERVER['BCE_CFC_RUNTIME_NAME']=='php7') { + include 'platform/BaiduCFC.php'; } elseif (isset($_SERVER['HEROKU_APP_DIR'])&&$_SERVER['HEROKU_APP_DIR']==='/app') { - include 'platform/heroku.php'; + include 'platform/Heroku.php'; $path = getpath(); //echo 'path:'. $path; $_GET = getGET(); @@ -18,9 +31,26 @@ if (isset($_SERVER['USER'])&&$_SERVER['USER']==='qcloud') { header($headerName . ': ' . $headerVal, true); } http_response_code($re['statusCode']); - echo $re['body']; -} else { - include 'platform/normal.php'; + if ($re['isBase64Encoded']) echo base64_decode($re['body']); + else echo $re['body']; +} elseif (isset($_SERVER['DOCUMENT_ROOT'])&&$_SERVER['DOCUMENT_ROOT']==='/var/task/user') { + if (getenv('ONEMANAGER_CONFIG_SAVE')=='env') include 'platform/Vercel_env.php'; + else include 'platform/Vercel.php'; + $path = getpath(); + //echo 'path:'. $path; + $_GET = getGET(); + //echo '
'. json_encode($_GET, JSON_PRETTY_PRINT).'
'; + $re = main($path); + $sendHeaders = array(); + foreach ($re['headers'] as $headerName => $headerVal) { + header($headerName . ': ' . $headerVal, true); + } + http_response_code($re['statusCode']); + if ($re['isBase64Encoded']) echo base64_decode($re['body']); + else echo $re['body']; +} elseif (isset($_SERVER['DOCUMENT_ROOT'])&&substr($_SERVER['DOCUMENT_ROOT'], 0, 13)==='/home/runner/') { + include 'platform/Replit.php'; + $path = getpath(); //echo 'path:'. $path; $_GET = getGET(); @@ -32,14 +62,36 @@ if (isset($_SERVER['USER'])&&$_SERVER['USER']==='qcloud') { header($headerName . ': ' . $headerVal, true); } http_response_code($re['statusCode']); - echo $re['body']; + if ($re['isBase64Encoded']) echo base64_decode($re['body']); + else echo $re['body']; +} else { + include 'platform/Normal.php'; + if (!function_exists('curl_init')) { + return message('Need curl, please install php-curl.', 'Error', 500); + } + $path = getpath(); + //echo 'path:'. $path; + $_GET = getGET(); + //echo '
'. json_encode($_GET, JSON_PRETTY_PRINT).'
'; + $re = main($path); + $sendHeaders = array(); + foreach ($re['headers'] as $headerName => $headerVal) { + header($headerName . ': ' . $headerVal, true); + } + http_response_code($re['statusCode']); + if ($re['isBase64Encoded']) echo base64_decode($re['body']); + else echo $re['body']; } +// Tencent SCF function main_handler($event, $context) { $event = json_decode(json_encode($event), true); $context = json_decode(json_encode($context), true); printInput($event, $context); + if ( $event['requestContext']['serviceId'] === substr($event['headers']['host'], 0, strlen($event['requestContext']['serviceId'])) ) { + if ($event['path']==='/' . $context['function_name']) return output('add / at last.', 308, ['Location'=>'/'.$event['requestContext']['stage'].'/'.$context['function_name'].'/']); + } unset($_POST); unset($_GET); unset($_COOKIE); @@ -50,3 +102,76 @@ function main_handler($event, $context) return main($path); } + +// Aliyun FC & Huawei FG & Baidu CFC +function handler($event, $context) +{ + if (isset($_SERVER['FC_FUNC_CODE_PATH'])) { + // Aliyun FC + set_error_handler("myErrorHandler"); + $tmp = array( + 'method' => $event->getMethod(), + 'clientIP' => $event->getAttribute("clientIP"), + 'requestURI' => $event->getAttribute("requestURI"), + 'path' => spurlencode($event->getAttribute("path"), '/'), + 'queryString' => $event->getQueryParams(), + 'headers' => $event->getHeaders(), + 'body' => $event->getBody()->getContents(), + ); + $event = $tmp; + $context = json_decode(json_encode($context), true); + printInput($event, $context); + unset($_POST); + unset($_GET); + unset($_COOKIE); + unset($_SERVER); + GetGlobalVariable($event); + $path = GetPathSetting($event, $context); + + $re = main($path); + + return new RingCentral\Psr7\Response($re['statusCode'], $re['headers'], ($re['isBase64Encoded']?base64_decode($re['body']):$re['body'])); + + } elseif ($_SERVER['_APP_SHARE_DIR']=='/var/share/CFF/processrouter') { + // Huawei FG + global $contextUserData; + $contextUserData = $context; + if ($context->getUserData('ONEMANAGER_CONFIG_SAVE')=='file') include_once 'platform/HuaweiFG_file.php'; + else include_once 'platform/HuaweiFG_env.php'; + + $event = json_decode(json_encode($event), true); + if ($event['isBase64Encoded']) $event['body'] = base64_decode($event['body']); + + printInput($event, $context); + unset($_POST); + unset($_GET); + unset($_COOKIE); + unset($_SERVER); + GetGlobalVariable($event); + //echo '
'. json_encode($_COOKIE, JSON_PRETTY_PRINT).'
'; + $path = GetPathSetting($event, $context); + + return main($path); + + } elseif ($_SERVER['BCE_CFC_RUNTIME_NAME']=='php7') { + // Baidu CFC + //$html = '
'. json_encode($event, JSON_PRETTY_PRINT).'
'; + //$html .= '
'. json_encode($context, JSON_PRETTY_PRINT).'
'; + //$html .= '
'. json_encode($_SERVER, JSON_PRETTY_PRINT).'
'; + //$html .= $event['path']; + //$html .= $context['functionBrn']; + //return json_encode(output($html), JSON_FORCE_OBJECT); + + printInput($event, $context); + unset($_POST); + unset($_GET); + unset($_COOKIE); + unset($_SERVER); + GetGlobalVariable($event); + //echo '
'. json_encode($_COOKIE, JSON_PRETTY_PRINT).'
'; + $path = GetPathSetting($event, $context); + + return json_encode(main($path), JSON_FORCE_OBJECT); + + } +} diff --git a/js/sha1.min.js b/js/sha1.min.js new file mode 100644 index 0000000..3d297fd --- /dev/null +++ b/js/sha1.min.js @@ -0,0 +1,8 @@ +/** + * Minified by jsDelivr using UglifyJS v3.1.10. + * Original file: /npm/js-sha1@0.6.0/src/sha1.js + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +!function(){"use strict";function Sha1(t){t?(blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}var root="object"==typeof window?window:{},NODE_JS=!root.JS_SHA1_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;NODE_JS&&(root=global);var COMMON_JS=!root.JS_SHA1_NO_COMMON_JS&&"object"==typeof module&&module.exports,AMD="function"==typeof define&&define.amd,HEX_CHARS="0123456789abcdef".split(""),EXTRA=[-2147483648,8388608,32768,128],SHIFT=[24,16,8,0],OUTPUT_TYPES=["hex","array","digest","arrayBuffer"],blocks=[],createOutputMethod=function(t){return function(h){return new Sha1(!0).update(h)[t]()}},createMethod=function(){var t=createOutputMethod("hex");NODE_JS&&(t=nodeWrap(t)),t.create=function(){return new Sha1},t.update=function(h){return t.create().update(h)};for(var h=0;h>2]|=t[i]<>2]|=s<>2]|=(192|s>>6)<>2]|=(128|63&s)<=57344?(o[e>>2]|=(224|s>>12)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<>2]|=(240|s>>18)<>2]|=(128|s>>12&63)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<=64?(this.block=o[16],this.start=e-64,this.hash(),this.hashed=!0):this.start=e}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Sha1.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,h=this.lastByteIndex;t[16]=this.block,t[h>>2]|=EXTRA[3&h],this.block=t[16],h>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}},Sha1.prototype.hash=function(){var t,h,s=this.h0,e=this.h1,i=this.h2,r=this.h3,o=this.h4,H=this.blocks;for(t=16;t<80;++t)h=H[t-3]^H[t-8]^H[t-14]^H[t-16],H[t]=h<<1|h>>>31;for(t=0;t<20;t+=5)s=(h=(e=(h=(i=(h=(r=(h=(o=(h=s<<5|s>>>27)+(e&i|~e&r)+o+1518500249+H[t]<<0)<<5|o>>>27)+(s&(e=e<<30|e>>>2)|~s&i)+r+1518500249+H[t+1]<<0)<<5|r>>>27)+(o&(s=s<<30|s>>>2)|~o&e)+i+1518500249+H[t+2]<<0)<<5|i>>>27)+(r&(o=o<<30|o>>>2)|~r&s)+e+1518500249+H[t+3]<<0)<<5|e>>>27)+(i&(r=r<<30|r>>>2)|~i&o)+s+1518500249+H[t+4]<<0,i=i<<30|i>>>2;for(;t<40;t+=5)s=(h=(e=(h=(i=(h=(r=(h=(o=(h=s<<5|s>>>27)+(e^i^r)+o+1859775393+H[t]<<0)<<5|o>>>27)+(s^(e=e<<30|e>>>2)^i)+r+1859775393+H[t+1]<<0)<<5|r>>>27)+(o^(s=s<<30|s>>>2)^e)+i+1859775393+H[t+2]<<0)<<5|i>>>27)+(r^(o=o<<30|o>>>2)^s)+e+1859775393+H[t+3]<<0)<<5|e>>>27)+(i^(r=r<<30|r>>>2)^o)+s+1859775393+H[t+4]<<0,i=i<<30|i>>>2;for(;t<60;t+=5)s=(h=(e=(h=(i=(h=(r=(h=(o=(h=s<<5|s>>>27)+(e&i|e&r|i&r)+o-1894007588+H[t]<<0)<<5|o>>>27)+(s&(e=e<<30|e>>>2)|s&i|e&i)+r-1894007588+H[t+1]<<0)<<5|r>>>27)+(o&(s=s<<30|s>>>2)|o&e|s&e)+i-1894007588+H[t+2]<<0)<<5|i>>>27)+(r&(o=o<<30|o>>>2)|r&s|o&s)+e-1894007588+H[t+3]<<0)<<5|e>>>27)+(i&(r=r<<30|r>>>2)|i&o|r&o)+s-1894007588+H[t+4]<<0,i=i<<30|i>>>2;for(;t<80;t+=5)s=(h=(e=(h=(i=(h=(r=(h=(o=(h=s<<5|s>>>27)+(e^i^r)+o-899497514+H[t]<<0)<<5|o>>>27)+(s^(e=e<<30|e>>>2)^i)+r-899497514+H[t+1]<<0)<<5|r>>>27)+(o^(s=s<<30|s>>>2)^e)+i-899497514+H[t+2]<<0)<<5|i>>>27)+(r^(o=o<<30|o>>>2)^s)+e-899497514+H[t+3]<<0)<<5|e>>>27)+(i^(r=r<<30|r>>>2)^o)+s-899497514+H[t+4]<<0,i=i<<30|i>>>2;this.h0=this.h0+s<<0,this.h1=this.h1+e<<0,this.h2=this.h2+i<<0,this.h3=this.h3+r<<0,this.h4=this.h4+o<<0},Sha1.prototype.hex=function(){this.finalize();var t=this.h0,h=this.h1,s=this.h2,e=this.h3,i=this.h4;return HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[15&t]+HEX_CHARS[h>>28&15]+HEX_CHARS[h>>24&15]+HEX_CHARS[h>>20&15]+HEX_CHARS[h>>16&15]+HEX_CHARS[h>>12&15]+HEX_CHARS[h>>8&15]+HEX_CHARS[h>>4&15]+HEX_CHARS[15&h]+HEX_CHARS[s>>28&15]+HEX_CHARS[s>>24&15]+HEX_CHARS[s>>20&15]+HEX_CHARS[s>>16&15]+HEX_CHARS[s>>12&15]+HEX_CHARS[s>>8&15]+HEX_CHARS[s>>4&15]+HEX_CHARS[15&s]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>4&15]+HEX_CHARS[15&e]+HEX_CHARS[i>>28&15]+HEX_CHARS[i>>24&15]+HEX_CHARS[i>>20&15]+HEX_CHARS[i>>16&15]+HEX_CHARS[i>>12&15]+HEX_CHARS[i>>8&15]+HEX_CHARS[i>>4&15]+HEX_CHARS[15&i]},Sha1.prototype.toString=Sha1.prototype.hex,Sha1.prototype.digest=function(){this.finalize();var t=this.h0,h=this.h1,s=this.h2,e=this.h3,i=this.h4;return[t>>24&255,t>>16&255,t>>8&255,255&t,h>>24&255,h>>16&255,h>>8&255,255&h,s>>24&255,s>>16&255,s>>8&255,255&s,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24&255,i>>16&255,i>>8&255,255&i]},Sha1.prototype.array=Sha1.prototype.digest,Sha1.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(20),h=new DataView(t);return h.setUint32(0,this.h0),h.setUint32(4,this.h1),h.setUint32(8,this.h2),h.setUint32(12,this.h3),h.setUint32(16,this.h4),t};var exports=createMethod();COMMON_JS?module.exports=exports:(root.sha1=exports,AMD&&define(function(){return exports}))}(); +//# sourceMappingURL=/sm/dad6bd9f16f12d9db4b0e4eaae5c5f614cb87edf6808e087afac03051831773b.map diff --git a/platform/AliyunFC.php b/platform/AliyunFC.php new file mode 100644 index 0000000..65d0c91 --- /dev/null +++ b/platform/AliyunFC.php @@ -0,0 +1,552 @@ +500) $event['body']=substr($event['body'],0,strpos($event['body'],'base64')+30) . '...Too Long!...' . substr($event['body'],-50); + echo urldecode(json_encode($event, JSON_PRETTY_PRINT)) . ' + +' . urldecode(json_encode($context, JSON_PRETTY_PRINT)) . ' + +'; +} + +function GetGlobalVariable($event) +{ + $_GET = $event['queryString']; + foreach ($_GET as $k => $v) { + if ($v=='') $_GET[$k] = true; + } + $postbody = explode("&",$event['body']); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + $cookiebody = explode("; ",$event['headers']['Cookie'][0]); + foreach ($cookiebody as $cookievalues) { + $pos = strpos($cookievalues,"="); + $_COOKIE[urldecode(substr($cookievalues,0,$pos))]=urldecode(substr($cookievalues,$pos+1)); + } +} + +function GetPathSetting($event, $context) +{ + $_SERVER['firstacceptlanguage'] = strtolower(splitfirst(splitfirst($event['headers']['Accept-Language'][0],';')[0],',')[0]); + $_SERVER['accountId'] = $context['accountId']; + $_SERVER['region'] = $context['region']; + $_SERVER['service_name'] = $context['service']['name']; + $_SERVER['function_name'] = $context['function']['name']; + //$path = str_replace('%5D', ']', str_replace('%5B', '[', $event['path']));//%5B + //$path = $event['path']; + $path = $event['requestURI']; + if (strpos($path, '?')) $path = substr($path, 0, strpos($path, '?')); + $tmp = urldecode($event['requestURI']); + if (strpos($tmp, '?')) $tmp = substr($tmp, 0, strpos($tmp, '?')); + if ($path=='/'||$path=='') { + $_SERVER['base_path'] = $tmp; + } else { + $tmp = str_replace('&', '&', $tmp); + while ($tmp!=urldecode($tmp)) $tmp = urldecode($tmp); + $tmp1 = urldecode($event['path']); + while ($tmp1!=urldecode($tmp1)) $tmp1 = urldecode($tmp1); + $_SERVER['base_path'] = substr($tmp, 0, strlen($tmp)-strlen($tmp1)+1); + //$_SERVER['base_path'] = substr($tmp, 0, strlen(urldecode($event['path']))); + } + $_SERVER['base_path'] = spurlencode($_SERVER['base_path'], '/'); + //$_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path); + $_SERVER['REMOTE_ADDR'] = $event['clientIP']; + $_SERVER['HTTP_X_REQUESTED_WITH'] = $event['headers']['X-Requested-With'][0]; + if (isset($event['headers']['Authorization'])) { + $basicAuth = splitfirst(base64_decode(splitfirst($event['headers']['Authorization'][0], 'Basic ')[1]), ':'); + $_SERVER['PHP_AUTH_USER'] = $basicAuth[0]; + $_SERVER['PHP_AUTH_PW'] = $basicAuth[1]; + } + $_SERVER['HTTP_HOST'] = $event['headers']['Host'][0]; + $_SERVER['REQUEST_SCHEME'] = $event['headers']['X-Forwarded-Proto'][0]; + $_SERVER['host'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']; + $_SERVER['referhost'] = explode('/', $event['headers']['Referer'][0])[2]; + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $event['headers']['If-Modified-Since'][0]; + $_SERVER['FC_FUNC_CODE_PATH'] = getenv('FC_FUNC_CODE_PATH'); + $_SERVER['REQUEST_METHOD'] = $event['method']; + return $path; + //return spurlencode($path, '/'); +} + +function getConfig($str, $disktag = '') +{ + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + $env = json_decode(getenv($disktag), true); + if (isset($env[$str])) { + if (isBase64Env($str)) return base64y_decode($env[$str]); + else return $env[$str]; + } + } else { + if (isBase64Env($str)) return base64y_decode(getenv($str)); + else return getenv($str); + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + if ($disktag=='') $disktag = $_SERVER['disktag']; + $disktags = explode("|", getConfig('disktag')); + $diskconfig = json_decode(getenv($disktag), true); + $tmp = []; + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $tmp[$k] = base64y_encode($v); + else $tmp[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $diskconfig[$k] = base64y_encode($v); + else $diskconfig[$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $tmp[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $tmp[$newtag] = getConfig($v); + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $tmp[$k] = json_encode($v); + } + } + if ($indisk) { + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $tmp[$disktag] = json_encode($diskconfig); + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $tmp['disktag'] = implode('|', $tags); + $tmp[$arr['disktag_newname']] = getConfig($arr['disktag_rename']); + $tmp[$arr['disktag_rename']] = ''; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $tmp['disktag'] = substr($disktag_s, 0, -1); + else $tmp['disktag'] = ''; + } + } +// echo '正式设置:'.json_encode($tmp,JSON_PRETTY_PRINT).' +//'; + $response = updateEnvironment($tmp, $_SERVER['accountId'], $_SERVER['region'], $_SERVER['service_name'], $_SERVER['function_name'], getConfig('AccessKeyID'), getConfig('AccessKeySecret')); + //WaitSCFStat(); + return $response; +} + +function install() +{ + global $constStr; + if ($_GET['install2']) { + $tmp['admin'] = $_POST['admin']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } + if (needUpdate()) { + OnekeyUpate(); + return message('update to github version, reinstall. + + ', 'Program updating', 201); + } + return output('Jump + + ', 302); + } + if ($_GET['install1']) { + //if ($_POST['admin']!='') { + $tmp['timezone'] = $_COOKIE['timezone']; + //$AccessKeyID = getConfig('AccessKeyID'); + //if ($AccessKeyID=='') { + $AccessKeyID = $_POST['AccessKeyID']; + $tmp['AccessKeyID'] = $AccessKeyID; + //} + //$AccessKeySecret = getConfig('AccessKeySecret'); + //if ($AccessKeySecret=='') { + $AccessKeySecret = $_POST['AccessKeySecret']; + $tmp['AccessKeySecret'] = $AccessKeySecret; + //} + $response = setConfigResponse( SetbaseConfig($tmp, $_SERVER['accountId'], $_SERVER['region'], $_SERVER['service_name'], $_SERVER['function_name'], $AccessKeyID, $AccessKeySecret) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + $html .= ' +
+
+ +
+ '; + $title = getconstStr('SetAdminPassword'); + return message($html, $title, 201); + } + //} + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + //if (getConfig('AccessKeyID')==''||getConfig('AccessKeySecret')=='') + $html .= ' + ' . getconstStr('Create') . ' AccessKeyID & AccessKeySecret
+
+
'; + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + $html .= '' . getconstStr('ClickInstall').', ' . getconstStr('LogintoBind'); + $title = 'Install'; + return message($html, $title, 201); +} + +function FCAPI2016($config, $Method, $data = '') +{ + $accountId = $config['accountId']; + $region = $config['region']; + $service_name = $config['service_name']; + $function_name = $config['function_name']; + $AccessKeyID = $config['AccessKeyID']; + $AccessKeySecret = $config['AccessKeySecret']; + + $host = $accountId . '.' . $region . '-internal.fc.aliyuncs.com'; + $path = '/2016-08-15/services/' . $service_name . '/functions/' . $function_name; + $url = 'https://' . $host . $path; + + $ContentMd5 = ''; + $ContentType = 'application/json'; + date_default_timezone_set('UTC'); // unset last timezone setting + $Date = substr(gmdate("r", time()), 0, -5) . 'GMT'; + $CanonicalizedFCHeaders = ''; + $CanonicalizedResource = $path; + + $signaturestr = $Method . "\n" . $ContentMd5 . "\n" . $ContentType . "\n" . $Date . "\n" . $CanonicalizedFCHeaders . $CanonicalizedResource; + $signature = base64_encode(hash_hmac('sha256', $signaturestr, $AccessKeySecret, true)); + + $header['Host'] = $host; + $header['Date'] = $Date; + $header['Content-Type'] = $ContentType; + $header['Authorization'] = 'FC ' . $AccessKeyID . ':' . $signature; + $header['Content-Length'] = strlen($data); + + //return curl($Method, $url, $data, $header)['body']; + $p = 0; + while ($response['stat']==0 && $p<3) { + $response = curl($Method, $url, $data, $header); + $p++; + } + + if ($response['stat']==0) { + $tmp['ErrorCode'] = 'Network Error'; + $tmp['ErrorMessage'] = 'Can not connect ' . $host; + return json_encode($tmp); + } + if ($response['stat']!=200) { + $tmp = json_decode($response['body'], true); + $tmp['ErrorMessage'] .= '
' . $response['stat'] . '
' . $signaturestr . '
' . json_encode($header) . PHP_EOL; + return json_encode($tmp); + } + return $response['body']; +} + +function getfunctioninfo($config) +{ + return FCAPI2016($config, 'GET'); +} + +function updateEnvironment($Envs, $accountId, $region, $service_name, $function_name, $AccessKeyID, $AccessKeySecret) +{ + //print_r($Envs); + $config['accountId'] = $accountId; + $config['region'] = $region; + $config['service_name'] = $service_name; + $config['function_name'] = $function_name; + $config['AccessKeyID'] = $AccessKeyID; + $config['AccessKeySecret'] = $AccessKeySecret; + + $tmp = json_decode(getfunctioninfo($config), true); + foreach ($tmp['environmentVariables'] as $key => $value ) { + $tmp_env[$key] = $value; + } + foreach ($Envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + //ksort($tmp_env); + sortConfig($tmp_env); + + $tmpdata['environmentVariables'] = $tmp_env; + return FCAPI2016($config, 'PUT', json_encode($tmpdata)); +} + +function SetbaseConfig($Envs, $accountId, $region, $service_name, $function_name, $AccessKeyID, $AccessKeySecret) +{ + $config['accountId'] = $accountId; + $config['region'] = $region; + $config['service_name'] = $service_name; + $config['function_name'] = $function_name; + $config['AccessKeyID'] = $AccessKeyID; + $config['AccessKeySecret'] = $AccessKeySecret; + + $tmp = json_decode(getfunctioninfo($config), true); + foreach ($tmp['environmentVariables'] as $key => $value ) { + $tmp_env[$key] = $value; + } + foreach ($Envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + ksort($tmp_env); + + $tmpdata['description'] = 'Onedrive index and manager in Aliyun FC.'; + $tmpdata['memorySize'] = 128; + $tmpdata['timeout'] = 30; + $tmpdata['environmentVariables'] = $tmp_env; + + return FCAPI2016($config, 'PUT', json_encode($tmpdata)); +} + +function updateProgram($accountId, $region, $service_name, $function_name, $AccessKeyID, $AccessKeySecret, $source) +{ + $config['accountId'] = $accountId; + $config['region'] = $region; + $config['service_name'] = $service_name; + $config['function_name'] = $function_name; + $config['AccessKeyID'] = $AccessKeyID; + $config['AccessKeySecret'] = $AccessKeySecret; + + $tmp = json_decode(getfunctioninfo($config), true); + + $tmpdata['code']['zipFile'] = base64_encode( file_get_contents($source) ); + + return FCAPI2016($config, 'PUT', json_encode($tmpdata)); +} + +function api_error($response) +{ + return isset($response['ErrorMessage']); +} + +function api_error_msg($response) +{ + return $response['ErrorCode'] . '
+' . $response['ErrorMessage'] . '

+ +accountId:' . $_SERVER['accountId'] . '
+region:' . $_SERVER['region'] . '
+service_name:' . $_SERVER['service_name'] . '
+function_name:' . $_SERVER['function_name'] . '
+ +'; +} + +function setConfigResponse($response) +{ + return json_decode($response, true); +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + $source = '/tmp/code.zip'; + $outPath = '/tmp/'; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return json_encode(['ErrorMessage'=>'Git Source input Error!']); + $tarfile = '/tmp/github.tar.gz'; + file_put_contents($tarfile, file_get_contents($url)); + $phar = new PharData($tarfile); + $html = $phar->extractTo($outPath, null, true);//路径 要解压的文件 是否覆盖 + + // 获取解压出的目录名 + $outPath = findIndexPath($outPath); + + // 将目录中文件打包成zip + $zip = new ZipArchive(); + if($zip->open($source, ZipArchive::CREATE)){ + addFileToZip($zip, $outPath); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 + $zip->close(); //关闭处理的zip文件 + } + + return updateProgram($_SERVER['accountId'], $_SERVER['region'], $_SERVER['service_name'], $_SERVER['function_name'], getConfig('AccessKeyID'), getConfig('AccessKeySecret'), $source); +} + +function addFileToZip($zip, $rootpath, $path = '') +{ + if (substr($rootpath,-1)=='/') $rootpath = substr($rootpath, 0, -1); + if (substr($path,0,1)=='/') $path = substr($path, 1); + $handler=opendir(path_format($rootpath.'/'.$path)); //打开当前文件夹由$path指定。 + while($filename=readdir($handler)){ + if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作 + $nowname = path_format($rootpath.'/'.$path."/".$filename); + if(is_dir($nowname)){// 如果读取的某个对象是文件夹,则递归 + addFileToZip($zip, $rootpath, $path."/".$filename); + }else{ //将文件加入zip对象 + $zip->addFile($nowname); + $newname = $path."/".$filename; + if (substr($newname,0,1)=='/') $newname = substr($newname, 1); + $zip->renameName($nowname, $newname); + } + } + } + @closedir($handler); +} + +function myErrorHandler($errno, $errstr, $errfile, $errline) { + if (!(error_reporting() & $errno)) { + return false; + } + switch ($errno) { + case E_USER_ERROR: + $errInfo = array( + "errorMessage" => $errstr, + "errorType" => \ServerlessFC\friendly_error_type($errno), + "stackTrace" => array( + "file" => $errfile, + "line" => $errline, + ), + ); + throw new \ErrorException($errstr, 0, $errno, $errfile, $errline); + break; + default: // E_USER_WARNING | E_USER_NOTICE + break; + } + return true; +} + +function WaitFunction() { + return true; +} + +function changeAuthKey() { + if ($_POST['AccessKeyID']!=''&&$_POST['AccessKeySecret']!='') { + $tmp['AccessKeyID'] = $_POST['AccessKeyID']; + $tmp['AccessKeySecret'] = $_POST['AccessKeySecret']; + $response = setConfigResponse( SetbaseConfig($tmp, $_SERVER['accountId'], $_SERVER['region'], $_SERVER['service_name'], $_SERVER['function_name'], $tmp['AccessKeyID'], $tmp['AccessKeySecret']) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + $html = ' +
+ ' . getconstStr('Create') . ' AccessKeyID & AccessKeySecret
+
+
+ +
+ '; + return message($html, 'Change platform Auth token or key', 200); +} + +function smallfileupload($drive, $path) { + return output('Can not upload through FC.', 400); +} diff --git a/platform/BaiduCFC.php b/platform/BaiduCFC.php new file mode 100644 index 0000000..f8354cf --- /dev/null +++ b/platform/BaiduCFC.php @@ -0,0 +1,491 @@ +500) $event['body']=substr($event['body'],0,strpos($event['body'],'base64')+30) . '...Too Long!...' . substr($event['body'],-50); + echo urldecode(json_encode($event, JSON_PRETTY_PRINT)) . ' + +' . urldecode(json_encode($context, JSON_PRETTY_PRINT)) . ' + +'; +} + +function GetGlobalVariable($event) +{ + $_GET = $event['queryStringParameters']; + foreach ($_GET as $k => $v) { + if ($v == '') $_GET[$k] = true; + } + $postbody = explode("&",$event['body']); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + $cookiebody = explode("; ",$event['headers']['Cookie']); + foreach ($cookiebody as $cookievalues) { + $pos = strpos($cookievalues,"="); + $_COOKIE[urldecode(substr($cookievalues,0,$pos))]=urldecode(substr($cookievalues,$pos+1)); + } +} + +function GetPathSetting($event, $context) +{ + $_SERVER['firstacceptlanguage'] = strtolower(splitfirst(splitfirst($event['headers']['Accept-Language'],';')[0],',')[0]); + $_SERVER['functionBrn'] = $context['functionBrn']; + $_SERVER['base_path'] = '/'; + $path = $event['path']; + //$_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path); + $_SERVER['REMOTE_ADDR'] = $event['requestContext']['sourceIp']; + $_SERVER['HTTP_X_REQUESTED_WITH'] = $event['headers']['X-Requested-With']; + $_SERVER['HTTP_USER_AGENT'] = $event['headers']['User-Agent']; + if (isset($event['headers']['authorization'])) { + $basicAuth = splitfirst(base64_decode(splitfirst($event['headers']['authorization'], 'Basic ')[1]), ':'); + $_SERVER['PHP_AUTH_USER'] = $basicAuth[0]; + $_SERVER['PHP_AUTH_PW'] = $basicAuth[1]; + } + $_SERVER['HTTP_HOST'] = $event['headers']['Host']; + $_SERVER['REQUEST_SCHEME'] = $event['headers']['X-Forwarded-Proto']; + $_SERVER['host'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']; + $_SERVER['referhost'] = explode('/', $event['headers']['Referer'])[2]; + $_SERVER['HTTP_TRANSLATE'] = $event['headers']['translate'];//'f' + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $event['headers']['If-Modified-Since']; + $_SERVER['REQUEST_METHOD'] = $event['httpMethod']; + $_SERVER['BCE_CFC_RUNTIME_NAME'] = 'php7'; + return $path; +} + +function getConfig($str, $disktag = '') +{ + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + $env = json_decode(getenv($disktag), true); + if (isset($env[$str])) { + if (isBase64Env($str)) return base64y_decode($env[$str]); + else return $env[$str]; + } + } else { + if (isBase64Env($str)) return base64y_decode(getenv($str)); + else return getenv($str); + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + if ($disktag=='') $disktag = $_SERVER['disktag']; + $disktags = explode("|",getConfig('disktag')); + $diskconfig = json_decode(getenv($disktag), true); + $tmp = []; + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $tmp[$k] = base64y_encode($v); + else $tmp[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $diskconfig[$k] = base64y_encode($v); + else $diskconfig[$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $tmp[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $tmp[$newtag] = getConfig($v); + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $tmp[$k] = json_encode($v); + } + } + if ($indisk) { + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $tmp[$disktag] = json_encode($diskconfig); + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $tmp['disktag'] = implode('|', $tags); + $tmp[$arr['disktag_newname']] = getConfig($arr['disktag_rename']); + $tmp[$arr['disktag_rename']] = ''; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $tmp['disktag'] = substr($disktag_s, 0, -1); + else $tmp['disktag'] = ''; + } + } +// echo '正式设置:'.json_encode($tmp,JSON_PRETTY_PRINT).' +//'; + $response = updateEnvironment($tmp, getConfig('SecretId'), getConfig('SecretKey')); + return $response; +} + +function install() +{ + global $constStr; + if ($_GET['install2']) { + $tmp['admin'] = $_POST['admin']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } + if (needUpdate()) { + OnekeyUpate(); + return message('update to github version, reinstall. + + ', 'Program updating', 201); + } + return output('Jump + + ', 302); + } + if ($_GET['install1']) { + $tmp['timezone'] = $_COOKIE['timezone']; + //$SecretId = getConfig('SecretId'); + //if ($SecretId=='') { + $SecretId = $_POST['SecretId']; + $tmp['SecretId'] = $SecretId; + //} + //$SecretKey = getConfig('SecretKey'); + //if ($SecretKey=='') { + $SecretKey = $_POST['SecretKey']; + $tmp['SecretKey'] = $SecretKey; + //} + $response = setConfigResponse(SetbaseConfig($tmp, $SecretId, $SecretKey)); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + $html .= ' +
+
+ +
+ '; + $title = getconstStr('SetAdminPassword'); + return message($html, $title, 201); + } + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + //if (getConfig('SecretId')==''||getConfig('SecretKey')=='') + $html .= ' + ' . getconstStr('Create') . ' Access Key & Secret Key
+
+
'; + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + $html .= ''.getconstStr('ClickInstall').', '.getconstStr('LogintoBind'); + $title = 'Install'; + return message($html, $title, 201); +} + +function CFCAPIv1($Brn, $AccessKey, $SecretKey, $Method, $End, $data = '') +{ + // brn:bce:cfc:bj:c094b1ca1XXXXXXXXb8dea6ab482:function:fdsa:$LATEST + $BRN = explode(':', $Brn); + if ( !($BRN[0]=='brn' && $BRN[1]=='bce' && $BRN[2]=='cfc') ) { + $tmp['code'] = 'BRN Error'; + $tmp['message'] = 'The BRN expect start with "brn:bce:cfc:", given: ' . $Brn . ' .'; + return json_encode($tmp); + } + $Region = $BRN[3]; + //$project_id = $BRN[4]; + $FunctionName = $BRN[6]; + $host = 'cfc.' . $Region . '.baidubce.com'; + date_default_timezone_set('UTC'); // unset last timezone setting + $timestamp = date('Y-m-d\TH:i:s\Z'); + //date_default_timezone_set(get_timezone($_SERVER['timezone'])); + $authStringPrefix = 'bce-auth-v1/' . $AccessKey . '/' . $timestamp . '/1800' ; + $path = '/v1/functions/' . $FunctionName . '/' . $End; + $CanonicalURI = spurlencode($path, '/'); + $CanonicalQueryString = ''; + $CanonicalHeaders = 'host:' . $host; + $CanonicalRequest = $Method . "\n" . $CanonicalURI . "\n" . $CanonicalQueryString . "\n" . $CanonicalHeaders; + $SigningKey = hash_hmac('sha256', $authStringPrefix, $SecretKey); + $Signature = hash_hmac('sha256', $CanonicalRequest, $SigningKey); + $authorization = $authStringPrefix . '/host/' . $Signature; + + $p = 0; + while ($response['stat']==0 && $p<3) { + $response = curl( + $Method, + 'https://' . $host . $path, + $data, + [ + 'Authorization' => $authorization, + 'Content-type' => 'application/json' + ] + ); + $p++; + } + + if ($response['stat']==0) { + $tmp['code'] = 'Network Error'; + $tmp['message'] = 'Can not connect ' . $host; + return json_encode($tmp); + } + if ($response['stat']!=200) { + $tmp = json_decode($response['body'], true); + $tmp['message'] .= '
' . $response['stat'] . '
' . $timestamp . PHP_EOL; + return json_encode($tmp); + } + return $response['body']; +} + +function getfunctioninfo($SecretId, $SecretKey) +{ + return CFCAPIv1($_SERVER['functionBrn'], $SecretId, $SecretKey, 'GET', 'configuration'); +} + +function updateEnvironment($Envs, $SecretId, $SecretKey) +{ + $FunctionConfig = json_decode(getfunctioninfo($SecretId, $SecretKey), true); + $tmp_env = $FunctionConfig['Environment']['Variables']; + foreach ($Envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + //ksort($tmp_env); + sortConfig($tmp_env); + + $tmp['Environment']['Variables'] = $tmp_env; + $data = json_encode($tmp); + + return CFCAPIv1($_SERVER['functionBrn'], $SecretId, $SecretKey, 'PUT', 'configuration', $data); +} + +function SetbaseConfig($Envs, $SecretId, $SecretKey) +{ + $FunctionConfig = json_decode(getfunctioninfo($SecretId, $SecretKey), true); + $tmp_env = $FunctionConfig['Environment']['Variables']; + foreach ($Envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + ksort($tmp_env); + + $tmp['Timeout'] = 30; + $tmp['Description'] = 'Onedrive index and manager in Baidu CFC.'; + $tmp['Environment']['Variables'] = $tmp_env; + $data = json_encode($tmp); + + return CFCAPIv1($_SERVER['functionBrn'], $SecretId, $SecretKey, 'PUT', 'configuration', $data); +} + +function updateProgram($SecretId, $SecretKey, $source) +{ + $tmp['ZipFile'] = base64_encode( file_get_contents($source) ); + $data = json_encode($tmp); + return CFCAPIv1($_SERVER['functionBrn'], $SecretId, $SecretKey, 'PUT', 'code', $data); +} + +function api_error($response) +{ + //return isset($response['code']); + return !(isset($response['FunctionBrn']) && $response['FunctionBrn'] == $_SERVER['functionBrn']); +} + +function api_error_msg($response) +{ + if (isset($response['code'])) $html = $response['code'] . '
+' . $response['message']; + else $html = json_encode($response, JSON_PRETTY_PRINT); + return $html . '

+BRN: ' . $_SERVER['functionBrn'] . '
+'; +} + +function setConfigResponse($response) +{ + //return $response; + return json_decode( $response, true ); +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + $source = '/tmp/code.zip'; + $outPath = '/tmp/'; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return json_encode(['FunctionBrn'=>$_SERVER['functionBrn'], 'code'=>'Git Source input Error!']); + $tarfile = '/tmp/github.tar.gz'; + file_put_contents($tarfile, file_get_contents($url)); + $phar = new PharData($tarfile); + $html = $phar->extractTo($outPath, null, true);//路径 要解压的文件 是否覆盖 + + // 获取解压出的目录名 + $outPath = findIndexPath($outPath); + + // 将目录中文件打包成zip + //$zip=new ZipArchive(); + $zip=new PharData($source); + //if($zip->open($source, ZipArchive::CREATE)){ + addFileToZip($zip, $outPath); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 + // $zip->close(); //关闭处理的zip文件 + //} + + return updateProgram(getConfig('SecretId'), getConfig('SecretKey'), $source); +} + +function addFileToZip($zip, $rootpath, $path = '') +{ + if (substr($rootpath,-1)=='/') $rootpath = substr($rootpath, 0, -1); + if (substr($path,0,1)=='/') $path = substr($path, 1); + $handler=opendir(path_format($rootpath.'/'.$path)); //打开当前文件夹由$path指定。 + while($filename=readdir($handler)){ + if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作 + $nowname = path_format($rootpath.'/'.$path."/".$filename); + if(is_dir($nowname)){// 如果读取的某个对象是文件夹,则递归 + $zip->addEmptyDir($path."/".$filename); + addFileToZip($zip, $rootpath, $path."/".$filename); + }else{ //将文件加入zip对象 + $newname = $path."/".$filename; + if (substr($newname,0,1)=='/') $newname = substr($newname, 1); + $zip->addFile($nowname, $newname); + //$zip->renameName($nowname, $newname); + } + } + } + @closedir($handler); +} + +function WaitFunction() { + return true; +} + +function changeAuthKey() { + if ($_POST['SecretId']!=''&&$_POST['SecretKey']!='') { + $SecretId = $_POST['SecretId']; + $tmp['SecretId'] = $SecretId; + $SecretKey = $_POST['SecretKey']; + $tmp['SecretKey'] = $SecretKey; + $response = setConfigResponse(SetbaseConfig($tmp, $SecretId, $SecretKey)); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + $html = ' +
+ ' . getconstStr('Create') . ' Access Key & Secret Key
+
+
+ +
+ '; + return message($html, 'Change platform Auth token or key', 200); +} + +function smallfileupload($drive, $path) { + return output('Can not upload through CFC.', 400); +} diff --git a/platform/Heroku.php b/platform/Heroku.php new file mode 100644 index 0000000..fe0fc4e --- /dev/null +++ b/platform/Heroku.php @@ -0,0 +1,423 @@ +'; + $stat = 201; + } + //return message($html, $title, $stat); + } + $_SERVER['firstacceptlanguage'] = strtolower(splitfirst(splitfirst($_SERVER['HTTP_ACCEPT_LANGUAGE'],';')[0],',')[0]); + $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_FORWARDED_FOR']; + $_SERVER['REQUEST_SCHEME'] = $_SERVER['HTTP_X_FORWARDED_PROTO']; + $_SERVER['host'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']; + $_SERVER['referhost'] = explode('/', $_SERVER['HTTP_REFERER'])[2]; + $_SERVER['base_path'] = path_format(substr($_SERVER['SCRIPT_NAME'], 0, -10) . '/'); + $p = strpos($_SERVER['REQUEST_URI'],'?'); + if ($p>0) $path = substr($_SERVER['REQUEST_URI'], 0, $p); + else $path = $_SERVER['REQUEST_URI']; + $path = path_format( substr($path, strlen($_SERVER['base_path'])) ); + return substr($path, 1); + //return spurlencode($path, '/'); +} + +function getGET() +{ + //error_log1('POST:' . json_encode($_POST)); + if (!$_POST) { + if (!!$HTTP_RAW_POST_DATA) { + $tmpdata = $HTTP_RAW_POST_DATA; + //error_log1('RAW:' . $tmpdata); + } else { + $tmpdata = file_get_contents('php://input'); + //error_log1('PHPINPUT:' . $tmpdata); + } + if (!!$tmpdata) { + $postbody = explode("&", $tmpdata); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + //error_log1('POSTformPHPINPUT:' . json_encode($_POST)); + } + } + $p = strpos($_SERVER['REQUEST_URI'],'?'); + if ($p>0) { + $getstr = substr($_SERVER['REQUEST_URI'], $p+1); + $getstrarr = explode("&",$getstr); + foreach ($getstrarr as $getvalues) { + if ($getvalues != '') { + $pos = strpos($getvalues, "="); + //echo $pos; + if ($pos > 0) { + $getarry[urldecode(substr($getvalues, 0, $pos))] = urldecode(substr($getvalues, $pos + 1)); + } else { + $getarry[urldecode($getvalues)] = true; + } + } + } + } + if (isset($getarry)) { + return $getarry; + } else { + return []; + } +} + +function getConfig($str, $disktag = '') +{ + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + $env = json_decode(getenv($disktag), true); + if (isset($env[$str])) { + if (isBase64Env($str)) return base64y_decode($env[$str]); + else return $env[$str]; + } + } else { + if (isBase64Env($str)) return base64y_decode(getenv($str)); + else return getenv($str); + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + if ($disktag=='') $disktag = $_SERVER['disktag']; + $disktags = explode("|",getConfig('disktag')); + if ($disktag!='') $diskconfig = json_decode(getenv($disktag), true); + $tmp = []; + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $tmp[$k] = base64y_encode($v); + else $tmp[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $diskconfig[$k] = base64y_encode($v); + else $diskconfig[$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $tmp[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $tmp[$newtag] = getConfig($v); + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $tmp[$k] = json_encode($v); + } + } + if ($indisk) { + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $tmp[$disktag] = json_encode($diskconfig); + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $tmp['disktag'] = implode('|', $tags); + $tmp[$arr['disktag_newname']] = getConfig($arr['disktag_rename']); + $tmp[$arr['disktag_rename']] = null; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $tmp['disktag'] = substr($disktag_s, 0, -1); + else $tmp['disktag'] = null; + } + } + foreach ($tmp as $key => $val) if ($val=='') $tmp[$key]=null; + + return setHerokuConfig($tmp, getConfig('HerokuappId'), getConfig('APIKey')); + error_log1(json_encode($arr, JSON_PRETTY_PRINT) . ' => tmp:' . json_encode($tmp, JSON_PRETTY_PRINT)); +} + +function install() +{ + global $constStr; + if ($_GET['install1']) { + if ($_POST['admin']!='') { + $tmp['admin'] = $_POST['admin']; + //$tmp['language'] = $_POST['language']; + $tmp['timezone'] = $_COOKIE['timezone']; + $APIKey = $_POST['APIKey']; + $tmp['APIKey'] = $APIKey; + $HerokuappId = getConfig('HerokuappId'); + if ($HerokuappId=='') { + $function_name = getConfig('function_name'); + if ($function_name=='') { + $tmp1 = substr($_SERVER['HTTP_HOST'], 0, strrpos($_SERVER['HTTP_HOST'], '.')); + $maindomain = substr($tmp1, strrpos($tmp1, '.')+1); + if ($maindomain=='herokuapp') $function_name = substr($tmp1, 0, strrpos($tmp1, '.')); + else return message('Please visit from xxxx.herokuapp.com', '', 500); + $res = HerokuAPI('GET', 'https://api.heroku.com/apps/' . $function_name, '', $APIKey); + $response = json_decode($res['body'], true); + if (isset($response['build_stack'])) { + $HerokuappId = $response['id']; + } else { + return message('Get Heroku app id: ' . json_encode($res, JSON_PRETTY_PRINT), 'Something error', 500); + } + } + } + $tmp['HerokuappId'] = $HerokuappId; + $response = json_decode(setHerokuConfig($tmp, $HerokuappId, $APIKey)['body'], true); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + $html .= ' + ' . getconstStr('Create') . ' API Key
+
'; + $html .= ' +
'; + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + $html .= ''.getconstStr('ClickInstall').', '.getconstStr('LogintoBind'); + $title = 'Install'; + return message($html, $title, 201); +} + +function HerokuAPI($method, $url, $data = '', $apikey) +{ + if ($method=='PATCH'||$method=='POST') { + $headers['Content-Type'] = 'application/json'; + } + $headers['Authorization'] = 'Bearer ' . $apikey; + $headers['Accept'] = 'application/vnd.heroku+json; version=3'; + //if (!isset($headers['Accept'])) $headers['Accept'] = '*/*'; + //if (!isset($headers['Referer'])) $headers['Referer'] = $url; + $sendHeaders = array(); + foreach ($headers as $headerName => $headerVal) { + $sendHeaders[] = $headerName . ': ' . $headerVal; + } + error_log1($method . $url . $data . $apikey); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST,$method); + curl_setopt($ch, CURLOPT_POSTFIELDS,$data); + curl_setopt($ch, CURLOPT_TIMEOUT, 5); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders); + $response['body'] = curl_exec($ch); + $response['stat'] = curl_getinfo($ch,CURLINFO_HTTP_CODE); + curl_close($ch); + error_log1($response['stat'].' +'.$response['body'].' +'); + return $response; +} + +function getHerokuConfig($HerokuappId, $apikey) +{ + return HerokuAPI('GET', 'https://api.heroku.com/apps/' . $HerokuappId . '/config-vars', '', $apikey); +} + +function setHerokuConfig($env, $HerokuappId, $apikey) +{ + $data = json_encode($env); + if (substr($data, 0, 1)=='{') return HerokuAPI('PATCH', 'https://api.heroku.com/apps/' . $HerokuappId . '/config-vars', $data, $apikey); +} + +function updateHerokuapp($HerokuappId, $apikey, $source) +{ + $tmp['source_blob']['url'] = $source; + $data = json_encode($tmp); + $response = HerokuAPI('POST', 'https://api.heroku.com/apps/' . $HerokuappId . '/builds', $data, $apikey); + $result = json_decode( $response['body'], true ); + $result['DplStatus'] = $result['id']; + $response['body'] = json_encode($result); + return $response; +} + +function api_error($response) +{ + return isset($response['id'])&&isset($response['message']); +} + +function api_error_msg($response) +{ + return $response['id'] . '
+' . $response['message'] . '

+function_name:' . $_SERVER['function_name'] . '
+'; +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + if ($GitSource=='Github') { + //'https://github.com/qkqpttgf/OneManager-php/tarball/master/'; + $source = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $source = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return ['stat'=>403, 'body'=>json_encode(['id'=>'Error', 'message'=>'Git Source input Error!'])]; + + return updateHerokuapp(getConfig('HerokuappId'), getConfig('APIKey'), $source); +} + +function setConfigResponse($response) +{ + return json_decode( $response['body'], true ); +} + +function WaitFunction($buildId = '') { + // GET /apps/{app_id_or_name}/builds/{build_id} + if ($buildId=='1') return true; + $response = HerokuAPI('GET', 'https://api.heroku.com/apps/' . getConfig('HerokuappId') . '/builds/' . $buildId, '', getConfig('APIKey')); + if ($response['stat']==200) { + $result = json_decode($response['body'], true); + if ($result['status']=="succeeded") return true; + else return false; + } else { + $response['body'] .= $url; + return $response; + } +} + +function changeAuthKey() { + if ($_POST['APIKey']!='') { + $APIKey = $_POST['APIKey']; + $tmp['APIKey'] = $APIKey; + $response = setConfigResponse( setHerokuConfig($tmp, getConfig('HerokuappId'), $APIKey) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + $html = ' +
+ '.getconstStr('Create').' API Key
+
+ +
+ '; + return message($html, 'Change platform Auth token or key', 200); +} + +function smallfileupload($drive, $path) { + if ($_FILES['file1']['error']) return output($_FILES['file1']['error'], 400); + if ($_FILES['file1']['size']>4*1024*1024) return output('File too large', 400); + return $drive->smallfileupload($path, $_FILES['file1']); +} diff --git a/platform/HuaweiFG_env.php b/platform/HuaweiFG_env.php new file mode 100644 index 0000000..f3c76c7 --- /dev/null +++ b/platform/HuaweiFG_env.php @@ -0,0 +1,542 @@ +geteventID(); + $tmp['RemainingTimeInMilliSeconds'] = $context->getRemainingTimeInMilliSeconds(); + $tmp['AccessKey'] = $context->getAccessKey(); + $tmp['SecretKey'] = $context->getSecretKey(); + $tmp['UserData']['HW_urn'] = $context->getUserData('HW_urn'); + $tmp['FunctionName'] = $context->getFunctionName(); + $tmp['RunningTimeInSeconds'] = $context->getRunningTimeInSeconds(); + $tmp['Version'] = $context->getVersion(); + $tmp['MemorySize'] = $context->getMemorySize(); + $tmp['CPUNumber'] = $context->getCPUNumber(); + $tmp['ProjectID'] = $context->getProjectID(); + $tmp['Package'] = $context->Package(); + $tmp['Token'] = $context->getToken(); + $tmp['Logger'] = $context->getLogger(); + + if (strlen(json_encode($event['body']))>500) $event['body']=substr($event['body'],0,strpos($event['body'],'base64')+30) . '...Too Long!...' . substr($event['body'],-50); + echo urldecode(json_encode($event, JSON_PRETTY_PRINT)) . ' + +' . urldecode(json_encode($tmp, JSON_PRETTY_PRINT)) . ' + +'; +} + +function GetGlobalVariable($event) +{ + $_GET = $event['queryStringParameters']; + $postbody = explode("&",$event['body']); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + $cookiebody = explode("; ",$event['headers']['cookie']); + foreach ($cookiebody as $cookievalues) { + $pos = strpos($cookievalues,"="); + $_COOKIE[urldecode(substr($cookievalues,0,$pos))]=urldecode(substr($cookievalues,$pos+1)); + } +} + +function GetPathSetting($event, $context) +{ + $_SERVER['firstacceptlanguage'] = strtolower(splitfirst(splitfirst($event['headers']['accept-language'],';')[0],',')[0]); + $_SERVER['function_name'] = $context->getFunctionName(); + $_SERVER['ProjectID'] = $context->getProjectID(); + $host_name = $event['headers']['host']; + $_SERVER['HTTP_HOST'] = $host_name; + $path = path_format($event['pathParameters'][''].'/'); + $path = str_replace('+', '%2B', $path); + $_SERVER['base_path'] = path_format($event['path'].'/'); + if ( $_SERVER['base_path'] == $path ) { + $_SERVER['base_path'] = '/'; + } else { + $_SERVER['base_path'] = substr($_SERVER['base_path'], 0, -strlen($path)); + if ($_SERVER['base_path']=='') $_SERVER['base_path'] = '/'; + } + //$_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path); + $_SERVER['REMOTE_ADDR'] = $event['headers']['x-real-ip']; + $_SERVER['HTTP_X_REQUESTED_WITH'] = $event['headers']['x-requested-with']; + $_SERVER['HTTP_USER_AGENT'] = $event['headers']['user-agent']; + if (isset($event['headers']['authorization'])) { + $basicAuth = splitfirst(base64_decode(splitfirst($event['headers']['authorization'], 'Basic ')[1]), ':'); + $_SERVER['PHP_AUTH_USER'] = $basicAuth[0]; + $_SERVER['PHP_AUTH_PW'] = $basicAuth[1]; + } + $_SERVER['REQUEST_SCHEME'] = $event['headers']['x-forwarded-proto']; + $_SERVER['host'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']; + $_SERVER['referhost'] = explode('/', $event['headers']['referer'])[2]; + $_SERVER['HTTP_TRANSLATE'] = $event['headers']['translate'];//'f' + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $event['headers']['if-modified-since']; + $_SERVER['REQUEST_METHOD'] = $event['httpMethod']; + $_SERVER['_APP_SHARE_DIR'] = '/var/share/CFF/processrouter'; + return $path; +} + +function getConfig($str, $disktag = '') +{ + global $contextUserData; + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + $env = json_decode($contextUserData->getUserData($disktag), true); + if (isset($env[$str])) { + if (isBase64Env($str)) return base64y_decode($env[$str]); + else return $env[$str]; + } + } else { + if (isBase64Env($str)) return base64y_decode($contextUserData->getUserData($str)); + else return $contextUserData->getUserData($str); + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + global $contextUserData; + if ($disktag=='') $disktag = $_SERVER['disktag']; + $disktags = explode("|",getConfig('disktag')); + $diskconfig = json_decode($contextUserData->getUserData($disktag), true); + $tmp = []; + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $tmp[$k] = base64y_encode($v); + else $tmp[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $diskconfig[$k] = base64y_encode($v); + else $diskconfig[$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $tmp[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $tmp[$newtag] = getConfig($v); + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $tmp[$k] = json_encode($v); + } + } + if ($indisk) { + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $tmp[$disktag] = json_encode($diskconfig); + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $tmp['disktag'] = implode('|', $tags); + $tmp[$arr['disktag_newname']] = getConfig($arr['disktag_rename']); + $tmp[$arr['disktag_rename']] = ''; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $tmp['disktag'] = substr($disktag_s, 0, -1); + else $tmp['disktag'] = ''; + } + } +// echo '正式设置:'.json_encode($tmp,JSON_PRETTY_PRINT).' +//'; + $response = updateEnvironment($tmp, getConfig('HW_urn'), getConfig('HW_key'), getConfig('HW_secret')); + return $response; +} + +function install() +{ + global $constStr; + global $contextUserData; + if ($_GET['install2']) { + $tmp['admin'] = $_POST['admin']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } + if (needUpdate()) { + OnekeyUpate(); + return message('update to github version, reinstall. + + ', 'Program updating', 201); + } + return output('Jump + + ', 302); + } + if ($_GET['install1']) { + //if ($_POST['admin']!='') { + $tmp['timezone'] = $_COOKIE['timezone']; + $tmp['HW_urn'] = $_POST['HW_urn']; + $tmp['HW_key'] = $_POST['HW_key']; + $tmp['HW_secret'] = $_POST['HW_secret']; + $tmp['ONEMANAGER_CONFIG_SAVE'] = $_POST['ONEMANAGER_CONFIG_SAVE']; + //$response = json_decode(SetbaseConfig($tmp, $HW_urn, $HW_name, $HW_pwd), true)['Response']; + $response = setConfigResponse( SetbaseConfig($tmp, $tmp['HW_urn'], $tmp['HW_key'], $tmp['HW_secret']) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + if ($tmp['ONEMANAGER_CONFIG_SAVE'] == 'file') { + $html = getconstStr('ONEMANAGER_CONFIG_SAVE_FILE') . '
' . getconstStr('Home') . ''; + $title = 'Reinstall'; + return message($html, $title, 201); + } + $html .= ' +
+
+ +
+ '; + $title = getconstStr('SetAdminPassword'); + return message($html, $title, 201); + } + //} + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + //if (getConfig('HW_urn')==''||getConfig('HW_key')==''||getConfig('HW_secret')=='') + $html .= ' + 在函数代码操作页上方找到URN,鼠标放上去后显示URN,复制填入:
+
+ 点击链接,新增访问密钥, + 在下载的credentials.csv文件中找到对应信息,填入:
+
+
'; + $html .= ' +
+
'; + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + $html .= ''.getconstStr('ClickInstall').', '.getconstStr('LogintoBind'); + $title = 'Install'; + return message($html, $title, 201); +} + +function FGAPIV2($HW_urn, $HW_key, $HW_secret, $Method, $End, $data = '') +{ + if ($HW_urn==''||$HW_key==''||$HW_secret=='') { + $tmp['error_code'] = 'Config Error'; + $tmp['error_msg'] = 'HW urn or access key id or secret is empty.'; + return json_encode($tmp); + } + + $URN = explode(':', $HW_urn); + $Region = $URN[2]; + $project_id = $URN[3]; + + $host = 'functiongraph.' . $Region . '.myhuaweicloud.com'; + $path = '/v2/' . $project_id . '/fgs/functions/' . $HW_urn . '/' . $End; + $url = 'https://' . $host . $path; + $CanonicalURI = spurlencode($path, '/') . '/'; + $CanonicalQueryString = ''; + + date_default_timezone_set('UTC'); // unset last timezone setting + $timestamp = date('Ymd\THis\Z'); + $header['X-Sdk-Date'] = $timestamp; + $header['Host'] = $host; + $header['Content-Type'] = 'application/json;charset=utf8'; + ksort($header); + $CanonicalHeaders = ''; + $SignedHeaders = ''; + foreach ($header as $key => $value) { + $CanonicalHeaders .= strtolower($key) . ':' . $value . "\n"; + $SignedHeaders .= strtolower($key) . ';'; + } + $SignedHeaders = substr($SignedHeaders, 0, -1); + $Hashedbody = hash("sha256", $data); + $CanonicalRequest = $Method . "\n" . $CanonicalURI . "\n" . $CanonicalQueryString . "\n" . $CanonicalHeaders . "\n" . $SignedHeaders . "\n" . $Hashedbody; + $HashedCanonicalRequest = hash("sha256", $CanonicalRequest); + $Algorithm = 'SDK-HMAC-SHA256'; + $StringToSign = $Algorithm . "\n" . $timestamp . "\n" . $HashedCanonicalRequest; + $signature = hash_hmac("sha256", $StringToSign, $HW_secret); + $Authorization = "$Algorithm Access=$HW_key, SignedHeaders=$SignedHeaders, Signature=$signature"; + $header['Authorization'] = $Authorization; + + //return curl($Method, $url, $data, $header)['body']; // . $CanonicalRequest; + $p = 0; + while ($response['stat']==0 && $p<3) { + $response = curl($Method, $url, $data, $header); + $p++; + } + + if ($response['stat']==0) { + $tmp['error_code'] = 'Network Error'; + $tmp['error_msg'] = 'Can not connect ' . $host; + return json_encode($tmp); + } + if ($response['stat']!=200) { + $tmp = json_decode($response['body'], true); + $tmp['error_code'] .= '.'; + $tmp['error_msg'] .= '
' . $response['stat'] . '
' . $CanonicalRequest . '
' . json_encode($header) . PHP_EOL; + return json_encode($tmp); + } + return $response['body']; +} + +function getfunctioninfo($HW_urn, $HW_key, $HW_secret) +{ + return FGAPIV2($HW_urn, $HW_key, $HW_secret, 'GET', 'config'); +} + +function updateEnvironment($Envs, $HW_urn, $HW_key, $HW_secret) +{ + //echo json_encode($Envs,JSON_PRETTY_PRINT); + global $contextUserData; + $tmp_env = json_decode(json_decode(getfunctioninfo($HW_urn, $HW_key, $HW_secret),true)['user_data'],true); + foreach ($Envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + //ksort($tmp_env); + sortConfig($tmp_env); + + $tmpdata['handler'] = 'index.handler'; + $tmpdata['memory_size'] = $contextUserData->getMemorySize()+1-1; + $tmpdata['runtime'] = 'PHP7.3'; + $tmpdata['timeout'] = $contextUserData->getRunningTimeInSeconds()+1-1; + $tmpdata['user_data'] = json_encode($tmp_env); + + return FGAPIV2($HW_urn, $HW_key, $HW_secret, 'PUT', 'config', json_encode($tmpdata)); +} + +function SetbaseConfig($Envs, $HW_urn, $HW_key, $HW_secret) +{ + //echo json_encode($Envs,JSON_PRETTY_PRINT); + if ($Envs['ONEMANAGER_CONFIG_SAVE'] == 'file') $Envs = Array( 'ONEMANAGER_CONFIG_SAVE' => 'file' ); + $tmp_env = json_decode(json_decode(getfunctioninfo($HW_urn, $HW_key, $HW_secret),true)['user_data'],true); + foreach ($Envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + ksort($tmp_env); + + $tmpdata['handler'] = 'index.handler'; + $tmpdata['memory_size'] = 128; + $tmpdata['runtime'] = 'PHP7.3'; + $tmpdata['timeout'] = 30; + $tmpdata['description'] = 'Onedrive index and manager in Huawei FG.'; + $tmpdata['user_data'] = json_encode($tmp_env); + + return FGAPIV2($HW_urn, $HW_key, $HW_secret, 'PUT', 'config', json_encode($tmpdata)); +} + +function updateProgram($HW_urn, $HW_key, $HW_secret, $source) +{ + $tmpdata['code_type'] = 'zip'; + $tmpdata['func_code']['file'] = base64_encode( file_get_contents($source) ); + + return FGAPIV2($HW_urn, $HW_key, $HW_secret, 'PUT', 'code', json_encode($tmpdata)); +} + +function api_error($response) +{ + return isset($response['error_msg']); +} + +function api_error_msg($response) +{ + return $response['error_code'] . '
+' . $response['error_msg'] . '
+request_id: ' . $response['request_id'] . '

+function_name: ' . $_SERVER['function_name'] . '
+'; +} + +function setConfigResponse($response) +{ + return json_decode( $response, true ); +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + $source = '/tmp/code.zip'; + $outPath = '/tmp/'; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return json_encode(['error_code'=>'Error', 'error_msg'=>'Git Source input Error!']); + $tarfile = '/tmp/github.tar.gz'; + file_put_contents($tarfile, file_get_contents($url)); + $phar = new PharData($tarfile); + $html = $phar->extractTo($outPath, null, true);//路径 要解压的文件 是否覆盖 + + // 获取解压出的目录名 + $outPath = findIndexPath($outPath); + + // 将目录中文件打包成zip + //$zip=new ZipArchive(); + $zip=new PharData($source); + //if($zip->open($source, ZipArchive::CREATE)){ + addFileToZip($zip, $outPath); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 + // $zip->close(); //关闭处理的zip文件 + //} + + return updateProgram(getConfig('HW_urn'), getConfig('HW_key'), getConfig('HW_secret'), $source); +} + +function addFileToZip($zip, $rootpath, $path = '') +{ + if (substr($rootpath,-1)=='/') $rootpath = substr($rootpath, 0, -1); + if (substr($path,0,1)=='/') $path = substr($path, 1); + $handler=opendir(path_format($rootpath.'/'.$path)); //打开当前文件夹由$path指定。 + while($filename=readdir($handler)){ + if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作 + $nowname = path_format($rootpath.'/'.$path."/".$filename); + if(is_dir($nowname)){// 如果读取的某个对象是文件夹,则递归 + $zip->addEmptyDir($path."/".$filename); + addFileToZip($zip, $rootpath, $path."/".$filename); + }else{ //将文件加入zip对象 + $newname = $path."/".$filename; + if (substr($newname,0,1)=='/') $newname = substr($newname, 1); + $zip->addFile($nowname, $newname); + //$zip->renameName($nowname, $newname); + } + } + } + @closedir($handler); +} + +function WaitFunction() { + return true; +} + +function changeAuthKey() { + if ($_POST['HW_key']!=''&&$_POST['HW_secret']!='') { + $tmp['HW_key'] = $_POST['HW_key']; + $tmp['HW_secret'] = $_POST['HW_secret']; + $response = setConfigResponse( SetbaseConfig($tmp, getConfig('HW_urn'), $tmp['HW_key'], $tmp['HW_secret']) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + $html = ' +
+ 点击链接,新增访问密钥, + 在下载的credentials.csv文件中找到对应信息,填入:
+
+
+ +
+ '; + return message($html, 'Change platform Auth token or key', 200); +} + +function smallfileupload($drive, $path) { + return output('Can not upload through FG.', 400); +} diff --git a/platform/HuaweiFG_file.php b/platform/HuaweiFG_file.php new file mode 100644 index 0000000..3fbecb0 --- /dev/null +++ b/platform/HuaweiFG_file.php @@ -0,0 +1,908 @@ +geteventID(); + $tmp['RemainingTimeInMilliSeconds'] = $context->getRemainingTimeInMilliSeconds(); + $tmp['AccessKey'] = $context->getAccessKey(); + $tmp['SecretKey'] = $context->getSecretKey(); + $tmp['UserData']['HW_urn'] = $context->getUserData('HW_urn'); + $tmp['FunctionName'] = $context->getFunctionName(); + $tmp['RunningTimeInSeconds'] = $context->getRunningTimeInSeconds(); + $tmp['Version'] = $context->getVersion(); + $tmp['MemorySize'] = $context->getMemorySize(); + $tmp['CPUNumber'] = $context->getCPUNumber(); + $tmp['ProjectID'] = $context->getProjectID(); + $tmp['Package'] = $context->Package(); + $tmp['Token'] = $context->getToken(); + $tmp['Logger'] = $context->getLogger(); + + if (strlen(json_encode($event['body']))>500) $event['body']=substr($event['body'],0,strpos($event['body'],'base64')+30) . '...Too Long!...' . substr($event['body'],-50); + echo urldecode(json_encode($event, JSON_PRETTY_PRINT)) . ' + +' . urldecode(json_encode($tmp, JSON_PRETTY_PRINT)) . ' + +'; +} + +function GetGlobalVariable($event) +{ + $_GET = $event['queryStringParameters']; + $postbody = explode("&",$event['body']); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + $cookiebody = explode("; ",$event['headers']['cookie']); + foreach ($cookiebody as $cookievalues) { + $pos = strpos($cookievalues,"="); + $_COOKIE[urldecode(substr($cookievalues,0,$pos))]=urldecode(substr($cookievalues,$pos+1)); + } +} + +function GetPathSetting($event, $context) +{ + $_SERVER['firstacceptlanguage'] = strtolower(splitfirst(splitfirst($event['headers']['accept-language'],';')[0],',')[0]); + $_SERVER['function_name'] = $context->getFunctionName(); + $_SERVER['ProjectID'] = $context->getProjectID(); + $host_name = $event['headers']['host']; + $_SERVER['HTTP_HOST'] = $host_name; + $path = path_format($event['pathParameters'][''].'/'); + $path = str_replace('+', '%2B', $path); + $_SERVER['base_path'] = path_format($event['path'].'/'); + if ( $_SERVER['base_path'] == $path ) { + $_SERVER['base_path'] = '/'; + } else { + $_SERVER['base_path'] = substr($_SERVER['base_path'], 0, -strlen($path)); + if ($_SERVER['base_path']=='') $_SERVER['base_path'] = '/'; + } + //$_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path); + $_SERVER['REMOTE_ADDR'] = $event['headers']['x-real-ip']; + $_SERVER['HTTP_X_REQUESTED_WITH'] = $event['headers']['x-requested-with']; + $_SERVER['HTTP_USER_AGENT'] = $event['headers']['user-agent']; + if (isset($event['headers']['authorization'])) { + $basicAuth = splitfirst(base64_decode(splitfirst($event['headers']['authorization'], 'Basic ')[1]), ':'); + $_SERVER['PHP_AUTH_USER'] = $basicAuth[0]; + $_SERVER['PHP_AUTH_PW'] = $basicAuth[1]; + } + $_SERVER['REQUEST_SCHEME'] = $event['headers']['x-forwarded-proto']; + $_SERVER['host'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']; + $_SERVER['referhost'] = explode('/', $event['headers']['referer'])[2]; + $_SERVER['HTTP_TRANSLATE'] = $event['headers']['translate'];//'f' + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $event['headers']['if-modified-since']; + $_SERVER['REQUEST_METHOD'] = $event['httpMethod']; + $_SERVER['_APP_SHARE_DIR'] = '/var/share/CFF/processrouter'; + return $path; +} + +function getConfig($str, $disktag = '') +{ + $projectPath = splitlast(__DIR__, '/')[0]; + $configPath = $projectPath . '/.data/config.php'; + $s = file_get_contents($configPath); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') { + $envs = json_decode($configs, true); + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + if (isset($envs[$disktag][$str])) { + if (isBase64Env($str)) return base64y_decode($envs[$disktag][$str]); + else return $envs[$disktag][$str]; + } + } else { + if (isset($envs[$str])) { + if (isBase64Env($str)) return base64y_decode($envs[$str]); + else return $envs[$str]; + } + } + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + + if ($disktag=='') $disktag = $_SERVER['disktag']; + $projectPath = splitlast(__DIR__, '/')[0]; + $configPath = $projectPath . '/.data/config.php'; + $s = file_get_contents($configPath); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') $envs = json_decode($configs, true); + $disktags = explode("|",getConfig('disktag')); + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $envs[$k] = base64y_encode($v); + else $envs[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $envs[$disktag][$k] = base64y_encode($v); + else $envs[$disktag][$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $envs[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $envs[$newtag] = $envs[$v]; + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $envs[$k] = $v; + } + } + if ($indisk) { + $diskconfig = $envs[$disktag]; + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $envs[$disktag] = $diskconfig; + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $envs['disktag'] = implode('|', $tags); + $envs[$arr['disktag_newname']] = $envs[$arr['disktag_rename']]; + $envs[$arr['disktag_rename']] = ''; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $envs['disktag'] = substr($disktag_s, 0, -1); + else $envs['disktag'] = ''; + } + } + $envs = array_filter($envs, 'array_value_isnot_null'); + //ksort($envs); + $response = updateEnvironment($envs, getConfig('HW_urn'), getConfig('HW_key'), getConfig('HW_secret')); + return $response; +} + +function install() +{ + global $constStr; + global $contextUserData; + if ($_GET['install2']) { + $tmp['admin'] = $_POST['admin']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } + if (needUpdate()) { + OnekeyUpate(); + return message('update to github version, reinstall. + + ', 'Program updating', 201); + } + return output('Jump + + ', 302); + } + if ($_GET['install1']) { + //if ($_POST['admin']!='') { + $tmp['timezone'] = $_COOKIE['timezone']; + $tmp['HW_urn'] = $_POST['HW_urn']; + $tmp['HW_key'] = $_POST['HW_key']; + $tmp['HW_secret'] = $_POST['HW_secret']; + $tmp['ONEMANAGER_CONFIG_SAVE'] = $_POST['ONEMANAGER_CONFIG_SAVE']; + //return message($html, $title, 201); + $response = setConfigResponse( SetbaseConfig($tmp, $tmp['HW_urn'], $tmp['HW_key'], $tmp['HW_secret']) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + if ($tmp['ONEMANAGER_CONFIG_SAVE'] != 'file') { + $html = getconstStr('ONEMANAGER_CONFIG_SAVE_ENV') . '
' . getconstStr('Home') . ''; + $title = 'Reinstall'; + return message($html, $title, 201); + } + $html .= ' +
+
+ +
+ '; + $title = getconstStr('SetAdminPassword'); + return message($html, $title, 201); + } + //} + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + //if (getConfig('HW_urn')==''||getConfig('HW_key')==''||getConfig('HW_secret')=='') + $html .= ' + 在函数代码操作页上方找到URN,鼠标放上去后显示URN,复制填入:
+
+ 点击链接,新增访问密钥, + 在下载的credentials.csv文件中找到对应信息,填入:
+
+
'; + $html .= ' +
+
'; + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + $html .= ''.getconstStr('ClickInstall').', '.getconstStr('LogintoBind'); + $title = 'Install'; + return message($html, $title, 201); +} + +function getfunctioninfo($HW_urn, $HW_key, $HW_secret) +{ + $URN = explode(':', $HW_urn); + $Region = $URN[2]; + $project_id = $URN[3]; + $url = 'https://functiongraph.' . $Region . '.myhuaweicloud.com/v2/' . $project_id . '/fgs/functions/' . $HW_urn . '/config'; + $signer = new Signer(); + $signer->Key = $HW_key; + $signer->Secret = $HW_secret; + $req = new Request('GET', $url); + $req->headers = array( + 'content-type' => 'application/json;charset=utf8', + ); + $req->body = ''; + $curl = $signer->Sign($req); + $response = curl_exec($curl); + $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close($curl); + return $response; +} + +function getfunctioncode($HW_urn, $HW_key, $HW_secret) +{ + $URN = explode(':', $HW_urn); + $Region = $URN[2]; + $project_id = $URN[3]; + $url = 'https://functiongraph.' . $Region . '.myhuaweicloud.com/v2/' . $project_id . '/fgs/functions/' . $HW_urn . '/code'; + $signer = new Signer(); + $signer->Key = $HW_key; + $signer->Secret = $HW_secret; + $req = new Request('GET', $url); + $req->headers = array( + 'content-type' => 'application/json;charset=utf8', + ); + $req->body = ''; + $curl = $signer->Sign($req); + $response = curl_exec($curl); + $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close($curl); + //return $response; + $url = json_decode($response, true)['func_code']['link']; + // return $url; + + + $bucket = splitfirst( splitfirst($url, '//')[1], '.')[0]; + $path = splitfirst( splitfirst($url, '//')[1], '/')[1]; + $date = gmdate('D, d M Y H:i:s') . ' GMT'; + //$date = 'Wed, 05 Aug 2020 06:34:50 GMT'; + $StringToSign = 'GET +' . ' +' . ' +' . ' +' . 'x-obs-date:' . $date . ' +' . '/' . $bucket . '/' . $path; + + $signature = base64_encode(hash_hmac('sha1', $StringToSign, $HW_secret, true)); + $response = curl('GET', $url, false, [ 'Authorization' => 'OBS ' . $HW_key . ':' . $signature, 'x-obs-date' => $date, 'Content-Type' => '' ]); + //if ($response['stat']==200) return $response['body']; + if ($response['stat']==0) return json_encode( [ 'error_code' => 'Network', 'error_msg' => 'Network error in getting code.' ] ); + else return $response['body']; +} + +function copyFolder($from, $to) +{ + if (substr($from, -1)=='/') $from = substr($from, 0, -1); + if (substr($to, -1)=='/') $to = substr($to, 0, -1); + if (!file_exists($to)) mkdir($to, 0777); + $handler=opendir($from); + while($filename=readdir($handler)) { + if($filename != '.' && $filename != '..'){ + $fromfile = $from.'/'.$filename; + $tofile = $to.'/'.$filename; + if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归 + copyFolder($fromfile, $tofile); + }else{ + copy($fromfile, $tofile); + } + } + } + closedir($handler); + return 1; +} + +function updateEnvironment($Envs, $HW_urn, $HW_key, $HW_secret) +{ + sortConfig($Envs); + //echo json_encode($Envs,JSON_PRETTY_PRINT); + $source = '/tmp/code.zip'; + $outPath = '/tmp/code/'; + $oldcode = '/tmp/oldcode.zip'; + + // 获取当前代码,并解压 + $coderoot = __DIR__ . '/../'; + + copyFolder($coderoot, $outPath); + + // 将配置写入 + $prestr = 'open($source, ZipArchive::CREATE)){ + addFileToZip($zip, $outPath); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 + // $zip->close(); //关闭处理的zip文件 + //} + + return updateProgram($HW_urn, $HW_key, $HW_secret, $source); +} + +function SetbaseConfig($Envs, $HW_urn, $HW_key, $HW_secret) +{ + //echo json_encode($Envs,JSON_PRETTY_PRINT); + if ($Envs['ONEMANAGER_CONFIG_SAVE'] == 'file') $envs = Array( 'ONEMANAGER_CONFIG_SAVE' => 'file' ); + else { + $Envs['ONEMANAGER_CONFIG_SAVE'] == ''; + $envs = $Envs; + $tmp_env = json_decode(json_decode(getfunctioninfo($HW_urn, $HW_key, $HW_secret),true)['user_data'],true); + foreach ($envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + ksort($tmp_env); + $envs = $tmp_env; + } + + // https://functiongraph.cn-north-4.myhuaweicloud.com/v2/{project_id}/fgs/functions/{function_urn}/config + $URN = explode(':', $HW_urn); + $Region = $URN[2]; + $project_id = $URN[3]; + $url = 'https://functiongraph.' . $Region . '.myhuaweicloud.com/v2/' . $project_id . '/fgs/functions/' . $HW_urn . '/config'; + $signer = new Signer(); + $signer->Key = $HW_key; + $signer->Secret = $HW_secret; + $req = new Request('PUT', $url); + $req->headers = array( + 'content-type' => 'application/json;charset=utf8', + ); + $tmpdata['handler'] = 'index.handler'; + $tmpdata['memory_size'] = 128; + $tmpdata['runtime'] = 'PHP7.3'; + $tmpdata['timeout'] = 30; + $tmpdata['description'] = 'Onedrive index and manager in Huawei FG.'; + $tmpdata['user_data'] = json_encode($envs); + $req->body = json_encode($tmpdata); + $curl = $signer->Sign($req); + $response = curl_exec($curl); + $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close($curl); + //return $response; + if (api_error(setConfigResponse($response))) { + return $response; + } + + $projectPath = splitlast(__DIR__, '/')[0]; + $configPath = $projectPath . '/.data/config.php'; + $s = file_get_contents($configPath); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') $tmp_env = json_decode($configs, true); + foreach ($Envs as $k => $v) { + $tmp_env[$k] = $v; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); + //ksort($tmp_env); + $response = updateEnvironment($tmp_env, $HW_urn, $HW_key, $HW_secret); + return $response; +} + +function updateProgram($HW_urn, $HW_key, $HW_secret, $source) +{ + $URN = explode(':', $HW_urn); + $Region = $URN[2]; + $project_id = $URN[3]; + $url = 'https://functiongraph.' . $Region . '.myhuaweicloud.com/v2/' . $project_id . '/fgs/functions/' . $HW_urn . '/code'; + $signer = new Signer(); + $signer->Key = $HW_key; + $signer->Secret = $HW_secret; + $req = new Request('PUT', $url); + $req->headers = array( + 'content-type' => 'application/json;charset=utf8', + ); + $tmpdata['code_type'] = 'zip'; + $tmpdata['func_code']['file'] = base64_encode( file_get_contents($source) ); + $req->body = json_encode($tmpdata); + $curl = $signer->Sign($req); + $response = curl_exec($curl); + $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close($curl); + return $response; +} + +function api_error($response) +{ + return isset($response['error_code']); +} + +function api_error_msg($response) +{ + return $response['error_code'] . '
+' . $response['error_msg'] . '
+request_id: ' . $response['request_id'] . '

+function_name: ' . $_SERVER['function_name'] . '
+'; +} + +function setConfigResponse($response) +{ + return json_decode( $response, true ); +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + $source = '/tmp/code.zip'; + $outPath = '/tmp/'; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return json_encode(['error_code'=>'Error', 'error_msg'=>'Git Source input Error!']); + $tarfile = '/tmp/github.tar.gz'; + file_put_contents($tarfile, file_get_contents($url)); + $phar = new PharData($tarfile); + $html = $phar->extractTo($outPath, null, true);//路径 要解压的文件 是否覆盖 + + // 获取解压出的目录名 + $outPath = findIndexPath($outPath); + + // 放入配置文件 + file_put_contents($outPath . '/.data/config.php', file_get_contents(__DIR__ . '/../.data/config.php')); + + // 将目录中文件打包成zip + //$zip=new ZipArchive(); + $zip=new PharData($source); + //if($zip->open($source, ZipArchive::CREATE)){ + addFileToZip($zip, $outPath); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 + // $zip->close(); //关闭处理的zip文件 + //} + + return updateProgram(getConfig('HW_urn'), getConfig('HW_key'), getConfig('HW_secret'), $source); +} + +function addFileToZip($zip, $rootpath, $path = '') +{ + if (substr($rootpath,-1)=='/') $rootpath = substr($rootpath, 0, -1); + if (substr($path,0,1)=='/') $path = substr($path, 1); + $handler=opendir(path_format($rootpath.'/'.$path)); //打开当前文件夹由$path指定。 + while($filename=readdir($handler)){ + if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作 + $nowname = path_format($rootpath.'/'.$path."/".$filename); + if(is_dir($nowname)){// 如果读取的某个对象是文件夹,则递归 + $zip->addEmptyDir($path."/".$filename); + addFileToZip($zip, $rootpath, $path."/".$filename); + }else{ //将文件加入zip对象 + $newname = $path."/".$filename; + if (substr($newname,0,1)=='/') $newname = substr($newname, 1); + $zip->addFile($nowname, $newname); + //$zip->renameName($nowname, $newname); + } + } + } + @closedir($handler); +} + + + + + + + + + +define("BasicDateFormat", "Ymd\THis\Z"); +define("Algorithm", "SDK-HMAC-SHA256"); +define("HeaderXDate", "X-Sdk-Date"); +define("HeaderHost", "host"); +define("HeaderAuthorization", "Authorization"); +define("HeaderContentSha256", "X-Sdk-Content-Sha256"); + +class Request +{ + public $method = ''; + public $scheme = ''; + public $host = ''; + public $uri = ''; + public $query = array(); + public $headers = array(); + public $body = ''; + + function __construct() + { + $args = func_get_args(); + $i = count($args); + if ($i == 0) { + $this->construct(NULL, NULL, NULL, NULL); + } elseif ($i == 1) { + $this->construct($args[0], NULL, NULL, NULL); + } elseif ($i == 2) { + $this->construct($args[0], $args[1], NULL, NULL); + } elseif ($i == 3) { + $this->construct($args[0], $args[1], $args[2], NULL); + } else { + $this->construct($args[0], $args[1], $args[2], $args[3]); + } + } + + function construct($method, $url, $headers, $body) + { + if ($method != NULL) { + $this->method = $method; + } + if ($url != NULL) { + $spl = explode("://", $url, 2); + $scheme = 'http'; + if (count($spl) > 1) { + $scheme = $spl[0]; + $url = $spl[1]; + } + $spl = explode("?", $url, 2); + $url = $spl[0]; + $query = array(); + if (count($spl) > 1) { + foreach (explode("&", $spl[1]) as $kv) { + $spl = explode("=", $kv, 2); + $key = $spl[0]; + if (count($spl) == 1) { + $value = ""; + } else { + $value = $spl[1]; + } + if ($key != "") { + $key = urldecode($key); + $value = urldecode($value); + if (array_key_exists($key, $query)) { + array_push($query[$key], $value); + } else { + $query[$key] = array($value); + } + } + } + } + $spl = explode("/", $url, 2); + $host = $spl[0]; + if (count($spl) == 1) { + $url = "/"; + } else { + $url = "/" . $spl[1]; + } + $this->scheme = $scheme; + $this->host = $host; + $this->uri = urldecode($url); + $this->query = $query; + } + if ($headers != NULL) { + $this->headers = $headers; + } + if ($body != NULL) { + $this->body = $body; + } + } +} + +class Signer +{ + public $Key = ''; + public $Secret = ''; + + function escape($string) + { + $entities = array('+', "%7E"); + $replacements = array('%20', "~"); + return str_replace($entities, $replacements, urlencode($string)); + } + + function findHeader($r, $header) + { + foreach ($r->headers as $key => $value) { + if (!strcasecmp($key, $header)) { + return $value; + } + } + return NULL; + } + +// Build a CanonicalRequest from a regular request string +// +// CanonicalRequest = +// HTTPRequestMethod + '\n' + +// CanonicalURI + '\n' + +// CanonicalQueryString + '\n' + +// CanonicalHeaders + '\n' + +// SignedHeaders + '\n' + +// HexEncode(Hash(RequestPayload)) + function CanonicalRequest($r, $signedHeaders) + { + $CanonicalURI = $this->CanonicalURI($r); + $CanonicalQueryString = $this->CanonicalQueryString($r); + $canonicalHeaders = $this->CanonicalHeaders($r, $signedHeaders); + $signedHeadersString = join(";", $signedHeaders); + $hash = $this->findHeader($r, HeaderContentSha256); + if (!$hash) { + $hash = hash("sha256", $r->body); + } + return "$r->method\n$CanonicalURI\n$CanonicalQueryString\n$canonicalHeaders\n$signedHeadersString\n$hash"; + } + +// CanonicalURI returns request uri + function CanonicalURI($r) + { + $pattens = explode("/", $r->uri); + $uri = array(); + foreach ($pattens as $v) { + array_push($uri, $this->escape($v)); + } + $urlpath = join("/", $uri); + if (substr($urlpath, -1) != "/") { + $urlpath = $urlpath . "/"; + } + return $urlpath; + } + +// CanonicalQueryString + function CanonicalQueryString($r) + { + $keys = array(); + foreach ($r->query as $key => $value) { + array_push($keys, $key); + } + sort($keys); + $a = array(); + foreach ($keys as $key) { + $k = $this->escape($key); + $value = $r->query[$key]; + if (is_array($value)) { + sort($value); + foreach ($value as $v) { + $kv = "$k=" . $this->escape($v); + array_push($a, $kv); + } + } else { + $kv = "$k=" . $this->escape($value); + array_push($a, $kv); + } + } + return join("&", $a); + } + +// CanonicalHeaders + function CanonicalHeaders($r, $signedHeaders) + { + $headers = array(); + foreach ($r->headers as $key => $value) { + $headers[strtolower($key)] = trim($value); + } + $a = array(); + foreach ($signedHeaders as $key) { + array_push($a, $key . ':' . $headers[$key]); + } + return join("\n", $a) . "\n"; + } + + function curlHeaders($r) + { + $header = array(); + foreach ($r->headers as $key => $value) { + array_push($header, strtolower($key) . ':' . trim($value)); + } + return $header; + } + +// SignedHeaders + function SignedHeaders($r) + { + $a = array(); + foreach ($r->headers as $key => $value) { + array_push($a, strtolower($key)); + } + sort($a); + return $a; + } + +// Create a "String to Sign". + function StringToSign($canonicalRequest, $t) + { + date_default_timezone_set('UTC'); + $date = date(BasicDateFormat, $t); + $hash = hash("sha256", $canonicalRequest); + return "SDK-HMAC-SHA256\n$date\n$hash"; + } + +// Create the HWS Signature. + function SignStringToSign($stringToSign, $signingKey) + { + return hash_hmac("sha256", $stringToSign, $signingKey); + } + +// Get the finalized value for the "Authorization" header. The signature parameter is the output from SignStringToSign + function AuthHeaderValue($signature, $accessKey, $signedHeaders) + { + $signedHeadersString = join(";", $signedHeaders); + return "SDK-HMAC-SHA256 Access=$accessKey, SignedHeaders=$signedHeadersString, Signature=$signature"; + } + + public function Sign($r) + { + date_default_timezone_set('UTC'); + $date = $this->findHeader($r, HeaderXDate); + if ($date) { + $t = date_timestamp_get(date_create_from_format(BasicDateFormat, $date)); + } + if (!@$t) { + $t = time(); + $r->headers[HeaderXDate] = date(BasicDateFormat, $t); + } + $queryString = $this->CanonicalQueryString($r); + if ($queryString != "") { + $queryString = "?" . $queryString; + } + $signedHeaders = $this->SignedHeaders($r); + $canonicalRequest = $this->CanonicalRequest($r, $signedHeaders); + $stringToSign = $this->StringToSign($canonicalRequest, $t); + $signature = $this->SignStringToSign($stringToSign, $this->Secret); + $authValue = $this->AuthHeaderValue($signature, $this->Key, $signedHeaders); + $r->headers[HeaderAuthorization] = $authValue; + + $curl = curl_init(); + $uri = str_replace(array("%2F"), array("/"), rawurlencode($r->uri)); + $url = $r->scheme . '://' . $r->host . $uri . $queryString; + $headers = $this->curlHeaders($r); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $r->method); + curl_setopt($curl, CURLOPT_POSTFIELDS, $r->body); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); + curl_setopt($curl, CURLOPT_NOBODY, FALSE); + return $curl; + } +} + +function WaitFunction() { + return true; +} + +function changeAuthKey() { + if ($_POST['HW_key']!=''&&$_POST['HW_secret']!='') { + $tmp['HW_key'] = $_POST['HW_key']; + $tmp['HW_secret'] = $_POST['HW_secret']; + $response = setConfigResponse( SetbaseConfig($tmp, getConfig('HW_urn'), $tmp['HW_key'], $tmp['HW_secret']) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + $html = ' +
+ 点击链接,新增访问密钥, + 在下载的credentials.csv文件中找到对应信息,填入:
+
+
+ +
+ '; + return message($html, 'Change platform Auth token or key', 200); +} + +function smallfileupload($drive, $path) { + return output('Can not upload through FG.', 400); +} diff --git a/platform/Normal.php b/platform/Normal.php new file mode 100644 index 0000000..454eb89 --- /dev/null +++ b/platform/Normal.php @@ -0,0 +1,399 @@ +0) $path = substr($_SERVER['REQUEST_URI'], 0, $p); + else $path = $_SERVER['REQUEST_URI']; + $path = path_format( substr($path, strlen($_SERVER['base_path'])) ); + return $path; +} + +function getGET() +{ + if (!$_POST) { + if (!!$HTTP_RAW_POST_DATA) { + $tmpdata = $HTTP_RAW_POST_DATA; + } else { + $tmpdata = file_get_contents('php://input'); + } + if (!!$tmpdata) { + $postbody = explode("&", $tmpdata); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + } + } + if (isset($_SERVER['UNENCODED_URL'])) $_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL']; + $p = strpos($_SERVER['REQUEST_URI'],'?'); + if ($p>0) { + $getstr = substr($_SERVER['REQUEST_URI'], $p+1); + $getstrarr = explode("&",$getstr); + foreach ($getstrarr as $getvalues) { + if ($getvalues != '') { + $pos = strpos($getvalues, "="); + //echo $pos; + if ($pos > 0) { + $getarry[urldecode(substr($getvalues, 0, $pos))] = urldecode(substr($getvalues, $pos + 1)); + } else { + $getarry[urldecode($getvalues)] = true; + } + } + } + } + if (isset($getarry)) { + return $getarry; + } else { + return []; + } +} + +function getConfig($str, $disktag = '') +{ + global $slash; + $projectPath = splitlast(__DIR__, $slash)[0]; + $configPath = $projectPath . $slash . '.data' . $slash . 'config.php'; + $s = file_get_contents($configPath); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') { + $envs = json_decode($configs, true); + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + if (isset($envs[$disktag][$str])) { + if (isBase64Env($str)) return base64y_decode($envs[$disktag][$str]); + else return $envs[$disktag][$str]; + } + } else { + if (isset($envs[$str])) { + if (isBase64Env($str)) return base64y_decode($envs[$str]); + else return $envs[$str]; + } + } + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + global $slash; + if ($disktag=='') $disktag = $_SERVER['disktag']; + $projectPath = splitlast(__DIR__, $slash)[0]; + $configPath = $projectPath . $slash . '.data' . $slash . 'config.php'; + $s = file_get_contents($configPath); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') $envs = json_decode($configs, true); + $disktags = explode("|", getConfig('disktag')); + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $envs[$k] = base64y_encode($v); + else $envs[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $envs[$disktag][$k] = base64y_encode($v); + else $envs[$disktag][$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $envs[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $envs[$newtag] = $envs[$v]; + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + //$tmpdisk = json_decode($v, true); + //var_dump($tmpdisk); + //error_log(json_encode($tmpdisk)); + //if ($tmpdisk===null) + $envs[$k] = $v; + //else $envs[$k] = $tmpdisk; + } + } + if ($indisk) { + $diskconfig = $envs[$disktag]; + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $envs[$disktag] = $diskconfig; + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $envs['disktag'] = implode('|', $tags); + $envs[$arr['disktag_newname']] = $envs[$arr['disktag_rename']]; + unset($envs[$arr['disktag_rename']]); + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $envs['disktag'] = substr($disktag_s, 0, -1); + else $envs['disktag'] = ''; + } + } + $envs = array_filter($envs, 'array_value_isnot_null'); + //ksort($envs); + sortConfig($envs); + + //echo '
'. json_encode($envs, JSON_PRETTY_PRINT).'
'; + $prestr = '0) return json_encode( [ 'response' => 'success' ] ); + return json_encode( [ 'message' => 'Failed to write config.', 'code' => 'failed' ] ); +} + +function install() +{ + global $constStr; + if ($_GET['install2']) { + if ($_POST['admin']!='') { + $tmp['admin'] = $_POST['admin']; + //$tmp['language'] = $_COOKIE['language']; + $tmp['timezone'] = $_COOKIE['timezone']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + return output('Jump + + ', 302); + } + } + } + if ($_GET['install1']) { + if (!ConfigWriteable()) { + $html .= getconstStr('MakesuerWriteable'); + $title = 'Error'; + return message($html, $title, 201); + } + /*if (!RewriteEngineOn()) { + $html .= getconstStr('MakesuerRewriteOn'); + $title = 'Error'; + return message($html, $title, 201); + }*/ + $html .= ' + + '; + $title = getconstStr('SetAdminPassword'); + return message($html, $title, 201); + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + + $title = 'Install'; + $html = '' . getconstStr('ClickInstall') . ', ' . getconstStr('LogintoBind'); + return message($html, $title, 201); +} + +function ConfigWriteable() +{ + $t = md5( md5(time()).rand(1000,9999) ); + $r = setConfig([ 'tmp' => $t ]); + $tmp = getConfig('tmp'); + setConfig([ 'tmp' => '' ]); + if ($tmp == $t) return true; + if ($r) return true; + return false; +} + +function api_error($response) +{ + return isset($response['message']); +} + +function api_error_msg($response) +{ + return $response['code'] . '
+' . $response['message'] . '
+'; +} + +function setConfigResponse($response) +{ + return json_decode($response, true); +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + global $slash; + // __DIR__ is xxx/platform + $projectPath = splitlast(__DIR__, $slash)[0]; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return 0; + $tarfile = $projectPath . $slash .'github.tar.gz'; + $githubfile = file_get_contents($url); + if (!$githubfile) return 0; + file_put_contents($tarfile, $githubfile); + + if (splitfirst(PHP_VERSION, '.')[0] > '5') { + $phar = new PharData($tarfile); // need php5.3, 7, 8 + $phar->extractTo($projectPath, null, true);//路径 要解压的文件 是否覆盖 + } else { + ob_start(); + passthru('tar -xzvf ' . $tarfile, $stat); + ob_get_clean(); + } + unlink($tarfile); + + $outPath = ''; + $outPath = findIndexPath($projectPath); + //error_log1($outPath); + if ($outPath=='') return 0; + + //unlink($outPath.'/config.php'); + $response = rename($projectPath . $slash . '.data' . $slash . 'config.php', $outPath . $slash . '.data' . $slash . 'config.php'); + if (!$response) { + $tmp1['code'] = "Move Failed"; + $tmp1['message'] = "Can not move " . $projectPath . $slash . '.data' . $slash . 'config.php' . " to " . $outPath . $slash . '.data' . $slash . 'config.php'; + return json_encode($tmp1); + } + return moveFolder($outPath, $projectPath); +} + +function moveFolder($from, $to) +{ + global $slash; + if (substr($from, -1)==$slash) $from = substr($from, 0, -1); + if (substr($to, -1)==$slash) $to = substr($to, 0, -1); + if (!file_exists($to)) mkdir($to, 0777); + $handler=opendir($from); + while($filename=readdir($handler)) { + if($filename != '.' && $filename != '..'){ + $fromfile = $from . $slash . $filename; + $tofile = $to . $slash . $filename; + if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归 + $response = moveFolder($fromfile, $tofile); + if (api_error(setConfigResponse($response))) return $response; + }else{ + //if (file_exists($tofile)) unlink($tofile); + $response = rename($fromfile, $tofile); + if (!$response) { + $tmp['code'] = "Move Failed"; + $tmp['message'] = "Can not move " . $fromfile . " to " . $tofile; + return json_encode($tmp); + } + if (file_exists($fromfile)) unlink($fromfile); + } + } + } + closedir($handler); + rmdir($from); + return json_encode( [ 'response' => 'success' ] ); +} + +function WaitFunction() { + return true; +} + +function changeAuthKey() { + return message("Not need.", 'Change platform Auth token or key', 404); +} + +function smallfileupload($drive, $path) { + if ($_FILES['file1']['error']) return output($_FILES['file1']['error'], 400); + if ($_FILES['file1']['size']>4*1024*1024) return output('File too large', 400); + return $drive->smallfileupload($path, $_FILES['file1']); +} diff --git a/platform/Replit.php b/platform/Replit.php new file mode 100644 index 0000000..a611805 --- /dev/null +++ b/platform/Replit.php @@ -0,0 +1,363 @@ +0) $path = substr($_SERVER['REQUEST_URI'], 0, $p); + else $path = $_SERVER['REQUEST_URI']; + $path = path_format( substr($path, strlen($_SERVER['base_path'])) ); + return $path; +} + +function getGET() +{ + if (!$_POST) { + if (!!$HTTP_RAW_POST_DATA) { + $tmpdata = $HTTP_RAW_POST_DATA; + } else { + $tmpdata = file_get_contents('php://input'); + } + if (!!$tmpdata) { + $postbody = explode("&", $tmpdata); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + } + } + if (isset($_SERVER['UNENCODED_URL'])) $_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL']; + $p = strpos($_SERVER['REQUEST_URI'],'?'); + if ($p>0) { + $getstr = substr($_SERVER['REQUEST_URI'], $p+1); + $getstrarr = explode("&",$getstr); + foreach ($getstrarr as $getvalues) { + if ($getvalues != '') { + $pos = strpos($getvalues, "="); + //echo $pos; + if ($pos > 0) { + $getarry[urldecode(substr($getvalues, 0, $pos))] = urldecode(substr($getvalues, $pos + 1)); + } else { + $getarry[urldecode($getvalues)] = true; + } + } + } + } + if (isset($getarry)) { + return $getarry; + } else { + return []; + } +} + +function ReplitAPI($op, $key, $value = '') { + //error_log1($op . '_' . $key . '_' . $value); + $apiurl = getenv('REPLIT_DB_URL'); + //foreach (explode("\n", curl('GET', $apiurl . '?prefix')['body']) as $a) curl('DELETE', $apiurl . '/' . $a); + if ($op === 'r') { + if (!($config = getcache('REPLIT_CONFIG'))) { + $config = json_decode(curl('GET', $apiurl . '/REPLIT_CONFIG')['body'], true); + savecache('REPLIT_CONFIG', $config); + } + return ['stat'=>200, 'body'=>(is_array($config[$key])?json_encode($config[$key]):$config[$key])]; + } elseif ($op === 'w') { + return curl('POST', $apiurl, 'REPLIT_CONFIG=' . $value, ["Content-Type"=>"application/x-www-form-urlencoded"]); + } elseif ($op === 'd') { + // not use + return curl('DELETE', $apiurl . '/' . $key); + } else { + return ['stat'=>500, 'body'=>'error option input to function ReplitAPI().']; + } +} + +function getConfig($str, $disktag = '') +{ + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + $env = json_decode(ReplitAPI('r', $disktag)['body'], true); + if (isset($env[$str])) { + if (isBase64Env($str)) return base64y_decode($env[$str]); + else return $env[$str]; + } + } else { + if (isBase64Env($str)) return base64y_decode(ReplitAPI('r', $str)['body']); + else return ReplitAPI('r', $str)['body']; + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + if (!($envs = getcache('REPLIT_CONFIG'))) { + $envs = json_decode(curl('GET', getenv('REPLIT_DB_URL') . '/REPLIT_CONFIG')['body'], true); + savecache('REPLIT_CONFIG', $envs); + } + if ($disktag=='') $disktag = $_SERVER['disktag']; + $disktags = explode("|", getConfig('disktag')); + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $envs[$k] = base64y_encode($v); + else $envs[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $envs[$disktag][$k] = base64y_encode($v); + else $envs[$disktag][$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $envs[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $envs[$newtag] = $envs[$v]; + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $envs[$k] = $v; + } + } + if ($indisk) { + $diskconfig = $envs[$disktag]; + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $envs[$disktag] = $diskconfig; + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $envs['disktag'] = implode('|', $tags); + $envs[$arr['disktag_newname']] = $envs[$arr['disktag_rename']]; + unset($envs[$arr['disktag_rename']]); + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $envs['disktag'] = substr($disktag_s, 0, -1); + else $envs['disktag'] = ''; + } + } + $envs = array_filter($envs, 'array_value_isnot_null'); + sortConfig($envs); + $response = ReplitAPI('w', 'REPLIT_CONFIG', json_encode($envs)); + //error_log1(json_encode($arr, JSON_PRETTY_PRINT) . ' => tmp:' . json_encode($envs, JSON_PRETTY_PRINT)); + savecache('REPLIT_CONFIG', null, '', 0); + if (api_error($response)) return ['stat'=>$response['stat'], 'body'=>$response['body'] . "
\nError in writting " . $key . "=" . $val]; + return $response; +} + +function install() +{ + global $constStr; + if ($_GET['install2']) { + if ($_POST['admin']!='') { + $tmp['admin'] = $_POST['admin']; + //$tmp['language'] = $_COOKIE['language']; + $tmp['timezone'] = $_COOKIE['timezone']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + return output('Jump + + ', 302); + } + } + } + if ($_GET['install1']) { + /*if (!ConfigWriteable()) { + $html .= getconstStr('MakesuerWriteable'); + $title = 'Error'; + return message($html, $title, 201); + } + if (!RewriteEngineOn()) { + $html .= getconstStr('MakesuerRewriteOn'); + $title = 'Error'; + return message($html, $title, 201); + }*/ + $html .= ' +
+
+ +
+ '; + $title = getconstStr('SetAdminPassword'); + return message($html, $title, 201); + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + + $title = 'Install'; + $html = '' . getconstStr('ClickInstall') . ', ' . getconstStr('LogintoBind'); + return message($html, $title, 201); +} + +function ConfigWriteable() +{ + $t = md5( md5(time()).rand(1000,9999) ); + $r = setConfig([ 'tmp' => $t ]); + $tmp = getConfig('tmp'); + setConfig([ 'tmp' => '' ]); + if ($tmp == $t) return true; + if ($r) return true; + return false; +} + +function api_error($response) +{ + return !($response['stat']==200||$response['stat']==204||$response['stat']==404); + //return isset($response['message']); +} + +function api_error_msg($response) +{ + return '
'. json_encode($response, JSON_PRETTY_PRINT).'
' . '
+'; +} + +function setConfigResponse($response) +{ + return $response; + //return json_decode($response, true); +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + // __DIR__ is xxx/platform + $projectPath = splitlast(__DIR__, '/')[0]; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return ['stat'=>500, 'body'=>'Git Source input Error!']; + $tarfile = $projectPath . '/github.tar.gz'; + $githubfile = file_get_contents($url); + if (!$githubfile) return ['stat'=>500, 'body'=>'download error from github.']; + file_put_contents($tarfile, $githubfile); + if (splitfirst(PHP_VERSION, '.')[0] > '5') { + $phar = new PharData($tarfile); // need php5.3, 7, 8 + $phar->extractTo($projectPath, null, true);//路径 要解压的文件 是否覆盖 + } else { + ob_start(); + passthru('tar -xzvf ' . $tarfile, $stat); + ob_get_clean(); + } + unlink($tarfile); + + $outPath = ''; + $outPath = findIndexPath($projectPath); + //error_log1($outPath); + if ($outPath=='') return ['stat'=>500, 'body'=>'can\'t find folder after download from github.']; + + return moveFolder($outPath, $projectPath); +} + +function moveFolder($from, $to) +{ + if (substr($from, -1)=='/') $from = substr($from, 0, -1); + if (substr($to, -1)=='/') $to = substr($to, 0, -1); + if (!file_exists($to)) mkdir($to, 0777); + $handler=opendir($from); + while($filename=readdir($handler)) { + if($filename != '.' && $filename != '..'){ + $fromfile = $from . '/' . $filename; + $tofile = $to . '/' . $filename; + if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归 + $response = moveFolder($fromfile, $tofile); + if (api_error(setConfigResponse($response))) return $response; + }else{ + if (file_exists($tofile)) unlink($tofile); + $response = rename($fromfile, $tofile); + if (!$response) { + $tmp['code'] = "Move Failed"; + $tmp['message'] = "Can not move " . $fromfile . " to " . $tofile; + return ['stat'=>500, 'body'=>json_encode($tmp)]; + } + if (file_exists($fromfile)) unlink($fromfile); + } + } + } + closedir($handler); + rmdir($from); + return ['stat'=>200, 'body'=>'success.']; +} + +function WaitFunction() { + return true; +} + +function changeAuthKey() { + return message("Not need.", 'Change platform Auth token or key', 404); +} + +function smallfileupload($drive, $path) { + if ($_FILES['file1']['error']) return output($_FILES['file1']['error'], 400); + if ($_FILES['file1']['size']>4*1024*1024) return output('File too large', 400); + return $drive->smallfileupload($path, $_FILES['file1']); +} diff --git a/platform/Replit_old.php b/platform/Replit_old.php new file mode 100644 index 0000000..572c150 --- /dev/null +++ b/platform/Replit_old.php @@ -0,0 +1,379 @@ +0) $path = substr($_SERVER['REQUEST_URI'], 0, $p); + else $path = $_SERVER['REQUEST_URI']; + $path = path_format( substr($path, strlen($_SERVER['base_path'])) ); + return $path; +} + +function getGET() +{ + if (!$_POST) { + if (!!$HTTP_RAW_POST_DATA) { + $tmpdata = $HTTP_RAW_POST_DATA; + } else { + $tmpdata = file_get_contents('php://input'); + } + if (!!$tmpdata) { + $postbody = explode("&", $tmpdata); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + } + } + if (isset($_SERVER['UNENCODED_URL'])) $_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL']; + $p = strpos($_SERVER['REQUEST_URI'],'?'); + if ($p>0) { + $getstr = substr($_SERVER['REQUEST_URI'], $p+1); + $getstrarr = explode("&",$getstr); + foreach ($getstrarr as $getvalues) { + if ($getvalues != '') { + $pos = strpos($getvalues, "="); + //echo $pos; + if ($pos > 0) { + $getarry[urldecode(substr($getvalues, 0, $pos))] = urldecode(substr($getvalues, $pos + 1)); + } else { + $getarry[urldecode($getvalues)] = true; + } + } + } + } + if (isset($getarry)) { + return $getarry; + } else { + return []; + } +} + +function ReplitAPI($op, $key, $value = '') { + //error_log1($op . '_' . $key . '_' . $value); + $apiurl = getenv('REPLIT_DB_URL'); + if ($op === 'r') { + return curl('GET', $apiurl . '/' . $key); + } elseif ($op === 'w') { + return curl('POST', $apiurl, $key . '=' . $value, ["Content-Type"=>"application/x-www-form-urlencoded"]); + } elseif ($op === 'd') { + return curl('DELETE', $apiurl . '/' . $key); + } else { + return ['stat'=>500, 'body'=>'error option input to function ReplitAPI().']; + } +} + +function getConfig($str, $disktag = '') +{ + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + $env = json_decode(ReplitAPI('r', $disktag)['body'], true); + if (isset($env[$str])) { + if (isBase64Env($str)) return base64y_decode($env[$str]); + else return $env[$str]; + } + } else { + if (isBase64Env($str)) return base64y_decode(ReplitAPI('r', $str)['body']); + else return ReplitAPI('r', $str)['body']; + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + if ($disktag=='') $disktag = $_SERVER['disktag']; + $disktags = explode("|", getConfig('disktag')); + if ($disktag!='') $diskconfig = json_decode(ReplitAPI('r', $disktag)['body'], true); + $tmp = []; + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $tmp[$k] = base64y_encode($v); + else $tmp[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $diskconfig[$k] = base64y_encode($v); + else $diskconfig[$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $tmp[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $tmp[$newtag] = getConfig($v); + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $tmp[$k] = json_encode($v); + } + } + if ($indisk) { + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $tmp[$disktag] = json_encode($diskconfig); + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $tmp['disktag'] = implode('|', $tags); + $tmp[$arr['disktag_newname']] = getConfig($arr['disktag_rename']); + $tmp[$arr['disktag_rename']] = null; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $tmp['disktag'] = substr($disktag_s, 0, -1); + else $tmp['disktag'] = null; + } + } + $response = null; + foreach ($tmp as $key => $val) { + if (!!$val) $response = ReplitAPI('w', $key, $val); + else $response = ReplitAPI('d', $key); + if (api_error($response)) return ['stat'=>$response['stat'], 'body'=>$response['body'] . "
\nError in writting " . $key . "=" . $val]; + } + //error_log1(json_encode($arr, JSON_PRETTY_PRINT) . ' => tmp:' . json_encode($tmp, JSON_PRETTY_PRINT)); + return $response; +} + +function install() +{ + global $constStr; + if ($_GET['install2']) { + if ($_POST['admin']!='') { + $tmp['admin'] = $_POST['admin']; + //$tmp['language'] = $_COOKIE['language']; + $tmp['timezone'] = $_COOKIE['timezone']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + return output('Jump + + ', 302); + } + } + } + if ($_GET['install1']) { + if (!ConfigWriteable()) { + $html .= getconstStr('MakesuerWriteable'); + $title = 'Error'; + return message($html, $title, 201); + } + /*if (!RewriteEngineOn()) { + $html .= getconstStr('MakesuerRewriteOn'); + $title = 'Error'; + return message($html, $title, 201); + }*/ + $html .= ' + + '; + $title = getconstStr('SetAdminPassword'); + return message($html, $title, 201); + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + + $title = 'Install'; + $html = '' . getconstStr('ClickInstall') . ', ' . getconstStr('LogintoBind'); + return message($html, $title, 201); +} + +function ConfigWriteable() +{ + $t = md5( md5(time()).rand(1000,9999) ); + $r = setConfig([ 'tmp' => $t ]); + $tmp = getConfig('tmp'); + setConfig([ 'tmp' => '' ]); + if ($tmp == $t) return true; + if ($r) return true; + return false; +} + +function api_error($response) +{ + return !($response['stat']==200||$response['stat']==204||$response['stat']==404); + //return isset($response['message']); +} + +function api_error_msg($response) +{ + return '
'. json_encode($response, JSON_PRETTY_PRINT).'
' . '
+'; +} + +function setConfigResponse($response) +{ + return $response; + //return json_decode($response, true); +} + +function OnekeyUpate($auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + $slash = '/'; + if (strpos(__DIR__, ':')) $slash = '\\'; + // __DIR__ is xxx/platform + $projectPath = splitlast(__DIR__, $slash)[0]; + + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + $tarfile = $projectPath . $slash .'github.tar.gz'; + $githubfile = file_get_contents($url); + if (!$githubfile) return ['stat'=>500, 'body'=>'download error from github.']; + file_put_contents($tarfile, $githubfile); + if (splitfirst(PHP_VERSION, '.')[0] > '5') { + $phar = new PharData($tarfile); // need php5.3, 7, 8 + $phar->extractTo($projectPath, null, true);//路径 要解压的文件 是否覆盖 + } else { + ob_start(); + passthru('tar -xzvf ' . $tarfile, $stat); + ob_get_clean(); + } + unlink($tarfile); + + $outPath = ''; + $tmp = scandir($projectPath); + $name = $auth . '-' . $project; + foreach ($tmp as $f) { + if ( substr($f, 0, strlen($name)) == $name) { + $outPath = $projectPath . $slash . $f; + break; + } + } + //error_log1($outPath); + if ($outPath=='') return ['stat'=>500, 'body'=>'can\'t find folder after download from github.']; + + return moveFolder($outPath, $projectPath, $slash); +} + +function moveFolder($from, $to, $slash) +{ + if (substr($from, -1)==$slash) $from = substr($from, 0, -1); + if (substr($to, -1)==$slash) $to = substr($to, 0, -1); + if (!file_exists($to)) mkdir($to, 0777); + $handler=opendir($from); + while($filename=readdir($handler)) { + if($filename != '.' && $filename != '..'){ + $fromfile = $from . $slash . $filename; + $tofile = $to . $slash . $filename; + if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归 + $response = moveFolder($fromfile, $tofile, $slash); + if (api_error(setConfigResponse($response))) return $response; + }else{ + if (file_exists($tofile)) unlink($tofile); + $response = rename($fromfile, $tofile); + if (!$response) { + $tmp['code'] = "Move Failed"; + $tmp['message'] = "Can not move " . $fromfile . " to " . $tofile; + return ['stat'=>500, 'body'=>json_encode($tmp)]; + } + if (file_exists($fromfile)) unlink($fromfile); + } + } + } + closedir($handler); + rmdir($from); + return ['stat'=>200, 'body'=>'success.']; +} + +function WaitFunction() { + return true; +} + +function changeAuthKey() { + return message("Not need.", 'Change platform Auth token or key', 404); +} diff --git a/platform/TencentSCF_env.php b/platform/TencentSCF_env.php new file mode 100644 index 0000000..7ba565d --- /dev/null +++ b/platform/TencentSCF_env.php @@ -0,0 +1,668 @@ +500) $event['body']=substr($event['body'],0,strpos($event['body'],'base64')+30) . '...Too Long!...' . substr($event['body'],-50); + echo urldecode(json_encode($event, JSON_PRETTY_PRINT)) . ' + +' . urldecode(json_encode($context, JSON_PRETTY_PRINT)) . ' + +'; +} + +function GetGlobalVariable($event) +{ + $_GET = $event['queryString']; + $postbody = explode("&",$event['body']); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + $cookiebody = explode("; ",$event['headers']['cookie']); + foreach ($cookiebody as $cookievalues) { + $pos = strpos($cookievalues,"="); + $_COOKIE[urldecode(substr($cookievalues,0,$pos))]=urldecode(substr($cookievalues,$pos+1)); + } +} + +function GetPathSetting($event, $context) +{ + $_SERVER['firstacceptlanguage'] = strtolower(splitfirst(splitfirst($event['headers']['accept-language'],';')[0],',')[0]); + $_SERVER['function_name'] = $context['function_name']; + $_SERVER['namespace'] = $context['namespace']; + $_SERVER['Region'] = $context['tencentcloud_region']; + $host_name = $event['headers']['host']; + $_SERVER['HTTP_HOST'] = $host_name; + $serviceId = $event['requestContext']['serviceId']; + if ( $serviceId === substr($host_name,0,strlen($serviceId)) ) { + $_SERVER['base_path'] = '/'.$event['requestContext']['stage'].'/'.$_SERVER['function_name'].'/'; + $path = substr($event['path'], strlen('/'.$_SERVER['function_name'].'/')); + } else { + $_SERVER['base_path'] = $event['requestContext']['path']; + $path = substr($event['path'], strlen($event['requestContext']['path'])); + } + //$_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path); + $_SERVER['REMOTE_ADDR'] = $event['requestContext']['sourceIp']; + $_SERVER['HTTP_X_REQUESTED_WITH'] = $event['headers']['x-requested-with']; + $_SERVER['HTTP_USER_AGENT'] = $event['headers']['user-agent']; + if (isset($event['headers']['authorization'])) { + $basicAuth = splitfirst(base64_decode(splitfirst($event['headers']['authorization'], 'Basic ')[1]), ':'); + $_SERVER['PHP_AUTH_USER'] = $basicAuth[0]; + $_SERVER['PHP_AUTH_PW'] = $basicAuth[1]; + } + $_SERVER['REQUEST_SCHEME'] = $event['headers']['x-api-scheme']; + //$_SERVER['REQUEST_SCHEME'] = $event['headers']['x-forwarded-proto']; + $_SERVER['host'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']; + $_SERVER['referhost'] = explode('/', $event['headers']['referer'])[2]; + $_SERVER['HTTP_TRANSLATE'] = $event['headers']['translate'];//'f' + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $event['headers']['if-modified-since']; + $_SERVER['REQUEST_METHOD'] = $event['httpMethod']; + $_SERVER['USER'] = 'qcloud'; + return $path; +} + +function getConfig($str, $disktag = '') +{ + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + $env = json_decode(getenv($disktag), true); + if (isset($env[$str])) { + if (isBase64Env($str)) return base64y_decode($env[$str]); + else return $env[$str]; + } + } else { + if (isBase64Env($str)) return base64y_decode(getenv($str)); + else return getenv($str); + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + if ($disktag=='') $disktag = $_SERVER['disktag']; + $disktags = explode("|",getConfig('disktag')); + $diskconfig = json_decode(getenv($disktag), true); + $tmp = []; + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $tmp[$k] = base64y_encode($v); + else $tmp[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $diskconfig[$k] = base64y_encode($v); + else $diskconfig[$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $tmp[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $tmp[$newtag] = getConfig($v); + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $tmp[$k] = json_encode($v); + } + } + if ($indisk) { + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $tmp[$disktag] = json_encode($diskconfig); + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $tmp['disktag'] = implode('|', $tags); + $tmp[$arr['disktag_newname']] = getConfig($arr['disktag_rename']); + $tmp[$arr['disktag_rename']] = ''; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $tmp['disktag'] = substr($disktag_s, 0, -1); + else $tmp['disktag'] = ''; + } + } +// echo '正式设置:'.json_encode($tmp,JSON_PRETTY_PRINT).' +//'; + $response = updateEnvironment($tmp, $_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')); + WaitSCFStat(); + return $response; +} + +function WaitSCFStat() +{ + $trynum = 0; + while( json_decode(getfunctioninfo($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')),true)['Response']['Status']!='Active' ) echo ' +'.++$trynum; +} + +function install() +{ + global $constStr; + if ($_GET['install2']) { + $tmp['admin'] = $_POST['admin']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } + if (needUpdate()) { + OnekeyUpate(); + return message('update to github version, reinstall. + + ', 'Program updating', 201, 1); + } + return message(getconstStr('Success') . ' + ', 201, 1); + } + if ($_GET['install1']) { + $tmp['timezone'] = $_COOKIE['timezone']; + $SecretId = getConfig('SecretId'); + if ($SecretId=='') { + $SecretId = $_POST['SecretId']; + $tmp['SecretId'] = $SecretId; + } + $SecretKey = getConfig('SecretKey'); + if ($SecretKey=='') { + $SecretKey = $_POST['SecretKey']; + $tmp['SecretKey'] = $SecretKey; + } + $tmp['ONEMANAGER_CONFIG_SAVE'] = $_POST['ONEMANAGER_CONFIG_SAVE']; + $response = json_decode(SetbaseConfig($tmp, $_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], $SecretId, $SecretKey), true)['Response']; + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + if ($tmp['ONEMANAGER_CONFIG_SAVE'] == 'file') { + $html = getconstStr('ONEMANAGER_CONFIG_SAVE_FILE') . '
' . getconstStr('Home') . ''; + $title = 'Reinstall'; + return message($html, $title, 201, 1); + } + $html .= ' +
+
+ +
+ '; + $title = getconstStr('SetAdminPassword'); + return message($html, $title, 201, 1); + } + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + //if (getConfig('SecretId')==''||getConfig('SecretKey')=='') + $html .= ' + ' . getconstStr('Create') . ' SecretId & SecretKey
+
+
'; + $html .= ' +
+
'; + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + $html .= ''.getconstStr('ClickInstall').', '.getconstStr('LogintoBind'); + $title = 'Install'; + return message($html, $title, 201); +} + +function post2url($url, $data) +{ + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_TIMEOUT, 5); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + $response = curl_exec($ch); + curl_close($ch); + //echo $response; + return $response; +} + +function ReorganizeDate($arr) +{ + $str = ''; + ksort($arr); + foreach ($arr as $k1 => $v1) { + $str .= '&' . $k1 . '=' . $v1; + } + $str = substr($str, 1); // remove first '&'. 去掉第一个& + return $str; +} + +function getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey) +{ + //$meth = 'GET'; + $meth = 'POST'; + $host = 'scf.tencentcloudapi.com'; + $tmpdata['Action'] = 'GetFunction'; + $tmpdata['FunctionName'] = $function_name; + $tmpdata['Namespace'] = $Namespace; + $tmpdata['Nonce'] = time(); + $tmpdata['Region'] = $Region; + $tmpdata['SecretId'] = $SecretId; + $tmpdata['Timestamp'] = time(); + $tmpdata['Token'] = ''; + $tmpdata['Version'] = '2018-04-16'; + $data = ReorganizeDate($tmpdata); + $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); + //echo urlencode($signStr); + //return file_get_contents('https://'.$url.'&Signature='.urlencode($signStr)); + return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); +} + +function updateEnvironment($Envs, $function_name, $Region, $Namespace, $SecretId, $SecretKey) +{ + //print_r($Envs); + WaitSCFStat(); + //json_decode($a,true)['Response']['Environment']['Variables'][0]['Key'] + $tmp = json_decode(getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey),true)['Response']['Environment']['Variables']; + foreach ($tmp as $tmp1) { + $tmp_env[$tmp1['Key']] = $tmp1['Value']; + } + foreach ($Envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + //$tmp_env['Region'] = $Region; + //ksort($tmp_env); + sortConfig($tmp_env); + + $i = 0; + foreach ($tmp_env as $key1 => $value1) { + $tmpdata['Environment.Variables.'.$i.'.Key'] = $key1; + $tmpdata['Environment.Variables.'.$i.'.Value'] = $value1; + $i++; + } + $meth = 'POST'; + $host = 'scf.tencentcloudapi.com'; + $tmpdata['Action'] = 'UpdateFunctionConfiguration'; + $tmpdata['FunctionName'] = $function_name; + $tmpdata['Namespace'] = $Namespace; + $tmpdata['Nonce'] = time(); + $tmpdata['Region'] = $Region; + $tmpdata['SecretId'] = $SecretId; + $tmpdata['Timestamp'] = time(); + $tmpdata['Token'] = ''; + $tmpdata['Version'] = '2018-04-16'; + $data = ReorganizeDate($tmpdata); + $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); + //echo urlencode($signStr); + return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); +} + +function SetbaseConfig($Envs, $function_name, $Region, $Namespace, $SecretId, $SecretKey) +{ + //echo json_encode($Envs,JSON_PRETTY_PRINT); + if ($Envs['ONEMANAGER_CONFIG_SAVE'] == 'file') $Envs = Array( 'ONEMANAGER_CONFIG_SAVE' => 'file' ); + //json_decode($a,true)['Response']['Environment']['Variables'][0]['Key'] + $tmp = json_decode(getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey),true)['Response']['Environment']['Variables']; + foreach ($tmp as $tmp1) { + $tmp_env[$tmp1['Key']] = $tmp1['Value']; + } + foreach ($Envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + //$tmp_env['Region'] = $Region; + ksort($tmp_env); + + $i = 0; + foreach ($tmp_env as $key1 => $value1) { + $tmpdata['Environment.Variables.'.$i.'.Key'] = $key1; + $tmpdata['Environment.Variables.'.$i.'.Value'] = $value1; + $i++; + } + $meth = 'POST'; + $host = 'scf.tencentcloudapi.com'; + $tmpdata['Action'] = 'UpdateFunctionConfiguration'; + $tmpdata['FunctionName'] = $function_name; + $tmpdata['Namespace'] = $Namespace; + $tmpdata['Nonce'] = time(); + $tmpdata['Region'] = $Region; + $tmpdata['SecretId'] = $SecretId; + $tmpdata['Timestamp'] = time(); + $tmpdata['Token'] = ''; + $tmpdata['Version'] = '2018-04-16'; + $tmpdata['Description'] = 'Onedrive index and manager in Tencent SCF.'; + $tmpdata['MemorySize'] = 64; + $tmpdata['Timeout'] = 30; + $data = ReorganizeDate($tmpdata); + echo $data; + $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); + //echo urlencode($signStr); + return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); +} + +function updateProgram_OLD($function_name, $Region, $Namespace, $SecretId, $SecretKey, $source) +{ + WaitSCFStat(); + $meth = 'POST'; + $host = 'scf.tencentcloudapi.com'; + $tmpdata['Action'] = 'UpdateFunctionCode'; + $tmpdata['Code.GitUrl'] = $source['url']; + $tmpdata['Code.GitBranch'] = $source['branch']; + $tmpdata['CodeSource'] = 'Git'; + $tmpdata['FunctionName'] = $function_name; + $tmpdata['Handler'] = 'index.main_handler'; + $tmpdata['Namespace'] = $Namespace; + $tmpdata['Nonce'] = time(); + $tmpdata['Region'] = $Region; + $tmpdata['SecretId'] = $SecretId; + $tmpdata['Timestamp'] = time(); + $tmpdata['Token'] = ''; + $tmpdata['Version'] = '2018-04-16'; + $data = ReorganizeDate($tmpdata); + $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); + //echo urlencode($signStr); + return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); +} + +function api_error($response) +{ + return isset($response['Error']); +} + +function api_error_msg($response) +{ + return $response['Error']['Code'] . '
+' . $response['Error']['Message'] . '

+function_name:' . $_SERVER['function_name'] . '
+Region:' . $_SERVER['Region'] . '
+namespace:' . $_SERVER['namespace'] . '
+'; +} + +function setConfigResponse($response) +{ + return json_decode( $response, true )['Response']; +} + +function WaitFunction() { + //$trynum = 0; + //while( json_decode(getfunctioninfo($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')),true)['Response']['Status']!='Active' ) echo ' +//'.++$trynum; + if ( json_decode(getfunctioninfo($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')),true)['Response']['Status']=='Active' ) return true; + else return false; +} + +function updateProgram($function_name, $Region, $Namespace, $SecretId, $SecretKey, $source) +{ + $secretId = $SecretId; + $secretKey = $SecretKey; + $host = 'scf.tencentcloudapi.com'; + $service = "scf"; + $version = "2018-04-16"; + $action = "UpdateFunctionCode"; + $region = $Region; + $timestamp = time(); + $algorithm = "TC3-HMAC-SHA256"; + + // step 1: build canonical request string + $httpRequestMethod = "POST"; + $canonicalUri = "/"; + $canonicalQueryString = ""; + $canonicalHeaders = "content-type:application/json; charset=utf-8\n"."host:".$host."\n"; + $signedHeaders = "content-type;host"; + + //$tmpdata['Action'] = 'UpdateFunctionCode'; + $tmpdata['Code']['ZipFile'] = base64_encode( file_get_contents($source) ); + $tmpdata['CodeSource'] = 'ZipFile'; + $tmpdata['FunctionName'] = $function_name; + $tmpdata['Handler'] = 'index.main_handler'; + //$tmpdata['Namespace'] = $Namespace; + //$tmpdata['Nonce'] = time(); + //$tmpdata['Region'] = $Region; + //$tmpdata['SecretId'] = $SecretId; + //$tmpdata['Timestamp'] = time(); + //$tmpdata['Token'] = ''; + //$tmpdata['Version'] = '2018-04-16'; + $payload = json_encode($tmpdata); + //$payload = '{"Limit": 1, "Filters": [{"Values": ["\u672a\u547d\u540d"], "Name": "instance-name"}]}'; + $hashedRequestPayload = hash("SHA256", $payload); + $canonicalRequest = $httpRequestMethod."\n" + .$canonicalUri."\n" + .$canonicalQueryString."\n" + .$canonicalHeaders."\n" + .$signedHeaders."\n" + .$hashedRequestPayload; + //echo $canonicalRequest.PHP_EOL; + + // step 2: build string to sign + $date = gmdate("Y-m-d", $timestamp); + $credentialScope = $date."/".$service."/tc3_request"; + $hashedCanonicalRequest = hash("SHA256", $canonicalRequest); + $stringToSign = $algorithm."\n" + .$timestamp."\n" + .$credentialScope."\n" + .$hashedCanonicalRequest; + //echo $stringToSign.PHP_EOL; + + // step 3: sign string + $secretDate = hash_hmac("SHA256", $date, "TC3".$secretKey, true); + $secretService = hash_hmac("SHA256", $service, $secretDate, true); + $secretSigning = hash_hmac("SHA256", "tc3_request", $secretService, true); + $signature = hash_hmac("SHA256", $stringToSign, $secretSigning); + //echo $signature.PHP_EOL; + + // step 4: build authorization + $authorization = $algorithm + ." Credential=".$secretId."/".$credentialScope + .", SignedHeaders=content-type;host, Signature=".$signature; + //echo $authorization.PHP_EOL; + + //$curl = "curl -X POST https://".$host + // .' -H "Authorization: '.$authorization.'"' + // .' -H "Content-Type: application/json; charset=utf-8"' + // .' -H "Host: '.$host.'"' + // .' -H "X-TC-Action: '.$action.'"' + // .' -H "X-TC-Timestamp: '.$timestamp.'"' + // .' -H "X-TC-Version: '.$version.'"' + // .' -H "X-TC-Region: '.$region.'"' + // ." -d '".$payload."'"; + //error_log1( $curl.PHP_EOL ); + //return '{"response": {"Error": {"Message":"' . $curl . '"}}}'; + $headers['Authorization'] = $authorization; + $headers['Content-Type'] = 'application/json; charset=utf-8'; + $headers['Host'] = $host; + $headers['X-TC-Action'] = $action; + $headers['X-TC-Timestamp'] = $timestamp; + $headers['X-TC-Version'] = $version; + $headers['X-TC-Region'] = $region; + return curl('POST', 'https://'.$host, $payload, $headers)['body']; +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + $source = '/tmp/code.zip'; + $outPath = '/tmp/'; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return json_encode(['Response'=>['Error'=>['code'=>'Git Source input Error!']]]); + $tarfile = '/tmp/github.tar.gz'; + file_put_contents($tarfile, file_get_contents($url)); + $phar = new PharData($tarfile); + $html = $phar->extractTo($outPath, null, true);//路径 要解压的文件 是否覆盖 + + // 获取解压出的目录名 + $outPath = findIndexPath($outPath); + + // 将目录中文件打包成zip + //$zip=new ZipArchive(); + $zip=new PharData($source); + //if($zip->open($source, ZipArchive::CREATE)){ + addFileToZip($zip, $outPath); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 + // $zip->close(); //关闭处理的zip文件 + //} + + return updateProgram($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey'), $source); +} + +function addFileToZip($zip, $rootpath, $path = '') +{ + if (substr($rootpath,-1)=='/') $rootpath = substr($rootpath, 0, -1); + if (substr($path,0,1)=='/') $path = substr($path, 1); + $handler=opendir(path_format($rootpath.'/'.$path)); //打开当前文件夹由$path指定。 + while($filename=readdir($handler)){ + if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作 + $nowname = path_format($rootpath.'/'.$path."/".$filename); + if(is_dir($nowname)){// 如果读取的某个对象是文件夹,则递归 + $zip->addEmptyDir($path."/".$filename); + addFileToZip($zip, $rootpath, $path."/".$filename); + }else{ //将文件加入zip对象 + $newname = $path."/".$filename; + if (substr($newname,0,1)=='/') $newname = substr($newname, 1); + $zip->addFile($nowname, $newname); + //$zip->renameName($nowname, $newname); + } + } + } + @closedir($handler); +} + +function changeAuthKey() { + if ($_POST['SecretId']!=''&&$_POST['SecretId']!='') { + $tmp['SecretId'] = $_POST['SecretId']; + $tmp['SecretKey'] = $_POST['SecretKey']; + $response = setConfigResponse( SetbaseConfig($tmp, $_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], $tmp['SecretId'], $tmp['SecretKey']) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + $html = ' +
+ ' . getconstStr('Create') . ' SecretId & SecretKey
+
+
+ +
+ '; + return message($html, 'Change platform Auth token or key', 200); +} + +function smallfileupload($drive, $path) { + return output('Can not upload through SCF.', 400); +} diff --git a/platform/TencentSCF_file.php b/platform/TencentSCF_file.php new file mode 100644 index 0000000..8db3f4c --- /dev/null +++ b/platform/TencentSCF_file.php @@ -0,0 +1,711 @@ +500) $event['body']=substr($event['body'],0,strpos($event['body'],'base64')+30) . '...Too Long!...' . substr($event['body'],-50); + echo urldecode(json_encode($event, JSON_PRETTY_PRINT)) . ' + +' . urldecode(json_encode($context, JSON_PRETTY_PRINT)) . ' + +'; +} + +function GetGlobalVariable($event) +{ + $_GET = $event['queryString']; + $postbody = explode("&",$event['body']); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + $cookiebody = explode("; ",$event['headers']['cookie']); + foreach ($cookiebody as $cookievalues) { + $pos = strpos($cookievalues,"="); + $_COOKIE[urldecode(substr($cookievalues,0,$pos))]=urldecode(substr($cookievalues,$pos+1)); + } +} + +function GetPathSetting($event, $context) +{ + $_SERVER['firstacceptlanguage'] = strtolower(splitfirst(splitfirst($event['headers']['accept-language'],';')[0],',')[0]); + $_SERVER['function_name'] = $context['function_name']; + $_SERVER['namespace'] = $context['namespace']; + $_SERVER['Region'] = $context['tencentcloud_region']; + $host_name = $event['headers']['host']; + $_SERVER['HTTP_HOST'] = $host_name; + $serviceId = $event['requestContext']['serviceId']; + if ( $serviceId === substr($host_name,0,strlen($serviceId)) ) { + $_SERVER['base_path'] = '/'.$event['requestContext']['stage'].'/'.$_SERVER['function_name'].'/'; + $path = substr($event['path'], strlen('/'.$_SERVER['function_name'].'/')); + } else { + $_SERVER['base_path'] = $event['requestContext']['path']; + $path = substr($event['path'], strlen($event['requestContext']['path'])); + } + //$_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path); + $_SERVER['REMOTE_ADDR'] = $event['requestContext']['sourceIp']; + $_SERVER['HTTP_X_REQUESTED_WITH'] = $event['headers']['x-requested-with']; + $_SERVER['HTTP_USER_AGENT'] = $event['headers']['user-agent']; + if (isset($event['headers']['authorization'])) { + $basicAuth = splitfirst(base64_decode(splitfirst($event['headers']['authorization'], 'Basic ')[1]), ':'); + $_SERVER['PHP_AUTH_USER'] = $basicAuth[0]; + $_SERVER['PHP_AUTH_PW'] = $basicAuth[1]; + } + $_SERVER['REQUEST_SCHEME'] = $event['headers']['x-api-scheme']; + //$_SERVER['REQUEST_SCHEME'] = $event['headers']['x-forwarded-proto']; + $_SERVER['host'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']; + $_SERVER['referhost'] = explode('/', $event['headers']['referer'])[2]; + $_SERVER['HTTP_TRANSLATE'] = $event['headers']['translate'];//'f' + $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $event['headers']['if-modified-since']; + $_SERVER['REQUEST_METHOD'] = $event['httpMethod']; + $_SERVER['USER'] = 'qcloud'; + return $path; +} + +function getConfig($str, $disktag = '') +{ + //include 'config.php'; + $s = file_get_contents('.data/config.php'); + //$configs = substr($s, 18, -2); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') { + $envs = json_decode($configs, true); + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + if (isset($envs[$disktag][$str])) { + if (isBase64Env($str)) return base64y_decode($envs[$disktag][$str]); + else return $envs[$disktag][$str]; + } + } else { + if (isset($envs[$str])) { + if (isBase64Env($str)) return base64y_decode($envs[$str]); + else return $envs[$str]; + } + } + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + if ($disktag=='') $disktag = $_SERVER['disktag']; + //include 'config.php'; + $s = file_get_contents('.data/config.php'); + //$configs = substr($s, 18, -2); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') $envs = json_decode($configs, true); + $disktags = explode("|",getConfig('disktag')); + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $envs[$k] = base64y_encode($v); + else $envs[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $envs[$disktag][$k] = base64y_encode($v); + else $envs[$disktag][$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $envs[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $envs[$newtag] = $envs[$v]; + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $envs[$k] = $v; + } + } + if ($indisk) { + $diskconfig = $envs[$disktag]; + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $envs[$disktag] = $diskconfig; + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $envs['disktag'] = implode('|', $tags); + $envs[$arr['disktag_newname']] = $envs[$arr['disktag_rename']]; + $envs[$arr['disktag_rename']] = ''; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $envs['disktag'] = substr($disktag_s, 0, -1); + else $envs['disktag'] = ''; + } + } + $envs = array_filter($envs, 'array_value_isnot_null'); + //ksort($envs); + $response = updateEnvironment($envs, $_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')); + WaitSCFStat($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')); + return $response; +} + +function WaitSCFStat($function_name, $Region, $Namespace, $SecretId, $SecretKey) +{ + $trynum = 0; + while( json_decode(getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey),true)['Response']['Status']!='Active' ) echo ' +'.++$trynum; +} + +function install() +{ + global $constStr; + if ($_GET['install2']) { + $tmp['admin'] = $_POST['admin']; + $response = setConfigResponse( setConfig($tmp) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } + if (needUpdate()) { + OnekeyUpate(); + return message('update to github version, reinstall. + + ', 'Program updating', 201, 1); + } + return message(getconstStr('Success') . ' + ', 201, 1); + } + if ($_GET['install1']) { + $tmp['timezone'] = $_COOKIE['timezone']; + $SecretId = $_POST['SecretId']; + $tmp['SecretId'] = $SecretId; + $SecretKey = $_POST['SecretKey']; + $tmp['SecretKey'] = $SecretKey; + $tmp['ONEMANAGER_CONFIG_SAVE'] = $_POST['ONEMANAGER_CONFIG_SAVE']; + $response = json_decode(SetbaseConfig($tmp, $_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], $SecretId, $SecretKey), true)['Response']; + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 201); + } else { + if ($tmp['ONEMANAGER_CONFIG_SAVE'] != 'file') { + $html = getconstStr('ONEMANAGER_CONFIG_SAVE_ENV') . '
' . getconstStr('Home') . ''; + $title = 'Reinstall'; + return message($html, $title, 201, 1); + } + $html .= ' +
+
+ +
+ '; + $title = getconstStr('SetAdminPassword'); + return message($html, $title, 201, 1); + } + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + //if (getConfig('SecretId')==''||getConfig('SecretKey')=='') + $html .= ' + '.getconstStr('Create').' SecretId & SecretKey
+
+
'; + $html .= ' +
+
'; + $html .= ' + +
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + $html .= ''.getconstStr('ClickInstall').', '.getconstStr('LogintoBind'); + $title = 'Install'; + return message($html, $title, 201); +} + +function post2url($url, $data) +{ + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_TIMEOUT, 5); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + $response = curl_exec($ch); + curl_close($ch); + //echo $response; + return $response; +} + +function ReorganizeDate($arr) +{ + $str = ''; + ksort($arr); + foreach ($arr as $k1 => $v1) { + $str .= '&' . $k1 . '=' . $v1; + } + $str = substr($str, 1); // remove first '&'. 去掉第一个& + return $str; +} + +function getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey) +{ + //$meth = 'GET'; + $meth = 'POST'; + $host = 'scf.tencentcloudapi.com'; + $tmpdata['Action'] = 'GetFunction'; + $tmpdata['FunctionName'] = $function_name; + $tmpdata['Namespace'] = $Namespace; + $tmpdata['Nonce'] = time(); + $tmpdata['Region'] = $Region; + $tmpdata['SecretId'] = $SecretId; + $tmpdata['Timestamp'] = time(); + $tmpdata['Token'] = ''; + $tmpdata['Version'] = '2018-04-16'; + $data = ReorganizeDate($tmpdata); + $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); + //echo urlencode($signStr); + //return file_get_contents('https://'.$url.'&Signature='.urlencode($signStr)); + return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); +} + +function getfunctioncodeurl($function_name, $Region, $Namespace, $SecretId, $SecretKey) +{ + //$meth = 'GET'; + $meth = 'POST'; + $host = 'scf.tencentcloudapi.com'; + $tmpdata['Action'] = 'GetFunctionAddress'; + $tmpdata['FunctionName'] = $function_name; + $tmpdata['Namespace'] = $Namespace; + $tmpdata['Nonce'] = time(); + $tmpdata['Region'] = $Region; + $tmpdata['SecretId'] = $SecretId; + $tmpdata['Timestamp'] = time(); + $tmpdata['Token'] = ''; + $tmpdata['Version'] = '2018-04-16'; + $data = ReorganizeDate($tmpdata); + $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); + //echo urlencode($signStr); + //return file_get_contents('https://'.$url.'&Signature='.urlencode($signStr)); + return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); +} + +function copyFolder($from, $to) +{ + if (substr($from, -1)=='/') $from = substr($from, 0, -1); + if (substr($to, -1)=='/') $to = substr($to, 0, -1); + if (!file_exists($to)) mkdir($to, 0777); + $handler=opendir($from); + while($filename=readdir($handler)) { + if($filename != '.' && $filename != '..'){ + $fromfile = $from.'/'.$filename; + $tofile = $to.'/'.$filename; + if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归 + copyFolder($fromfile, $tofile); + }else{ + copy($fromfile, $tofile); + } + } + } + closedir($handler); + return 1; +} + +function updateEnvironment($Envs, $function_name, $Region, $Namespace, $SecretId, $SecretKey) +{ + sortConfig($Envs); + // 获取当前代码并解压 + //$codeurl = json_decode(getfunctioncodeurl($function_name, $Region, $Namespace, $SecretId, $SecretKey), true)['Response']['Url']; + //$codezip = '/tmp/oldcode.zip'; + $outPath = '/tmp/code/'; + + //file_put_contents($codezip, file_get_contents($codeurl)); + //$zip=new ZipArchive(); + //$zip->open($codezip); + //$html = $zip->extractTo($outPath); + + $coderoot = __DIR__ . '/../'; + copyFolder($coderoot, $outPath); + + // 将配置写入 + $prestr = 'open($source, ZipArchive::CREATE)){ + addFileToZip($zip, $outPath); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 + // $zip->close(); //关闭处理的zip文件 + //} + + return updateProgram($function_name, $Region, $namespace, $SecretId, $SecretKey, $source); + $tmp1['Response']['Error']['Message'] = $codeurl; + error_log1($tmp1['Response']['Error']['Message']); + return json_encode($tmp1); +} + +function SetbaseConfig($Envs, $function_name, $Region, $Namespace, $SecretId, $SecretKey) +{ + if ($Envs['ONEMANAGER_CONFIG_SAVE'] == 'file') $tmp_env = Array( 'ONEMANAGER_CONFIG_SAVE' => 'file' ); + else { + $Envs['ONEMANAGER_CONFIG_SAVE'] == ''; + $tmp = json_decode(getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey),true)['Response']['Environment']['Variables']; + foreach ($tmp as $tmp1) { + $tmp_env[$tmp1['Key']] = $tmp1['Value']; + } + foreach ($Envs as $key1 => $value1) { + $tmp_env[$key1] = $value1; + } + $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 + ksort($tmp_env); + } + + $i = 0; + foreach ($tmp_env as $key1 => $value1) { + $tmpdata['Environment.Variables.'.$i.'.Key'] = $key1; + $tmpdata['Environment.Variables.'.$i.'.Value'] = $value1; + $i++; + } + + $meth = 'POST'; + $host = 'scf.tencentcloudapi.com'; + $tmpdata['Action'] = 'UpdateFunctionConfiguration'; + $tmpdata['FunctionName'] = $function_name; + $tmpdata['Namespace'] = $Namespace; + $tmpdata['Nonce'] = time(); + $tmpdata['Region'] = $Region; + $tmpdata['SecretId'] = $SecretId; + $tmpdata['Timestamp'] = time(); + $tmpdata['Token'] = ''; + $tmpdata['Version'] = '2018-04-16'; + $tmpdata['Description'] = 'Onedrive index and manager in Tencent SCF.'; + $tmpdata['MemorySize'] = 64; + $tmpdata['Timeout'] = 30; + $data = ReorganizeDate($tmpdata); + //echo $data; + $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); + //echo urlencode($signStr); + $response = post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); + if (api_error(setConfigResponse($response))) { + return $response; + } + if ( json_decode(getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey),true)['Response']['Timeout'] < 25 ) { + $tmp['Response']['Error']['Message'] = 'Operating, please try again.'; + $tmp['Response']['Error']['Code'] = 'Retry'; + return json_encode($tmp); + } + WaitSCFStat($function_name, $Region, $Namespace, $SecretId, $SecretKey); + + $s = file_get_contents('.data/config.php'); + //$configs = substr($s, 18, -2); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') $envs = json_decode($configs, true); + foreach ($Envs as $k => $v) { + $envs[$k] = $v; + } + $envs = array_filter($envs, 'array_value_isnot_null'); + //ksort($envs); + $response = updateEnvironment($envs, $function_name, $Region, $Namespace, $SecretId, $SecretKey); + return $response; +} + +function updateProgram($function_name, $Region, $Namespace, $SecretId, $SecretKey, $source) +{ + $secretId = $SecretId; + $secretKey = $SecretKey; + $host = 'scf.tencentcloudapi.com'; + $service = "scf"; + $version = "2018-04-16"; + $action = "UpdateFunctionCode"; + $region = $Region; + $timestamp = time(); + $algorithm = "TC3-HMAC-SHA256"; + + // step 1: build canonical request string + $httpRequestMethod = "POST"; + $canonicalUri = "/"; + $canonicalQueryString = ""; + $canonicalHeaders = "content-type:application/json; charset=utf-8\n"."host:".$host."\n"; + $signedHeaders = "content-type;host"; + + //$tmpdata['Action'] = 'UpdateFunctionCode'; + $tmpdata['Code']['ZipFile'] = base64_encode( file_get_contents($source) ); + $tmpdata['CodeSource'] = 'ZipFile'; + $tmpdata['FunctionName'] = $function_name; + $tmpdata['Handler'] = 'index.main_handler'; + //$tmpdata['Namespace'] = $Namespace; + //$tmpdata['Nonce'] = time(); + //$tmpdata['Region'] = $Region; + //$tmpdata['SecretId'] = $SecretId; + //$tmpdata['Timestamp'] = time(); + //$tmpdata['Token'] = ''; + //$tmpdata['Version'] = '2018-04-16'; + $payload = json_encode($tmpdata); + //$payload = '{"Limit": 1, "Filters": [{"Values": ["\u672a\u547d\u540d"], "Name": "instance-name"}]}'; + $hashedRequestPayload = hash("SHA256", $payload); + $canonicalRequest = $httpRequestMethod."\n" + .$canonicalUri."\n" + .$canonicalQueryString."\n" + .$canonicalHeaders."\n" + .$signedHeaders."\n" + .$hashedRequestPayload; + //echo $canonicalRequest.PHP_EOL; + + // step 2: build string to sign + $date = gmdate("Y-m-d", $timestamp); + $credentialScope = $date."/".$service."/tc3_request"; + $hashedCanonicalRequest = hash("SHA256", $canonicalRequest); + $stringToSign = $algorithm."\n" + .$timestamp."\n" + .$credentialScope."\n" + .$hashedCanonicalRequest; + //echo $stringToSign.PHP_EOL; + + // step 3: sign string + $secretDate = hash_hmac("SHA256", $date, "TC3".$secretKey, true); + $secretService = hash_hmac("SHA256", $service, $secretDate, true); + $secretSigning = hash_hmac("SHA256", "tc3_request", $secretService, true); + $signature = hash_hmac("SHA256", $stringToSign, $secretSigning); + //echo $signature.PHP_EOL; + + // step 4: build authorization + $authorization = $algorithm + ." Credential=".$secretId."/".$credentialScope + .", SignedHeaders=content-type;host, Signature=".$signature; + //echo $authorization.PHP_EOL; + + //$curl = "curl -X POST https://".$host + // .' -H "Authorization: '.$authorization.'"' + // .' -H "Content-Type: application/json; charset=utf-8"' + // .' -H "Host: '.$host.'"' + // .' -H "X-TC-Action: '.$action.'"' + // .' -H "X-TC-Timestamp: '.$timestamp.'"' + // .' -H "X-TC-Version: '.$version.'"' + // .' -H "X-TC-Region: '.$region.'"' + // ." -d '".$payload."'"; + //error_log1( $curl.PHP_EOL ); + //return '{"response": {"Error": {"Message":"' . $curl . '"}}}'; + $headers['Authorization'] = $authorization; + $headers['Content-Type'] = 'application/json; charset=utf-8'; + $headers['Host'] = $host; + $headers['X-TC-Action'] = $action; + $headers['X-TC-Timestamp'] = $timestamp; + $headers['X-TC-Version'] = $version; + $headers['X-TC-Region'] = $region; + return curl('POST', 'https://'.$host, $payload, $headers)['body']; +} + +function api_error($response) +{ + return isset($response['Error']); + return ($response==null)||isset($response['Error']); +} + +function api_error_msg($response) +{ + return $response['Error']['Code'] . '
+' . $response['Error']['Message'] . '

+function_name:' . $_SERVER['function_name'] . '
+Region:' . $_SERVER['Region'] . '
+namespace:' . $_SERVER['namespace'] . '
+'; +} + +function setConfigResponse($response) +{ + return json_decode( $response, true )['Response']; +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + $source = '/tmp/code.zip'; + $outPath = '/tmp/'; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return json_encode(['Response'=>['Error'=>['code'=>'Git Source input Error!']]]); + $tarfile = '/tmp/github.tar.gz'; + file_put_contents($tarfile, file_get_contents($url)); + $phar = new PharData($tarfile); + $html = $phar->extractTo($outPath, null, true);//路径 要解压的文件 是否覆盖 + + // 获取解压出的目录名 + $outPath = findIndexPath($outPath); + + // 放入配置文件 + file_put_contents($outPath . '/.data/config.php', file_get_contents(__DIR__ . '/../.data/config.php')); + + // 将目录中文件打包成zip + //$zip=new ZipArchive(); + $zip=new PharData($source); + //if($zip->open($source, ZipArchive::CREATE)){ + addFileToZip($zip, $outPath); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 + // $zip->close(); //关闭处理的zip文件 + //} + + return updateProgram($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey'), $source); +} + +function addFileToZip($zip, $rootpath, $path = '') +{ + if (substr($rootpath,-1)=='/') $rootpath = substr($rootpath, 0, -1); + if (substr($path,0,1)=='/') $path = substr($path, 1); + $handler=opendir(path_format($rootpath.'/'.$path)); //打开当前文件夹由$path指定。 + while($filename=readdir($handler)){ + if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作 + $nowname = path_format($rootpath.'/'.$path."/".$filename); + if(is_dir($nowname)){// 如果读取的某个对象是文件夹,则递归 + $zip->addEmptyDir($path."/".$filename); + addFileToZip($zip, $rootpath, $path."/".$filename); + }else{ //将文件加入zip对象 + $newname = $path."/".$filename; + if (substr($newname,0,1)=='/') $newname = substr($newname, 1); + $zip->addFile($nowname, $newname); + //$zip->renameName($nowname, $newname); + } + } + } + @closedir($handler); +} + +function WaitFunction() { + if ( json_decode(getfunctioninfo($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')),true)['Response']['Status']=='Active' ) return true; + else return false; +} + +function changeAuthKey() { + if ($_POST['SecretId']!=''&&$_POST['SecretId']!='') { + $tmp['SecretId'] = $_POST['SecretId']; + $tmp['SecretKey'] = $_POST['SecretKey']; + $response = setConfigResponse( SetbaseConfig($tmp, $_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], $tmp['SecretId'], $tmp['SecretKey']) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + $html = ' +
+ ' . getconstStr('Create') . ' SecretId & SecretKey
+
+
+ +
+ '; + return message($html, 'Change platform Auth token or key', 200); +} + +function smallfileupload($drive, $path) { + return output('Can not upload through SCF.', 400); +} diff --git a/platform/Vercel.php b/platform/Vercel.php new file mode 100644 index 0000000..1fea82d --- /dev/null +++ b/platform/Vercel.php @@ -0,0 +1,497 @@ +0) $path = substr($_SERVER['REQUEST_URI'], 0, $p); + else $path = $_SERVER['REQUEST_URI']; + $path = path_format( substr($path, strlen($_SERVER['base_path'])) ); + $_SERVER['DOCUMENT_ROOT'] = '/var/task/user'; + return $path; +} + +function getGET() +{ + if (!$_POST) { + if (!!$HTTP_RAW_POST_DATA) { + $tmpdata = $HTTP_RAW_POST_DATA; + } else { + $tmpdata = file_get_contents('php://input'); + } + if (!!$tmpdata) { + $postbody = explode("&", $tmpdata); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + } + } + if (isset($_SERVER['UNENCODED_URL'])) $_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL']; + $p = strpos($_SERVER['REQUEST_URI'],'?'); + if ($p>0) { + $getstr = substr($_SERVER['REQUEST_URI'], $p+1); + $getstrarr = explode("&",$getstr); + foreach ($getstrarr as $getvalues) { + if ($getvalues != '') { + $pos = strpos($getvalues, "="); + //echo $pos; + if ($pos > 0) { + $getarry[urldecode(substr($getvalues, 0, $pos))] = urldecode(substr($getvalues, $pos + 1)); + } else { + $getarry[urldecode($getvalues)] = true; + } + } + } + } + if (isset($getarry)) { + return $getarry; + } else { + return []; + } +} + +function getConfig($str, $disktag = '') +{ + $projectPath = splitlast(__DIR__, '/')[0]; + $configPath = $projectPath . '/.data/config.php'; + $s = file_get_contents($configPath); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') { + $envs = json_decode($configs, true); + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + if (isset($envs[$disktag][$str])) { + if (isBase64Env($str)) return base64y_decode($envs[$disktag][$str]); + else return $envs[$disktag][$str]; + } + } else { + if (isset($envs[$str])) { + if (isBase64Env($str)) return base64y_decode($envs[$str]); + else return $envs[$str]; + } + } + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + if ($disktag=='') $disktag = $_SERVER['disktag']; + $projectPath = splitlast(__DIR__, '/')[0]; + $configPath = $projectPath . '/.data/config.php'; + $s = file_get_contents($configPath); + $configs = '{' . splitlast(splitfirst($s, '{')[1], '}')[0] . '}'; + if ($configs!='') $envs = json_decode($configs, true); + $disktags = explode("|",getConfig('disktag')); + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $envs[$k] = base64y_encode($v); + else $envs[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $envs[$disktag][$k] = base64y_encode($v); + else $envs[$disktag][$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $envs[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $envs[$newtag] = $envs[$v]; + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $envs[$k] = $v; + } + } + if ($indisk) { + $diskconfig = $envs[$disktag]; + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $envs[$disktag] = $diskconfig; + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $envs['disktag'] = implode('|', $tags); + $envs[$arr['disktag_newname']] = $envs[$arr['disktag_rename']]; + $envs[$arr['disktag_rename']] = ''; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $envs['disktag'] = substr($disktag_s, 0, -1); + else $envs['disktag'] = ''; + } + } + $envs = array_filter($envs, 'array_value_isnot_null'); + //ksort($envs); + //sortConfig($envs); + //error_log1(json_encode($arr, JSON_PRETTY_PRINT) . ' => tmp:' . json_encode($envs, JSON_PRETTY_PRINT)); + //echo json_encode($arr, JSON_PRETTY_PRINT) . ' => tmp:' . json_encode($envs, JSON_PRETTY_PRINT); + return setVercelConfig($envs, getConfig('HerokuappId'), getConfig('APIKey')); +} + +function install() +{ + global $constStr; + if ($_GET['install1']) { + if ($_POST['admin']!='') { + $tmp['admin'] = $_POST['admin']; + //$tmp['language'] = $_POST['language']; + $tmp['timezone'] = $_COOKIE['timezone']; + $APIKey = $_POST['APIKey']; + //if ($APIKey=='') { + // $APIKey = getConfig('APIKey'); + //} + $tmp['APIKey'] = $APIKey; + + $token = $APIKey; + $header["Authorization"] = "Bearer " . $token; + $header["Content-Type"] = "application/json"; + $aliases = json_decode(curl("GET", "https://api.vercel.com/v3/now/aliases", "", $header)['body'], true); + $host = splitfirst($_SERVER["host"], "//")[1]; + foreach ($aliases["aliases"] as $key => $aliase) { + if ($host==$aliase["alias"]) $projectId = $aliase["projectId"]; + } + $tmp['HerokuappId'] = $projectId; + + $response = json_decode(setVercelConfig($tmp, $projectId, $APIKey), true); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + $html .= '
+ ' . getconstStr('Create') . ' token
+
'; + $html .= '
+
'; + $html .= ' + +
+
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + + if (substr($_SERVER["host"], -10)=="vercel.app") { + $html .= '' . getconstStr('ClickInstall') . ', ' . getconstStr('LogintoBind'); + $html .= "
Remember: you MUST wait 30-60s after each operate / do some change, that make sure Vercel has done the building
" ; + } else { + $html.= "Please visit form *.vercel.app"; + } + $title = 'Install'; + return message($html, $title, 201); +} + +function copyFolder($from, $to) +{ + if (substr($from, -1)=='/') $from = substr($from, 0, -1); + if (substr($to, -1)=='/') $to = substr($to, 0, -1); + if (!file_exists($to)) mkdir($to, 0777, 1); + $handler=opendir($from); + while($filename=readdir($handler)) { + if($filename != '.' && $filename != '..'){ + $fromfile = $from.'/'.$filename; + $tofile = $to.'/'.$filename; + if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归 + copyFolder($fromfile, $tofile); + }else{ + copy($fromfile, $tofile); + } + } + } + closedir($handler); + return 1; +} + +function setVercelConfig($envs, $appId, $token) +{ + sortConfig($envs); + $outPath = '/tmp/code/'; + $outPath_Api = $outPath . 'api/'; + $coderoot = __DIR__; + $coderoot = splitlast($coderoot, '/')[0] . '/'; + //echo $outPath_Api . '
' . $coderoot . '
'; + copyFolder($coderoot, $outPath_Api); + $prestr = '"; + getEachFiles($file, $sourcePath); + $data["files"] = $file; + + //echo json_encode($data, JSON_PRETTY_PRINT) . " ,data
"; + $response = curl("POST", $url, json_encode($data), $header); + //echo json_encode($response, JSON_PRETTY_PRINT) . " ,res
"; + $result = json_decode($response["body"], true); + $result['DplStatus'] = $result['id']; + return json_encode($result); +} + +function checkBuilding($projectId, $token) +{ + $r = 0; + $url = "https://api.vercel.com/v6/deployments/?projectId=" . $projectId; + $header["Authorization"] = "Bearer " . $token; + $header["Content-Type"] = "application/json"; + $response = curl("GET", $url, '', $header); + //echo json_encode($response, JSON_PRETTY_PRINT) . " ,res
"; + $result = json_decode($response["body"], true); + foreach ( $result['deployments'] as $deployment ) { + if ($deployment['state']!=="READY") $r++; + } + return $r; + //if ($r===0) return true; + //else return false; +} + +function getEachFiles(&$file, $base, $path = "") +{ + //if (substr($base, -1)=="/") $base = substr($base, 0, -1); + //if (substr($path, -1)=="/") $path = substr($path, 0, -1); + $handler=opendir(path_format($base . "/" . $path)); + while($filename=readdir($handler)) { + if($filename != '.' && $filename != '..' && $filename != '.git'){ + $fromfile = path_format($base . "/" . $path . "/" . $filename); + //echo $fromfile . "
"; + if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归 + $response = getEachFiles($file, $base, path_format($path . "/" . $filename)); + if (api_error(setConfigResponse($response))) return $response; + }else{ + $tmp['file'] = path_format($path . "/" . $filename); + $tmp['data'] = file_get_contents($fromfile); + $file[] = $tmp; + } + } + } + closedir($handler); + + return json_encode( [ 'response' => 'success' ] ); +} + +function api_error($response) +{ + return isset($response['error']); +} + +function api_error_msg($response) +{ + return $response['error']['code'] . '
+' . $response['error']['message'] . '
+'; +} + +function setConfigResponse($response) +{ + return json_decode($response, true); +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + $tmppath = '/tmp'; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return json_encode(['error'=>['code'=>'Git Source input Error!']]); + + $tarfile = $tmppath . '/github.tar.gz'; + file_put_contents($tarfile, file_get_contents($url)); + $phar = new PharData($tarfile); + $html = $phar->extractTo($tmppath, null, true);//路径 要解压的文件 是否覆盖 + unlink($tarfile); + + // 获取解压出的目录名 + $outPath = findIndexPath($tmppath); + + if ($outPath=='') return '{"error":{"message":"no outpath"}}'; + $name = $project . 'CODE'; + mkdir($tmppath . "/" . $name, 0777, 1); + rename($outPath, $tmppath . "/" . $name . '/api'); + $outPath = $tmppath . "/" . $name; + //echo $outPath . "
"; + //error_log1($outPath); + + // put in config + $coderoot = __DIR__; + $coderoot = splitlast($coderoot, '/')[0] . '/'; + copy($coderoot . '.data/config.php', $outPath . '/api/.data/config.php'); + + return VercelUpdate(getConfig('HerokuappId'), getConfig('APIKey'), $outPath); +} + +function WaitFunction($deployid = '') { + if ($buildId=='1') { + $tmp['stat'] = 400; + $tmp['body'] = 'id must provided.'; + return $tmp; + } + $header["Authorization"] = "Bearer " . getConfig('APIKey'); + $header["Content-Type"] = "application/json"; + $url = "https://api.vercel.com/v11/deployments/" . $deployid; + $response = curl("GET", $url, "", $header); + if ($response['stat']==200) { + $result = json_decode($response['body'], true); + if ($result['readyState']=="READY") return true; + if ($result['readyState']=="ERROR") return $response; + return false; + } else { + $response['body'] .= $url; + return $response; + } +} + +function changeAuthKey() { + if ($_POST['APIKey']!='') { + $APIKey = $_POST['APIKey']; + $tmp['APIKey'] = $APIKey; + $response = setConfigResponse( setVercelConfig($tmp, getConfig('HerokuappId'), $APIKey) ); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + $html = ' +
+ ' . getconstStr('Create') . ' token
+
+ +
+ '; + return message($html, 'Change platform Auth token or key', 200); +} + +function smallfileupload($drive, $path) { + if ($_FILES['file1']['error']) return output($_FILES['file1']['error'], 400); + if ($_FILES['file1']['size']>4*1024*1024) return output('File too large', 400); + return $drive->smallfileupload($path, $_FILES['file1']); +} diff --git a/platform/Vercel_env.php b/platform/Vercel_env.php new file mode 100644 index 0000000..c0f3607 --- /dev/null +++ b/platform/Vercel_env.php @@ -0,0 +1,473 @@ +0) $path = substr($_SERVER['REQUEST_URI'], 0, $p); + else $path = $_SERVER['REQUEST_URI']; + $path = path_format( substr($path, strlen($_SERVER['base_path'])) ); + $_SERVER['DOCUMENT_ROOT'] = '/var/task/user'; + return $path; +} + +function getGET() +{ + if (!$_POST) { + if (!!$HTTP_RAW_POST_DATA) { + $tmpdata = $HTTP_RAW_POST_DATA; + } else { + $tmpdata = file_get_contents('php://input'); + } + if (!!$tmpdata) { + $postbody = explode("&", $tmpdata); + foreach ($postbody as $postvalues) { + $pos = strpos($postvalues,"="); + $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); + } + } + } + if (isset($_SERVER['UNENCODED_URL'])) $_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL']; + $p = strpos($_SERVER['REQUEST_URI'],'?'); + if ($p>0) { + $getstr = substr($_SERVER['REQUEST_URI'], $p+1); + $getstrarr = explode("&",$getstr); + foreach ($getstrarr as $getvalues) { + if ($getvalues != '') { + $pos = strpos($getvalues, "="); + //echo $pos; + if ($pos > 0) { + $getarry[urldecode(substr($getvalues, 0, $pos))] = urldecode(substr($getvalues, $pos + 1)); + } else { + $getarry[urldecode($getvalues)] = true; + } + } + } + } + if (isset($getarry)) { + return $getarry; + } else { + return []; + } +} + +function getConfig($str, $disktag = '') +{ + if (isInnerEnv($str)) { + if ($disktag=='') $disktag = $_SERVER['disktag']; + $tmp = getenv($disktag); + if (is_array($tmp)) $env = $tmp; + else $env = json_decode($tmp, true); + if (isset($env[$str])) { + if (isBase64Env($str)) return base64y_decode($env[$str]); + else return $env[$str]; + } + } else { + if (isBase64Env($str)) return base64y_decode(getenv($str)); + else return getenv($str); + } + return ''; +} + +function setConfig($arr, $disktag = '') +{ + if ($disktag=='') $disktag = $_SERVER['disktag']; + $disktags = explode("|", getenv('disktag')); + if ($disktag!='') { + $tmp = getenv($disktag); + if (is_array($tmp)) $diskconfig = $tmp; + else $diskconfig = json_decode($tmp, true); + } + $tmp = []; + $indisk = 0; + $operatedisk = 0; + foreach ($arr as $k => $v) { + if (isCommonEnv($k)) { + if (isBase64Env($k)) $tmp[$k] = base64y_encode($v); + else $tmp[$k] = $v; + } elseif (isInnerEnv($k)) { + if (isBase64Env($k)) $diskconfig[$k] = base64y_encode($v); + else $diskconfig[$k] = $v; + $indisk = 1; + } elseif ($k=='disktag_add') { + array_push($disktags, $v); + $operatedisk = 1; + } elseif ($k=='disktag_del') { + $disktags = array_diff($disktags, [ $v ]); + $tmp[$v] = ''; + $operatedisk = 1; + } elseif ($k=='disktag_copy') { + $newtag = $v . '_' . date("Ymd_His"); + $tagvalue = getenv($v); + if (is_array($tagvalue)) $tmp[$newtag] = json_encode($tagvalue); + else $tmp[$newtag] = $tagvalue; + array_push($disktags, $newtag); + $operatedisk = 1; + } elseif ($k=='disktag_rename' || $k=='disktag_newname') { + if ($arr['disktag_rename']!=$arr['disktag_newname']) $operatedisk = 1; + } else { + $tmp[$k] = json_encode($v); + } + } + if ($indisk) { + $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); + ksort($diskconfig); + $tmp[$disktag] = json_encode($diskconfig); + } + if ($operatedisk) { + if (isset($arr['disktag_newname']) && $arr['disktag_newname']!='') { + $tags = []; + foreach ($disktags as $tag) { + if ($tag==$arr['disktag_rename']) array_push($tags, $arr['disktag_newname']); + else array_push($tags, $tag); + } + $tmp['disktag'] = implode('|', $tags); + $tagvalue = getenv($arr['disktag_rename']); + if (is_array($tagvalue)) $tmp[$arr['disktag_newname']] = json_encode($tagvalue); + else $tmp[$arr['disktag_newname']] = $tagvalue; + $tmp[$arr['disktag_rename']] = null; + } else { + $disktags = array_unique($disktags); + foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; + if ($disktag_s!='') $tmp['disktag'] = substr($disktag_s, 0, -1); + else $tmp['disktag'] = null; + } + } + foreach ($tmp as $key => $val) if ($val=='') $tmp[$key]=null; + + //error_log1(json_encode($arr, JSON_PRETTY_PRINT) . ' => tmp:' . json_encode($tmp, JSON_PRETTY_PRINT)); + //echo json_encode($arr, JSON_PRETTY_PRINT) . ' => tmp:' . json_encode($tmp, JSON_PRETTY_PRINT); + return setVercelConfig($tmp, getConfig('HerokuappId'), getConfig('APIKey')); +} + +function install() +{ + global $constStr; + if ($_GET['install1']) { + if ($_POST['admin']!='') { + $tmp['admin'] = $_POST['admin']; + //$tmp['language'] = $_POST['language']; + $tmp['timezone'] = $_COOKIE['timezone']; + $APIKey = $_POST['APIKey']; + $tmp['APIKey'] = $APIKey; + + $token = $APIKey; + $header["Authorization"] = "Bearer " . $token; + $header["Content-Type"] = "application/json"; + $aliases = json_decode(curl("GET", "https://api.vercel.com/v3/now/aliases", "", $header)['body'], true); + $host = splitfirst($_SERVER["host"], "//")[1]; + foreach ($aliases["aliases"] as $key => $aliase) { + if ($host==$aliase["alias"]) $projectId = $aliase["projectId"]; + } + $tmp['HerokuappId'] = $projectId; + + $response = json_decode(setVercelConfig($tmp, $projectId, $APIKey), true); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + } + if ($_GET['install0']) { + $html .= ' +
+language:
'; + foreach ($constStr['languages'] as $key1 => $value1) { + $html .= ' +
'; + } + $html .= '
+ ' . getconstStr('Create') . ' token
+
'; + $html .= '
+
'; + $html .= ' + +
+
+ '; + $title = getconstStr('SelectLanguage'); + return message($html, $title, 201); + } + + if (substr($_SERVER["host"], -10)=="vercel.app") { + $html .= '' . getconstStr('ClickInstall') . ', ' . getconstStr('LogintoBind'); + $html .= "
Remember: you MUST wait 30-60s after each operate / do some change, that make sure Vercel has done the building
" ; + } else { + $html.= "Please visit form *.vercel.app"; + } + $title = 'Install'; + return message($html, $title, 201); +} + +// POST /v8/projects/:id/env +function setVercelConfig($envs, $appId, $token) +{ + $url = "https://api.vercel.com/v8/projects/" . $appId . "/env"; + $header["Authorization"] = "Bearer " . $token; + $header["Content-Type"] = "application/json"; + $response = curl("GET", $url, "", $header); + $result = json_decode($response['body'], true); + foreach ($result["envs"] as $key => $value) { + $existEnvs[$value["key"]] = $value["id"]; + } + foreach ($envs as $key => $value) { + $response = null; + $tmp = null; + $tmp["type"] = "encrypted"; + $tmp["key"] = $key; + $tmp["value"] = $value; + $tmp["target"] = [ "development", "production", "preview" ]; + if (isset($existEnvs[$key])) { + if ($value) $response = curl("PATCH", $url . "/" . $existEnvs[$key], json_encode($tmp), $header); + else $response = curl("DELETE", $url . "/" . $existEnvs[$key], "", $header); + } else { + if ($value) $response = curl("POST", $url, json_encode($tmp), $header); + } + //echo $key . " = " . $value . ",
" . $response . json_encode($response, JSON_PRETTY_PRINT) . "
"; + if (!!$response && $response['stat']!=200) return $response['body']; + } + return VercelUpdate($appId, $token); +} + +function VercelUpdate($appId, $token, $sourcePath = "") +{ + if (checkBuilding($appId, $token)) return '{"error":{"message":"Another building is in progress."}}'; + $url = "https://api.vercel.com/v13/deployments"; + $header["Authorization"] = "Bearer " . $token; + $header["Content-Type"] = "application/json"; + $data["name"] = "OneManager"; + $data["project"] = $appId; + $data["target"] = "production"; + $data["routes"][0]["src"] = "/(.*)"; + $data["routes"][0]["dest"] = "/api/index.php"; + $data["functions"]["api/index.php"]["runtime"] = "vercel-php@0.4.0"; + if ($sourcePath=="") $sourcePath = splitlast(splitlast(__DIR__, "/")[0], "/")[0]; + //echo $sourcePath . "
"; + getEachFiles($file, $sourcePath); + $data["files"] = $file; + + //echo json_encode($data, JSON_PRETTY_PRINT) . " ,data
"; + $response = curl("POST", $url, json_encode($data), $header); + //echo json_encode($response, JSON_PRETTY_PRINT) . " ,res
"; + $result = json_decode($response["body"], true); + $result['DplStatus'] = $result['id']; + return json_encode($result); +} + +function checkBuilding($projectId, $token) +{ + $r = 0; + $url = "https://api.vercel.com/v6/deployments/?projectId=" . $projectId; + $header["Authorization"] = "Bearer " . $token; + $header["Content-Type"] = "application/json"; + $response = curl("GET", $url, '', $header); + //echo json_encode($response, JSON_PRETTY_PRINT) . " ,res
"; + $result = json_decode($response["body"], true); + foreach ( $result['deployments'] as $deployment ) { + if ($deployment['state']!=="READY") $r++; + } + return $r; + //if ($r===0) return true; + //else return false; +} + +function getEachFiles(&$file, $base, $path = "") +{ + //if (substr($base, -1)=="/") $base = substr($base, 0, -1); + //if (substr($path, -1)=="/") $path = substr($path, 0, -1); + $handler=opendir(path_format($base . "/" . $path)); + while($filename=readdir($handler)) { + if($filename != '.' && $filename != '..' && $filename != '.git'){ + $fromfile = path_format($base . "/" . $path . "/" . $filename); + //echo $fromfile . "
"; + if(is_dir($fromfile)){// 如果读取的某个对象是文件夹,则递归 + $response = getEachFiles($file, $base, path_format($path . "/" . $filename)); + if (api_error(setConfigResponse($response))) return $response; + }else{ + $tmp['file'] = path_format($path . "/" . $filename); + $tmp['data'] = file_get_contents($fromfile); + $file[] = $tmp; + } + } + } + closedir($handler); + + return json_encode( [ 'response' => 'success' ] ); +} + +function api_error($response) +{ + return isset($response['error']); +} + +function api_error_msg($response) +{ + return $response['error']['code'] . '
+' . $response['error']['message'] . '
+'; +} + +function setConfigResponse($response) +{ + return json_decode($response, true); +} + +function OnekeyUpate($GitSource = 'Github', $auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') +{ + $tmppath = '/tmp'; + + if ($GitSource=='Github') { + // 从github下载对应tar.gz,并解压 + $url = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . urlencode($branch) . '/'; + } elseif ($GitSource=='HITGitlab') { + $url = 'https://git.hit.edu.cn/' . $auth . '/' . $project . '/-/archive/' . urlencode($branch) . '/' . $project . '-' . urlencode($branch) . '.tar.gz'; + } else return json_encode(['error'=>['code'=>'Git Source input Error!']]); + + $tarfile = $tmppath . '/github.tar.gz'; + file_put_contents($tarfile, file_get_contents($url)); + $phar = new PharData($tarfile); + $html = $phar->extractTo($tmppath, null, true);//路径 要解压的文件 是否覆盖 + unlink($tarfile); + + // 获取解压出的目录名 + $outPath = findIndexPath($tmppath); + + if ($outPath=='') return '{"error":{"message":"no outpath"}}'; + $name = $project . 'CODE'; + mkdir($tmppath . "/" . $name, 0777, 1); + rename($outPath, $tmppath . "/" . $name . '/api'); + $outPath = $tmppath . "/" . $name; + //echo $outPath . "
"; + //error_log1($outPath); + + return VercelUpdate(getConfig('HerokuappId'), getConfig('APIKey'), $outPath); +} + +function WaitFunction($deployid) { + if ($buildId=='1') { + $tmp['stat'] = 400; + $tmp['body'] = 'id must provided.'; + return $tmp; + } + $header["Authorization"] = "Bearer " . getConfig('APIKey'); + $header["Content-Type"] = "application/json"; + $url = "https://api.vercel.com/v11/deployments/" . $deployid; + $response = curl("GET", $url, "", $header); + if ($response['stat']==200) { + $result = json_decode($response['body'], true); + if ($result['readyState']=="READY") return true; + if ($result['readyState']=="ERROR") return $response; + return false; + } else { + $response['body'] .= $url; + return $response; + } +} + +function changeAuthKey() { + if ($_POST['APIKey']!='') { + $APIKey = $_POST['APIKey']; + $tmp['APIKey'] = $APIKey; + $response = json_decode(setVercelConfig($tmp, getConfig('HerokuappId'), $APIKey), true); + if (api_error($response)) { + $html = api_error_msg($response); + $title = 'Error'; + return message($html, $title, 400); + } else { + $html = getconstStr('Success') . ' + '; + return message($html, $title, 201, 1); + } + } + $html = ' +
+ ' . getconstStr('Create') . ' token
+
+ +
+ '; + return message($html, 'Change platform Auth token or key', 200); +} diff --git a/platform/heroku.php b/platform/heroku.php deleted file mode 100644 index d243a0a..0000000 --- a/platform/heroku.php +++ /dev/null @@ -1,260 +0,0 @@ -0) $path = substr($_SERVER['REQUEST_URI'], 0, $p); - else $path = $_SERVER['REQUEST_URI']; - $path = path_format( substr($path, strlen($_SERVER['base_path'])) ); - return substr($path, 1); - //return spurlencode($path, '/'); -} - -function getGET() -{ - $p = strpos($_SERVER['REQUEST_URI'],'?'); - if ($p>0) { - $getstr = substr($_SERVER['REQUEST_URI'], $p+1); - $getstrarr = explode("&",$getstr); - foreach ($getstrarr as $getvalues) { - if ($getvalues != '') { - $pos = strpos($getvalues, "="); - //echo $pos; - if ($pos > 0) { - $getarry[urldecode(substr($getvalues, 0, $pos))] = urldecode(substr($getvalues, $pos + 1)); - } else { - $getarry[urldecode($getvalues)] = true; - } - } - } - } - if (isset($getarry)) { - return $getarry; - } else { - return []; - } -} - -function getConfig($str, $disktag = '') -{ - global $InnerEnv; - global $Base64Env; - if (in_array($str, $InnerEnv)) { - if ($disktag=='') $disktag = $_SERVER['disktag']; - $env = json_decode(getenv($disktag), true); - if (isset($env[$str])) { - if (in_array($str, $Base64Env)) return equal_replace($env[$str],1); - else return $env[$str]; - } - } else { - if (in_array($str, $Base64Env)) return equal_replace(getenv($str),1); - else return getenv($str); - } - return ''; -} - -function setConfig($arr, $disktag = '') -{ - global $InnerEnv; - global $Base64Env; - if ($disktag=='') $disktag = $_SERVER['disktag']; - $disktags = explode("|",getConfig('disktag')); - $diskconfig = json_decode(getenv($disktag), true); - $tmp = []; - $indisk = 0; - $oparetdisk = 0; - foreach ($arr as $k => $v) { - if (in_array($k, $InnerEnv)) { - if (in_array($k, $Base64Env)) $diskconfig[$k] = equal_replace($v); - else $diskconfig[$k] = $v; - $indisk = 1; - } elseif ($k=='disktag_add') { - array_push($disktags, $v); - $oparetdisk = 1; - } elseif ($k=='disktag_del') { - $disktags = array_diff($disktags, [ $v ]); - $tmp[$v] = ''; - $oparetdisk = 1; - } else { - if (in_array($k, $Base64Env)) $tmp[$k] = equal_replace($v); - else $tmp[$k] = $v; - } - } - if ($indisk) { - $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); - ksort($diskconfig); - $tmp[$disktag] = json_encode($diskconfig); - } - if ($oparetdisk) { - $disktags = array_unique($disktags); - foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; - if ($disktag_s!='') $tmp['disktag'] = substr($disktag_s, 0, -1); - else $tmp['disktag'] = ''; - } - foreach ($tmp as $key => $val) if ($val=='') $tmp[$key]=null; -// echo '正式设置:'.json_encode($tmp,JSON_PRETTY_PRINT).' -//'; - return setHerokuConfig($tmp, getConfig('function_name'), getConfig('APIKey')); -} - -function install() -{ - global $constStr; - if ($_GET['install1']) { - if ($_POST['admin']!='') { - $tmp['admin'] = $_POST['admin']; - $tmp['language'] = $_POST['language']; - $tmp['timezone'] = $_COOKIE['timezone']; - $APIKey = getConfig('APIKey'); - if ($APIKey=='') { - $APIKey = $_POST['APIKey']; - $tmp['APIKey'] = $APIKey; - } - $function_name = getConfig('function_name'); - if ($function_name=='') { - $tmp1 = substr($_SERVER['HTTP_HOST'], 0, strrpos($_SERVER['HTTP_HOST'], '.')); - $maindomain = substr($tmp1, strrpos($tmp1, '.')+1); - if ($maindomain=='herokuapp') $function_name = substr($tmp1, 0, strrpos($tmp1, '.')); - else $function_name = 'visit from xxxx.herokuapp.com'; - $tmp['function_name'] = $function_name; - } - $response = json_decode(setHerokuConfig($tmp, $function_name, $APIKey)['body'], true); - if (api_error($response)) { - $html = api_error_msg($response); - $title = 'Error'; - } else { - return output('Jump', 302); - } - return message($html, $title, 201); - } - } - if ($_GET['install0']) { - $html .= ' -
-language:
'; - foreach ($constStr['languages'] as $key1 => $value1) { - $html .= ' -
'; - } - if (getConfig('APIKey')=='') $html .= ' - '.getconstStr('Create').' API Key
-
'; - $html .= ' -
'; - $html .= ' - -
- '; - $title = getconstStr('SelectLanguage'); - return message($html, $title, 201); - } - $html .= ''.getconstStr('ClickInstall').', '.getconstStr('LogintoBind'); - $title = 'Error'; - return message($html, $title, 201); -} - -function HerokuAPI($method, $url, $data = '', $apikey) -{ - if ($method=='PATCH'||$method=='POST') { - $headers['Content-Type'] = 'application/json'; - } - $headers['Authorization'] = 'Bearer ' . $apikey; - $headers['Accept'] = 'application/vnd.heroku+json; version=3'; - //if (!isset($headers['Accept'])) $headers['Accept'] = '*/*'; - //if (!isset($headers['Referer'])) $headers['Referer'] = $url; - $sendHeaders = array(); - foreach ($headers as $headerName => $headerVal) { - $sendHeaders[] = $headerName . ': ' . $headerVal; - } - error_log($method . $url . $data . $apikey); - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST,$method); - curl_setopt($ch, CURLOPT_POSTFIELDS,$data); - curl_setopt($ch, CURLOPT_TIMEOUT, 5); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders); - $response['body'] = curl_exec($ch); - $response['stat'] = curl_getinfo($ch,CURLINFO_HTTP_CODE); - curl_close($ch); - error_log($response['stat'].' -'.$response['body'].' -'); - return $response; -} - -function getHerokuConfig($function_name, $apikey) -{ - return HerokuAPI('GET', 'https://api.heroku.com/apps/' . $function_name . '/config-vars', '', $apikey); -} - -function setHerokuConfig($env, $function_name, $apikey) -{ - $data = json_encode($env); - return HerokuAPI('PATCH', 'https://api.heroku.com/apps/' . $function_name . '/config-vars', $data, $apikey); -} - -function updateHerokuapp($function_name, $apikey, $source) -{ - $tmp['source_blob']['url'] = $source; - $data = json_encode($tmp); - return HerokuAPI('POST', 'https://api.heroku.com/apps/' . $function_name . '/builds', $data, $apikey); -} - -function api_error($response) -{ - return isset($response['id'])&&isset($response['message']); -} - -function api_error_msg($response) -{ - return $response['id'] . '
-' . $response['message'] . '

-function_name:' . $_SERVER['function_name'] . '
-'; -} - -function OnekeyUpate($auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') -{ - //'https://github.com/qkqpttgf/OneManager-php/tarball/master/'; - $source = 'https://github.com/' . $auth . '/' . $project . '/tarball/' . $branch . '/'; - return json_decode(updateHerokuapp(getConfig('function_name'), getConfig('APIKey'), $source)['body'], true); -} - -function setConfigResponse($response) -{ - return json_decode( $response['body'], true ); -} diff --git a/platform/normal.php b/platform/normal.php deleted file mode 100644 index 07bca30..0000000 --- a/platform/normal.php +++ /dev/null @@ -1,262 +0,0 @@ -0) $path = substr($_SERVER['REQUEST_URI'], 0, $p); - else $path = $_SERVER['REQUEST_URI']; - $path = path_format( substr($path, strlen($_SERVER['base_path'])) ); - return substr($path, 1); - //return spurlencode($path, '/'); -} - -function getGET() -{ - $p = strpos($_SERVER['REQUEST_URI'],'?'); - if ($p>0) { - $getstr = substr($_SERVER['REQUEST_URI'], $p+1); - $getstrarr = explode("&",$getstr); - foreach ($getstrarr as $getvalues) { - if ($getvalues != '') { - $pos = strpos($getvalues, "="); - //echo $pos; - if ($pos > 0) { - $getarry[urldecode(substr($getvalues, 0, $pos))] = urldecode(substr($getvalues, $pos + 1)); - } else { - $getarry[urldecode($getvalues)] = true; - } - } - } - } - if (isset($getarry)) { - return $getarry; - } else { - return []; - } -} - -function getConfig($str, $disktag = '') -{ - global $InnerEnv; - global $Base64Env; - //include 'config.php'; - $s = file_get_contents('config.php'); - $configs = substr($s, 18, -2); - if ($configs!='') { - $envs = json_decode($configs, true); - if (in_array($str, $InnerEnv)) { - if ($disktag=='') $disktag = $_SERVER['disktag']; - if (isset($envs[$disktag][$str])) { - if (in_array($str, $Base64Env)) return equal_replace($envs[$disktag][$str],1); - else return $envs[$disktag][$str]; - } - } else { - if (isset($envs[$str])) { - if (in_array($str, $Base64Env)) return equal_replace($envs[$str],1); - else return $envs[$str]; - } - } - } - return ''; -} - -function setConfig($arr, $disktag = '') -{ - global $InnerEnv; - global $Base64Env; - if ($disktag=='') $disktag = $_SERVER['disktag']; - //include 'config.php'; - $s = file_get_contents('config.php'); - $configs = substr($s, 18, -2); - if ($configs!='') $envs = json_decode($configs, true); - $disktags = explode("|",getConfig('disktag')); - //$indisk = 0; - $operatedisk = 0; - foreach ($arr as $k => $v) { - if (in_array($k, $InnerEnv)) { - if (in_array($k, $Base64Env)) $envs[$disktag][$k] = equal_replace($v); - else $envs[$disktag][$k] = $v; - /*$diskconfig[$k] = $v; - $indisk = 1;*/ - } elseif ($k=='disktag_add') { - array_push($disktags, $v); - $operatedisk = 1; - } elseif ($k=='disktag_del') { - $disktags = array_diff($disktags, [ $v ]); - $envs[$v] = ''; - $operatedisk = 1; - } else { - if (in_array($k, $Base64Env)) $envs[$k] = equal_replace($v); - else $envs[$k] = $v; - } - } - /*if ($indisk) { - $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); - ksort($diskconfig); - $tmp[$disktag] = json_encode($diskconfig); - }*/ - if ($operatedisk) { - $disktags = array_unique($disktags); - foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; - if ($disktag_s!='') $envs['disktag'] = substr($disktag_s, 0, -1); - else $envs['disktag'] = ''; - } - $envs = array_filter($envs, 'array_value_isnot_null'); - ksort($envs); - //echo '
'. json_encode($envs, JSON_PRETTY_PRINT).'
'; - $prestr = 'document.cookie=\'language=; path=/\';', 302); - } - } - } - if ($_GET['install1']) { - if (!ConfigWriteable()) { - $html .= getconstStr('MakesuerWriteable'); - $title = 'Error'; - return message($html, $title, 201); - } - /*if (!RewriteEngineOn()) { - $html .= getconstStr('MakesuerRewriteOn'); - $title = 'Error'; - return message($html, $title, 201); - }*/ - $html .= ' - - '; - $title = getconstStr('SetAdminPassword'); - return message($html, $title, 201); - } - if ($_GET['install0']) { - $html .= ' -
-language:
'; - foreach ($constStr['languages'] as $key1 => $value1) { - $html .= ' -
'; - } - $html .= ' - -
- '; - $title = getconstStr('SelectLanguage'); - return message($html, $title, 201); - } - $html .= ''.getconstStr('ClickInstall').', '.getconstStr('LogintoBind'); - $title = 'Error'; - return message($html, $title, 201); -} - -function ConfigWriteable() -{ - $t = md5( md5(time()).rand(1000,9999) ); - $r = setConfig([ 'tmp' => $t ]); - $tmp = getConfig('tmp'); - setConfig([ 'tmp' => '' ]); - if ($tmp == $t) return true; - if ($r) return true; - return false; -} - -function RewriteEngineOn() -{ - $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://'; - $tmpurl = $http_type . $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT']; - $tmpurl .= path_format($_SERVER['base_path'] . '/config.php'); - $tmp = curl_request($tmpurl); - if ($tmp['stat']==200) return false; - if ($tmp['stat']==201) return true; //when install return 201, after installed return 404 or 200; - return false; -} - -function api_error($response) -{ - return !$response; -} - -function api_error_msg($response) -{ - return $response . '
-Can not write config to file.
-'; -} - -function OnekeyUpate() -{ - return json_decode(updateHerokuapp(getConfig('function_name'), getConfig('APIKey'))['body'], true); -} - -function setConfigResponse($response) -{ - return $response; -} diff --git a/platform/scf.php b/platform/scf.php deleted file mode 100644 index 84cb5ee..0000000 --- a/platform/scf.php +++ /dev/null @@ -1,429 +0,0 @@ -500) $event['body']=substr($event['body'],0,strpos($event['body'],'base64')+30) . '...Too Long!...' . substr($event['body'],-50); - echo urldecode(json_encode($event, JSON_PRETTY_PRINT)) . ' - -' . urldecode(json_encode($context, JSON_PRETTY_PRINT)) . ' - -'; -} - -function GetGlobalVariable($event) -{ - $_GET = $event['queryString']; - $postbody = explode("&",$event['body']); - foreach ($postbody as $postvalues) { - $pos = strpos($postvalues,"="); - $_POST[urldecode(substr($postvalues,0,$pos))]=urldecode(substr($postvalues,$pos+1)); - } - $cookiebody = explode("; ",$event['headers']['cookie']); - foreach ($cookiebody as $cookievalues) { - $pos = strpos($cookievalues,"="); - $_COOKIE[urldecode(substr($cookievalues,0,$pos))]=urldecode(substr($cookievalues,$pos+1)); - } - $_SERVER['USER'] = 'qcloud'; -} - -function GetPathSetting($event, $context) -{ - $_SERVER['firstacceptlanguage'] = strtolower(splitfirst(splitfirst($event['headers']['accept-language'],';')[0],',')[0]); - $_SERVER['function_name'] = $context['function_name']; - $_SERVER['namespace'] = $context['namespace']; - $host_name = $event['headers']['host']; - $_SERVER['HTTP_HOST'] = $host_name; - $serviceId = $event['requestContext']['serviceId']; - if ( $serviceId === substr($host_name,0,strlen($serviceId)) ) { - $_SERVER['base_path'] = '/'.$event['requestContext']['stage'].'/'.$_SERVER['function_name'].'/'; - $_SERVER['Region'] = getenv('Region'); - if ($_SERVER['Region'] == '') { - $_SERVER['Region'] = substr($host_name, strpos($host_name, '.')+1); - $_SERVER['Region'] = substr($_SERVER['Region'], 0, strpos($_SERVER['Region'], '.')); - } - $path = substr($event['path'], strlen('/'.$_SERVER['function_name'].'/')); - } else { - $_SERVER['base_path'] = $event['requestContext']['path']; - $_SERVER['Region'] = getenv('Region'); - $path = substr($event['path'], strlen($event['requestContext']['path'])); - } - if (substr($path,-1)=='/') $path=substr($path,0,-1); - $_SERVER['is_guestup_path'] = is_guestup_path($path); - $_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path); - $_SERVER['REMOTE_ADDR'] = $event['requestContext']['sourceIp']; - $_SERVER['HTTP_X_REQUESTED_WITH'] = $event['headers']['x-requested-with']; - return $path; -} - -function getConfig($str, $disktag = '') -{ - global $InnerEnv; - global $Base64Env; - if (in_array($str, $InnerEnv)) { - if ($disktag=='') $disktag = $_SERVER['disktag']; - $env = json_decode(getenv($disktag), true); - if (isset($env[$str])) { - if (in_array($str, $Base64Env)) return equal_replace($env[$str],1); - else return $env[$str]; - } - } else { - if (in_array($str, $Base64Env)) return equal_replace(getenv($str),1); - else return getenv($str); - } - return ''; -} - -function setConfig($arr, $disktag = '') -{ - global $InnerEnv; - global $Base64Env; - if ($disktag=='') $disktag = $_SERVER['disktag']; - $disktags = explode("|",getConfig('disktag')); - $diskconfig = json_decode(getenv($disktag), true); - $tmp = []; - $indisk = 0; - $oparetdisk = 0; - foreach ($arr as $k => $v) { - if (in_array($k, $InnerEnv)) { - if (in_array($k, $Base64Env)) $diskconfig[$k] = equal_replace($v); - else $diskconfig[$k] = $v; - $indisk = 1; - } elseif ($k=='disktag_add') { - array_push($disktags, $v); - $oparetdisk = 1; - } elseif ($k=='disktag_del') { - $disktags = array_diff($disktags, [ $v ]); - $tmp[$v] = ''; - $oparetdisk = 1; - } else { - if (in_array($k, $Base64Env)) $tmp[$k] = equal_replace($v); - else $tmp[$k] = $v; - } - } - if ($indisk) { - $diskconfig = array_filter($diskconfig, 'array_value_isnot_null'); - ksort($diskconfig); - $tmp[$disktag] = json_encode($diskconfig); - } - if ($oparetdisk) { - $disktags = array_unique($disktags); - foreach ($disktags as $disktag) if ($disktag!='') $disktag_s .= $disktag . '|'; - if ($disktag_s!='') $tmp['disktag'] = substr($disktag_s, 0, -1); - else $tmp['disktag'] = ''; - } -// echo '正式设置:'.json_encode($tmp,JSON_PRETTY_PRINT).' -//'; - $response = updateEnvironment($tmp, $_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')); - WaitSCFStat(); - return $response; -} - -function WaitSCFStat() -{ - $trynum = 0; - while( json_decode(getfunctioninfo($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey')),true)['Response']['Status']!='Active' ) echo ' -'.++$trynum; -} - -function install() -{ - global $constStr; - if ($_GET['install2']) { - $tmp['admin'] = $_POST['admin']; - setConfig($tmp); - if (needUpdate()) { - OnekeyUpate(); - return message('update to github version, reinstall.', 'Program updating', 201); - } - return output('Jump', 302); - } - if ($_GET['install1']) { - //if ($_POST['admin']!='') { - $tmp['language'] = $_POST['language']; - $tmp['Region'] = $_POST['Region']; - $tmp['timezone'] = $_COOKIE['timezone']; - $SecretId = getConfig('SecretId'); - if ($SecretId=='') { - $SecretId = $_POST['SecretId']; - $tmp['SecretId'] = $SecretId; - } - $SecretKey = getConfig('SecretKey'); - if ($SecretKey=='') { - $SecretKey = $_POST['SecretKey']; - $tmp['SecretKey'] = $SecretKey; - } - $response = json_decode(SetbaseConfig($tmp, $_SERVER['function_name'], $_POST['Region'], $_SERVER['namespace'], $SecretId, $SecretKey), true)['Response']; - if (api_error($response)) { - $html = api_error_msg($response); - $title = 'Error'; - return message($html, $title, 201); - } else { - $html .= ' -
-
- -
- '; - $title = getconstStr('SetAdminPassword'); - return message($html, $title, 201); - } - //} - } - if ($_GET['install0']) { - $html .= ' -
-language:
'; - foreach ($constStr['languages'] as $key1 => $value1) { - $html .= ' -
'; - } - if (getConfig('SecretId')==''||getConfig('SecretKey')=='') $html .= ' - '.getconstStr('Create').' SecretId & SecretKey
-
-
'; - $html .= ' - (腾讯几个月了还不做出来,只能先弄选择了)
- -
- '; - $title = getconstStr('SelectLanguage'); - return message($html, $title, 201); - } - $html .= ''.getconstStr('ClickInstall').', '.getconstStr('LogintoBind'); - $title = 'Error'; - return message($html, $title, 201); -} - -function post2url($url, $data) -{ - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $data); - curl_setopt($ch, CURLOPT_TIMEOUT, 5); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - $response = curl_exec($ch); - curl_close($ch); - //echo $response; - return $response; -} - -function ReorganizeDate($arr) -{ - $str = ''; - ksort($arr); - foreach ($arr as $k1 => $v1) { - $str .= '&' . $k1 . '=' . $v1; - } - $str = substr($str, 1); // remove first '&'. 去掉第一个& - return $str; -} - -function getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey) -{ - //$meth = 'GET'; - $meth = 'POST'; - $host = 'scf.tencentcloudapi.com'; - $tmpdata['Action'] = 'GetFunction'; - $tmpdata['FunctionName'] = $function_name; - $tmpdata['Namespace'] = $Namespace; - $tmpdata['Nonce'] = time(); - $tmpdata['Region'] = $Region; - $tmpdata['SecretId'] = $SecretId; - $tmpdata['Timestamp'] = time(); - $tmpdata['Token'] = ''; - $tmpdata['Version'] = '2018-04-16'; - $data = ReorganizeDate($tmpdata); - $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); - //echo urlencode($signStr); - //return file_get_contents('https://'.$url.'&Signature='.urlencode($signStr)); - return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); -} - -function updateEnvironment($Envs, $function_name, $Region, $Namespace, $SecretId, $SecretKey) -{ - //print_r($Envs); - WaitSCFStat(); - //json_decode($a,true)['Response']['Environment']['Variables'][0]['Key'] - $tmp = json_decode(getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey),true)['Response']['Environment']['Variables']; - foreach ($tmp as $tmp1) { - $tmp_env[$tmp1['Key']] = $tmp1['Value']; - } - foreach ($Envs as $key1 => $value1) { - $tmp_env[$key1] = $value1; - } - $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 - $tmp_env['Region'] = $Region; - ksort($tmp_env); - - $i = 0; - foreach ($tmp_env as $key1 => $value1) { - $tmpdata['Environment.Variables.'.$i.'.Key'] = $key1; - $tmpdata['Environment.Variables.'.$i.'.Value'] = $value1; - $i++; - } - $meth = 'POST'; - $host = 'scf.tencentcloudapi.com'; - $tmpdata['Action'] = 'UpdateFunctionConfiguration'; - $tmpdata['FunctionName'] = $function_name; - $tmpdata['Namespace'] = $Namespace; - $tmpdata['Nonce'] = time(); - $tmpdata['Region'] = $Region; - $tmpdata['SecretId'] = $SecretId; - $tmpdata['Timestamp'] = time(); - $tmpdata['Token'] = ''; - $tmpdata['Version'] = '2018-04-16'; - $data = ReorganizeDate($tmpdata); - $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); - //echo urlencode($signStr); - return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); -} - -function SetbaseConfig($Envs, $function_name, $Region, $Namespace, $SecretId, $SecretKey) -{ - echo json_encode($Envs,JSON_PRETTY_PRINT); - /*$trynum = 0; - while( json_decode(getfunctioninfo($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], $SecretId, $SecretKey),true)['Response']['Status']!='Active' ) echo ' -'.++$trynum;*/ - //json_decode($a,true)['Response']['Environment']['Variables'][0]['Key'] - $tmp = json_decode(getfunctioninfo($function_name, $Region, $Namespace, $SecretId, $SecretKey),true)['Response']['Environment']['Variables']; - foreach ($tmp as $tmp1) { - $tmp_env[$tmp1['Key']] = $tmp1['Value']; - } - foreach ($Envs as $key1 => $value1) { - $tmp_env[$key1] = $value1; - } - $tmp_env = array_filter($tmp_env, 'array_value_isnot_null'); // remove null. 清除空值 - $tmp_env['Region'] = $Region; - ksort($tmp_env); - - $i = 0; - foreach ($tmp_env as $key1 => $value1) { - $tmpdata['Environment.Variables.'.$i.'.Key'] = $key1; - $tmpdata['Environment.Variables.'.$i.'.Value'] = $value1; - $i++; - } - $meth = 'POST'; - $host = 'scf.tencentcloudapi.com'; - $tmpdata['Action'] = 'UpdateFunctionConfiguration'; - $tmpdata['FunctionName'] = $function_name; - $tmpdata['Namespace'] = $Namespace; - $tmpdata['Nonce'] = time(); - $tmpdata['Region'] = $Region; - $tmpdata['SecretId'] = $SecretId; - $tmpdata['Timestamp'] = time(); - $tmpdata['Token'] = ''; - $tmpdata['Version'] = '2018-04-16'; - $tmpdata['Description'] = 'Onedrive index and manager in SCF.'; - $tmpdata['MemorySize'] = 64; - $tmpdata['Timeout'] = 30; - $data = ReorganizeDate($tmpdata); - echo $data; - $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); - //echo urlencode($signStr); - return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); -} - -function updateProgram($function_name, $Region, $Namespace, $SecretId, $SecretKey, $source) -{ - WaitSCFStat(); - $meth = 'POST'; - $host = 'scf.tencentcloudapi.com'; - $tmpdata['Action'] = 'UpdateFunctionCode'; - $tmpdata['Code.GitUrl'] = $source['url']; - $tmpdata['Code.GitBranch'] = $source['branch']; - $tmpdata['CodeSource'] = 'Git'; - $tmpdata['FunctionName'] = $function_name; - $tmpdata['Handler'] = 'index.main_handler'; - $tmpdata['Namespace'] = $Namespace; - $tmpdata['Nonce'] = time(); - $tmpdata['Region'] = $Region; - $tmpdata['SecretId'] = $SecretId; - $tmpdata['Timestamp'] = time(); - $tmpdata['Token'] = ''; - $tmpdata['Version'] = '2018-04-16'; - $data = ReorganizeDate($tmpdata); - $signStr = base64_encode(hash_hmac('sha1', $meth.$host.'/?'.$data, $SecretKey, true)); - //echo urlencode($signStr); - return post2url('https://'.$host, $data.'&Signature='.urlencode($signStr)); -} - -function api_error($response) -{ - return isset($response['Error']); -} - -function api_error_msg($response) -{ - return $response['Error']['Code'] . '
-' . $response['Error']['Message'] . '

-function_name:' . $_SERVER['function_name'] . '
-Region:' . $_SERVER['Region'] . '
-namespace:' . $_SERVER['namespace'] . '
-'; -} - -function OnekeyUpate($auth = 'qkqpttgf', $project = 'OneManager-php', $branch = 'master') -{ - $source['url'] = 'https://github.com/' . $auth . '/' . $project; - $source['branch'] = $branch; - return json_decode(updateProgram($_SERVER['function_name'], $_SERVER['Region'], $_SERVER['namespace'], getConfig('SecretId'), getConfig('SecretKey'), $source), true)['Response']; -} - -function setConfigResponse($response) -{ - return json_decode( $response, true )['Response']; -} diff --git a/readme.md b/readme.md index fe1ab60..4bd5dca 100644 --- a/readme.md +++ b/readme.md @@ -1,53 +1,229 @@ -Install program first, then add onedrive in setup after login. -先安装程序,登录后在设置中添加onedrive。 +[中文readme](readme_cn.md) -# Deploy to heroku -Official: https://heroku.com +# NOTICE: -How to Install: Click the button [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) to Deploy a new app, or create an app then deploy via connect to your github fork. + The Releases is used as archive, not newest code. -DEMO: https://herooneindex.herokuapp.com/ + Please read the descriptions of settings before raising an issue. -# Deploy to VPS(Virtual Private Server) 部署到VPS或空间 -How to Install: - 1.Start web service on your server (httpd or other), make sure you can visit it. - 启动web服务器,确保你能访问到。 - 2.Make the rewrite works, the rule is in .htaccess file, make sure any query redirect to index.php. - 开启伪静态(重写)功能,规则在.htaccess文件中,ngnix从里面复制,我们的目的是不管访问什么都让index.php来处理。 - 3.Upload code. - 上传好代码。 - 4.Change the file config.php can be read&write (666 is suggested). - 让代码中的config.php文件程序可读写,推荐chmod 666 config.php。 - 5.View the website in chrome or other. - 在浏览器中访问。 +--- -# Deploy to SCF -Official: https://cloud.tencent.com/product/scf +# Deploy to Vercel -~~How to Install: https://service-pgxgvop2-1258064400.ap-hongkong.apigateway.myqcloud.com/test/abcdef/%E6%97%A0%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%87%BD%E6%95%B0SCF%E6%90%AD%E5%BB%BAOneDrive.mp4?preview~~ +### Official -先手动在环境变量添加Region,ap-hongkong或ap-guangzhou之类,具体看 https://cloud.tencent.com/document/api/583/17238 最底下,然后再安装。 -添加网盘时,SCF反应不过来,会添加失败,请不要删除,再添加一次相同的就可以了。 + https://vercel.com/ -DEMO: https://service-pgxgvop2-1258064400.ap-hongkong.apigateway.myqcloud.com/test/abcdef/ +### Demo -# Features 特性 -When downloading files, the program produce a direct url, visitor download files from MS OFFICE via the direct url, the server expend a few bandwidth in produce. -下载时,由程序解析出直链,浏览器直接从微软Onedrive服务器下载文件,服务器只消耗与微软通信的少量流量。 -When uploading files, the program produce a direct url, visitor upload files to MS OFFICE via the direct url, the server expend a few bandwidth in produce. -上传时,由程序生成上传url,浏览器直接向微软Onedrive的这个url上传文件,服务器只消耗与微软通信的少量流量。 -The XXX_path in setting is the path in Onedrive, not in url, program will find the path in Onedrive. -设置中的 XXX_path 是Onedrive里面的路径,并不是你url里面的,程序会去你Onedrive里面找这个路径。 -LOGO ICON: put your 'favicon.ico' in the path you showed, make sure xxxxx.com/favicon.ico can be visited. -网站图标:将favicon.ico文件放在你要展示的目录中,确保 xxxxx.com/favicon.ico 可以访问到。 -Program will show content of 'readme.md' & 'head.md'. -可以在文件列表显示head.md跟readme.md文件的内容。 -guest up path, is a folder that the guest can upload files, but can not be list (exclude admin). -游客上传目录(也叫图床目录),是指定一个目录,让游客可以上传文件,不限格式,不限大小。这个目录里面的内容不列清单(除非管理登录)。 -If there is 'index.html' file, program will only show the content of 'index.html', not list the files. -如果目录中有index.html文件,只会输出显示html文件,不显示程序框架。 -Click 'EditTime' or 'Size', the list will sort by time or size, Click 'File' can resume sort. -点击“时间”、“大小”,可以排序显示,点“文件”恢复原样。 + https://onemanager-php.vercel.app/ -QQ Group: 943919989 (请看完上面的中英双语再加群,谢谢!) -Telegram Group: https://t.me/joinchat/I_RVc0bqxuxlT-d0cO7ozw +### Notice + +> 1. you must wait 30-50s to make sure deploy READY after change config; +> +> 2. Vercel limit 100 deploy every day. + +### How to Install + +> https://scfonedrive.github.io/Vercel/Deploy.html . + +--- + +# Deploy to Replit + +### Official + + https://repl.it/ + https://replit.com/ + +### Demo + + https://onemanager.qkqpttgf.repl.co/ + +### Notice + +> `Import from Github` useing the `.replit` file in code files will cause an empty web page, may someone help me? + +### How to Install + +> 1. Click the "+" or "Create Repl", find template "PHP Web Server" (via input "php"), input a name for your project in "Title" or left it default, Click the "+ Create Repl". +> 2. After done, input `git clone https://github.com/qkqpttgf/OneManager-php && mv -b OneManager-php/* ./ && mv -b OneManager-php/.[^.]* ./ && rm -rf *~ && rm -rf OneManager-php` to Console or Shell on the right, press "Enter" to run it. +> 3. Click the green button "Run", it will show the web page on the right, you can open it in a new tab or window. + +--- + +# Deploy to Heroku + +### Official + + https://heroku.com + +### Demo + + https://herooneindex.herokuapp.com/ + +### How to Install + +> ~~Click the button [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) to Deploy a new app~~(`"We couldn't deploy your app because the source code violates the Salesforce Acceptable Use and External-Facing Services Policy."`) +> +> Star this project, then Fork, create an app in Heroku, then turn to the Deploy tab, "Deployment method" via "Connect GitHub", select your github fork. + +--- + +# Deploy to Glitch + +### Official + + https://glitch.com/ + +### Demo + + https://onemanager.glitch.me/ + +### How to Install + + [New Project] -> [Import form Github] -> paste "https://github.com/qkqpttgf/OneManager-php" , after done, [Show] -> [In a New Window]. + +--- + +# Deploy to Tencent Serverless Cloud Function (SCF) + +### Official + + https://cloud.tencent.com/product/scf + +### DEMO + + null + +### How to Install + + see CN readme. + +---- + + +# Deploy to Huawei cloud Function Graph (FG) + +### Official + + https://console.huaweicloud.com/functiongraph/ + +### DEMO + + null + +### How to Install + + see CN readme. + +---- + +# Deploy to Aliyun Function Compute (FC) + +### Official: + + https://fc.console.aliyun.com/ + +### DEMO + + null + +### How to Install + + see CN readme. + +--- + +# Deploy to Baidu Cloud Function Compute (CFC) + +### Official + + https://console.bce.baidu.com/cfc/#/cfc/functions + +### DEMO + + null + +### How to Install + + see CN readme. + +--- + +# Deploy to Virtual Private Server (VPS) or php host + +### DEMO + + null + +### How to Install + +1. Start web service on your server (httpd or other), make sure you can visit it. + +2. Make the rewrite works, the rule is in .htaccess file, make sure any query redirect to index.php. + +3. Upload code. + +4. Change the file .data/config.php can be read&write (666 is suggested). + +5. View the website in chrome or other. + +---- + +# Features + + When downloading files, the program produce a direct url, visitor download files from MS OFFICE via the direct url, the server expend a few bandwidth in produce. + + When uploading files, the program produce a direct url, visitor upload files to MS OFFICE via the direct url, the server expend a few bandwidth in produce. + + The XXX_path in setting is the path in Onedrive, not in url, program will find the path in Onedrive. + + LOGO ICON: put your 'favicon.ico' in the path you showed, make sure xxxxx.com/favicon.ico can be visited. + + Program will show content of 'readme.md' & 'head.md'. + + guest upload path, is a folder that the guest can upload files, but can not be list (exclude admin). + + If there is 'index.html' file, program will only show the content of 'index.html', not list the files. + + Click 'EditTime' or 'Size', the list will sort by time or size, Click 'File' can resume sort. + +---- + +# Functional files + +### favicon.ico + + put it in the showing home folder of FIRST disk (maybe not root of onedrive). + +### index.html + + show content of index.html as html. + +### head.md + +### readme.md + + it will showed at top or bottom as markdown. + +### head.omf + +### foot.omf + + it will showed at top or bottom as html (javascript works!). + +---- + +# A cup of coffee + + https://paypal.me/qkqpttgf + +----- + +# Chat + +### Telegram Group + + https://t.me/joinchat/I_RVc0bqxuxlT-d0cO7ozw diff --git a/readme_cn.md b/readme_cn.md new file mode 100644 index 0000000..bf8ab5e --- /dev/null +++ b/readme_cn.md @@ -0,0 +1,271 @@ +[Readme EN](readme.md) + +# 注意: + + 请关掉浏览器的翻译。 + + Releases只是当存档在用的,并不是最新代码。 + + 请将设置中所有的设置项的说明都读一遍,有些问题就不用问了。 + +--- + +# 部署到 Vercel + +### 官网 + + https://vercel.com/ + +### Demo + + https://onemanager-php.vercel.app/ + +### 注意 + +> 1. 每次更改配置后都要等 30-50s 来确保部署成功; +> +> 2. Vercel 每天限制 100 次部署。 + +### 安装(英文) + + https://scfonedrive.github.io/Vercel/Deploy.html + +--- + +# 部署到 Replit + +### 官网 + + https://repl.it/ + https://replit.com/ + +### Demo + + https://onemanager.qkqpttgf.repl.co/ + +### 注意 + +> 直接`Import from Github`通过`.replit`文件指定php时,网页会空白,有人帮忙解决吗? + +### 安装 + +> 1. 点右上的 "+" 或左上的 "+ Create Repl",template中输入php,点选"PHP Web Server",在"Title"里输入你想要的名称或者让它默认, 点下面的"+ Create Repl"。 +> 2. 结束后,在右边的Console或Shell里输入 `git clone https://github.com/qkqpttgf/OneManager-php && mv -b OneManager-php/* ./ && mv -b OneManager-php/.[^.]* ./ && rm -rf *~ && rm -rf OneManager-php` 敲回车运行。 +> 3. 点上方的绿色 "Run" 按钮,右边会显示一个网页,你要在新窗口打开它来安装,不然不能登录。 + +--- + +# 部署到 Heroku + +### 官网 + + https://heroku.com + +### Demo + + https://herooneindex.herokuapp.com/ + +### 安装 + +> 给这个项目点star,然后fork,在Heroku创建一个app,然后点进Deploy页,在"Deployment method"处点"Connect GitHub",选择你的fork。 + +--- + +# 部署到 Glitch + +### 官网 + + https://glitch.com/ + +### Demo + + https://onemanager.glitch.me/ + +### 安装 + + 点 [New Project] -> 点 [Import form Github] -> 粘贴 "https://github.com/qkqpttgf/OneManager-php" ,结束后,左上角点 [Show] -> [In a New Window]。 + +--- + +# 部署到腾讯无服务器云函数 Serverless Cloud Function (SCF) + +### 官网 + + https://cloud.tencent.com/product/scf + +### DEMO + + 暂无 + +### 注意事项 + + SCF新增限制,环境变量整体最大4KB,所以最多添加4个盘(可以在安装时选择将配置保存在文件来避开限制)。 + +### 安装 + +1. 进入函数服务,上方选择地区,然后点击新建。 + +2. 输入函数名称,选择模板函数,在模糊搜索中输入onedrive,大小写随意,选择那个【获取onedrive信息.....】,点下一步,在代码界面不用动,直接点完成。 + +3. 点击触发管理,创建触发器,触发方式改成API网关触发,底下勾选启用集成响应,提交。 + +4. 在触发管理中可以看到一个 访问路径,访问它,开始安装。 + + (重点:**勾选集成响应**) + +> **添加网盘时,SCF可能会反应不过来,不跳转到微软,导致添加失败,请不要删除这个盘,再添加一次相同标签的盘就可以了。** + +---- + + +# 部署到华为云函数工作流 Function Graph (FG) + +### 官网 + + https://console.huaweicloud.com/functiongraph/ + +### DEMO + + 暂无 + +### 注意事项 + + FG中,环境变量整体大小为2KB,所以最多添加2个盘(一个onedrive一个aliyundrive)(可以在安装时选择将配置保存在文件来避开限制)。 + +### 安装 + +1. 在函数列表,点右边创建函数 +2. 输入名称,选择运行时语言为PHP7.3,点上传ZIP文件,选择文件,然后点右边的创建函数(这里的ZIP文件不能直接用从Github上下载的ZIP文件,要将它解压后,去掉外层文件夹后,再压缩为ZIP。) +3. 创建触发器:选API网关,安全认证选None,后端超时(毫秒)将5000改成30000,上面创建分组一下,其它的点点点 +4. 访问触发器给的url,开始安装 +5. 在【触发器界面】点【触发器名称】,跳到API网关管理,右边【更多URL】,可以添加自定义域名,自定义域名后发现还是要 xxxx.com/函数名 来访问,点上方的【编辑】,第1页不用改,点【下一步】,**请求Path改成/**,注意匹配模式是前缀匹配,Method为ANY,然后不用点下一步了,点【立即完成】,然后去【发布】生效 + +---- + +# 部署到阿里云函数计算 Function Compute (FC) + +### 官网 + + https://fc.console.aliyun.com/ + +### DEMO + + 无 + +### 安装 + +1. 新建函数 -- HTTP函数 +2. 运行环境选择php7.2 +3. 触发器认证方式选择anonymous,请求方式里面,点一下GET,再点一下POST,最终框框里面有这2个 +4. 上传代码(这里的ZIP文件不能直接用从Github上下载的ZIP文件,要将它解压后,去掉外层文件夹后,再压缩为ZIP。) +5. 触发器中点进去,找到配置自定义域名,点击前往,创建,路径中填 /* ,其它下拉选择。 +6. 访问你的域名,开始安装 + +--- + +# 部署到百度云函数计算 Cloud Function Compute (CFC) + +### 官网 + + https://console.bce.baidu.com/cfc/#/cfc/functions + +### DEMO + + 暂无 + +### 注意事项 + + **自定义域名需要另外使用API网关,并备案。** + +### 安装 + +1. 在函数列表,点创建函数 +2. 创建方式改为空白函数,点下一步 +3. 输入名称,选择运行时为PHP7.2,点下一步 +4. 触发器:下拉选择HTTP触发器,URL路径填 /{filepath+} ,HTTP方法全选,身份验证:不验证,点提交 +5. 进入代码编辑页,编辑类型改上传函数ZIP包,选择文件(这里的ZIP文件不能直接用从Github上下载的ZIP文件,要将它解压后,去掉外层文件夹后,再压缩为ZIP。),开始上传 +6. 点击右边触发器,复制并访问提供的url,开始安装 + +--- + +# 部署到VPS (Virtual Private Server) 或 空间 + +### DEMO + +暂无 + +### 安装 + +1. 启动web服务器,确保你能访问到。 + +2. 开启伪静态(重写)功能,规则在.htaccess文件中,ngnix从里面复制,我们的目的是不管访问什么都让index.php来处理。 + +3. 上传好代码。 + +4. 使web身份可读写代码中的.data/config.php文件,推荐chmod 666 .data/config.php。 + +5. 在浏览器中访问。 + +---- + +# 特性 + + 下载时,由程序解析出直链,浏览器直接从微软Onedrive服务器下载文件,服务器只消耗与微软通信的少量流量。 + + 上传时,由程序生成上传url,浏览器直接向微软Onedrive的这个url上传文件,服务器只消耗与微软通信的少量流量。 + + 设置中的 XXX_path 是Onedrive里面的路径,并不是你url里面的,程序会去你Onedrive里面找这个路径。 + + 网站图标:将favicon.ico文件放在你要展示的目录中,确保 xxxxx.com/favicon.ico 可以访问到。 + + 可以在文件列表显示head.md跟readme.md文件的内容。 + + 游客上传目录(也叫图床目录),是指定一个目录,让游客可以上传文件,不限格式,不限大小。这个目录里面的内容不列清单(除非管理登录)。 + + 如果目录中有index.html文件,只会输出显示html文件,不显示程序框架。 + + 点击“时间”、“大小”,可以排序显示,点“文件”恢复原样。 + +---- + +# 功能性文件 + +### favicon.ico + + 放在第一个盘的显示目录(不一定是onedrive根目录)。 + +### index.html + + 将index.html以静态网页显示出来。 + +### head.md + +### readme.md + + 以MD语法显示在顶部或底部。 + +### head.omf + +### foot.omf + + 以html显示在顶部或底部(可以跑js)。 + +---- + +# 捐赠 + + https://paypal.me/qkqpttgf + +----- + +# 群聊 + + **请看完上面的中英双语再加群,谢谢!** + +### QQ 群: + + 212088653 + +### Telegram Group + + https://t.me/joinchat/I_RVc0bqxuxlT-d0cO7ozw diff --git a/theme/Onedrive-dev.html b/theme/Onedrive-dev.html new file mode 100644 index 0000000..3a2a8cc --- /dev/null +++ b/theme/Onedrive-dev.html @@ -0,0 +1,577 @@ + + + + + + <!--Title--> + + + + + +
+ + +
+
+
+ +
+
+
+ +
+
+ +
+
+
+

+ + + > + + +

+
+ +
+
+
+
+
+ +   +
+
+
+ + <!--FileName--> + + +
+ +
+
+
+
+ + +
+
+
+ +
+ +
+ +
+ +
+
+
+
+
+
+ +
+ +
+ +
+ +
+ folder icon +
+
+ +
+
+
+
+ + +
+ +
+ +
+ +
+ +
+
+ +
+
+
+
+ +
+ +
+
+ +
+
+ +
+ + + + + + + + diff --git a/theme/apache.html b/theme/apache.html new file mode 100644 index 0000000..2971a82 --- /dev/null +++ b/theme/apache.html @@ -0,0 +1,27 @@ + + + + <!--Sitename--> /<!--PathArrayStart--><!--PathArrayName-->/<!--PathArrayEnd--> + + +

//

+ + + + + + + + + + + + + + + + + +
NameLast modifiedSizeDescription

Parent Directory   -  
/ -  
 

+ + diff --git a/theme/classic.html b/theme/classic.html new file mode 100644 index 0000000..a4b19bb --- /dev/null +++ b/theme/classic.html @@ -0,0 +1,1769 @@ + +{ + "music":"musical-notes", + "video":"logo-youtube", + "img":"image", + "office":"newspaper", + "txt":"clipboard", + "zip":"file-tray-full", + "iso":"disc", + "apk":"logo-android", + "exe":"logo-windows", + "default":"document" +} + + + + + <!--Title--> + + + + + + + + + + + + +
+ + + + +
    • + +
    • +
    • +
    • + +
    • +
    • +
  • + +   + + + + --> +
    + +
    + +

    + +

    + +
    +
    +
    +
    + + > + +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + +
    +
    +
    +
    + +
    +
    +
    +
    + + +
    +
    +
    +

    /

    +
    +
    + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + +
    +
    + + + +
    +
    + +   +
    +
    + + <!--FileName--> + + +
    + + + + + +
    Loading PDF
    + + + + + +
    + +
    + + +     + + + + +
    + + +
    + + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +
    + + +     + + + +   + +
    + +
  • +
      +
    • +
    • +
    • +
    • +
    • +
    +
  • + + + +
    + +
  • +
      +
    • +
    • +
    • +
    • +
    +
  • + + + + +
    + +
    + + + + + + + +
    + + + + + + + + + + + + + + +
    +
    + + +
    +
    + + + +
    +
    + + +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + + + + +
    + + + + + + +
    + + + + + +
    + + + + + + + + + + + + + + + diff --git a/theme/flatcard.html b/theme/flatcard.html new file mode 100644 index 0000000..87faa9a --- /dev/null +++ b/theme/flatcard.html @@ -0,0 +1,1703 @@ + +{ + "music":"musical-notes", + "video":"logo-youtube", + "img":"image", + "office":"newspaper", + "txt":"clipboard", + "zip":"file-tray-full", + "iso":"disc", + "apk":"logo-android", + "exe":"logo-windows", + "default":"document" +} + + + + + <!--Title--> + + + + + + + + + + + + + + + + +
    • + +
    • +
    • +
    • + +
    • +
    • +
  • + + + +
    + +

    + +

    + +
    +
    +
    +
    + + > + +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + +
    +
    +
    +
    + +
    +
    +
    +
    + + +
    +
    +
    +

    /

    +
    +
    + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + +
    +
    + + + +
    +
    + + +
    +
    + + <!--FileName--> + + +
    + + + + + +
    Loading PDF
    + + + + + +
    + +
    + +     + + + + +
    + +
    + + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +
    + + +    + + + + +
    + +
  • +
      +
    • +
    • +
    • +
    • +
    • +
    +
  • + + + +
    + +
  • +
      +
    • +
    • +
    • +
    • +
    +
  • + + + + +
    + +
    + + + + + + + +
    + + + + + + + + + + + + + + +
    +
    + + +
    +
    + + + +
    +
    + + +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + + + + +
    + + + + + + +
    + + + + + +
    + + + + + + + + + + + + + + + diff --git a/theme/iis.html b/theme/iis.html new file mode 100644 index 0000000..0988c3e --- /dev/null +++ b/theme/iis.html @@ -0,0 +1,24 @@ + + + <!--Sitename--> - /<!--PathArrayStart--><!--PathArrayName-->/<!--PathArrayEnd--> + + +

    - //


    + + + + + + + + + + + + + + +
    [To Parent Directory]
    <dir>
    +
    + + diff --git a/theme/ly_white.php b/theme/ly_white.php deleted file mode 100644 index 1db80bd..0000000 --- a/theme/ly_white.php +++ /dev/null @@ -1,1289 +0,0 @@ - - - - - <?php echo $pretitle; if ($_SERVER['base_disk_path']!=$_SERVER['base_path']) { if (getConfig('diskname')!='') $diskname = getConfig('diskname'); else $diskname = $_SERVER['disktag']; echo ' - ' . $diskname; } ?> - <?php echo $_SERVER['sitename'];?> - - - - - - -   -
    - -
    - - - - -
    - - - -
    • - -
    • -
    • -
    • - -
    • -
    • -
  • - -   - -
    - -
    - -

    - -

    -1) { ?> -
    -
    -
    -
    -'.$diskname.' -'; - } ?> -
    -
    -
    -
    - -
    -
    -
    -
    - -
    -
    -
    -
    - -
    -
    -
    - - - - - -

    -
    -
    - -
    -
    - - -
    -
    -' . $files['error']['message'] . '
    '; - $statusCode=404; - } else { - if (isset($files['file'])) { -?> -
    -
    - -   -
    -
    -document.getElementById(\'url\').offsetWidth) this.style.width=\'100%\';" /> -'; - } elseif (in_array($ext, $exts['video'])) { - //echo ''; - $DPvideo=$files['@microsoft.graph.downloadUrl']; - echo '
    -'; - } elseif (in_array($ext, $exts['music'])) { - echo ' -'; - } elseif (in_array($ext, ['pdf'])) { - /*echo ' - -';*/ - $pdfurl = $files['@microsoft.graph.downloadUrl']; - echo '
    -'; - } elseif (in_array($ext, $exts['office'])) { - echo ' -'; - } elseif (in_array($ext, $exts['txt'])) { - $txtstr = htmlspecialchars(curl_request($files['@microsoft.graph.downloadUrl'])['body']); -?> -
    - -
    - -     - - - -'; ?> -
    - - -
    -'; - }*/ else { - echo ''.getconstStr('FileNotSupport').''; - } ?> -
    -
    - - - - - - - - - - - - - - -'; - foreach ($files['children'] as $file) { - // Files - if (isset($file['file'])) { - if ($_SERVER['admin'] or !isHideFile($file['name'])) { - $filenum++; ?> - - - - - - -
        
    - -
  • -
      -
    • -
    • -
    • -
    • -
    • -
    -
  • - - - -
    - -
  • -
      -
    • -
    • -
    • -
    • -
    -
  • - - - - - - - - - - - - - - - - - - - - - - - -
    -200) { - $pagenum = $files['folder']['page']; - $maxpage = ceil($files['folder']['childCount']/200); - $prepagenext = ' - - - - - - - - -
    '; - if ($pagenum!=1) { - $prepagenum = $pagenum-1; - $prepagenext .= ' - '.getconstStr('PrePage').''; - } - $prepagenext .= ' - '; - for ($page=1;$page<=$maxpage;$page++) { - if ($page == $pagenum) { - $prepagenext .= ' - ' . $page . ' '; - } else { - $prepagenext .= ' - ' . $page . ' '; - } - } - $prepagenext = substr($prepagenext,0,-1); - $prepagenext .= ' - '; - if ($pagenum!=$maxpage) { - $nextpagenum = $pagenum+1; - $prepagenext .= ' - '.getconstStr('NextPage').''; - } - $prepagenext .= ' -
    - '; - echo $prepagenext; - } - if ($_SERVER['admin']) { ?> -
    -
    - - -
    -
    - -
    -
    -
    -
    -
    -
    -
    - -
    -
    -'; - } - } - } else { - echo ' -
    -
    -
    - - -
    -
    -
    '; - $statusCode = 401; - } - } ?> -
    -
    -
    - - - -
    - - - - - - -
    - - - -
    - - - - -"日)", - "1"=>"一)", - "2"=>"二)", - "3"=>"三)", - "4"=>"四)", - "5"=>"五)", - "6"=>"六)" -); -echo '(星期'.$week[$w]; -?> - -
    -
    - - -
    -  - - - - - - - - - - diff --git a/theme/lybwb.php b/theme/lybwb.php deleted file mode 100644 index a6d611d..0000000 --- a/theme/lybwb.php +++ /dev/null @@ -1,1283 +0,0 @@ - - - - - <?php echo $pretitle;?> - <?php echo $_SERVER['sitename'];?> - - - - - - - - - - -
    - - - -
    • - -
    • -
    • -
    • - -
    • -
    • -
  • - -   - -
    - -
    - -

    - -

    -1) { ?> -
    -
    -
    -
    -'.$diskname.' -'; - } ?> -
    -
    -
    -
    - -
    -
    -
    - - - - - -

    -
    -
    - -
    -
    - - -
    -
    -' . $files['error']['message'] . '
    '; - $statusCode=404; - } else { - if (isset($files['file'])) { -?> -
    -
    - -   -
    -
    -document.getElementById(\'url\').offsetWidth) this.style.width=\'100%\';" /> -'; - } elseif (in_array($ext, $exts['video'])) { - //echo ''; - $DPvideo=$files['@microsoft.graph.downloadUrl']; - echo '
    -'; - } elseif (in_array($ext, $exts['music'])) { - echo ' -'; - } elseif (in_array($ext, ['pdf'])) { - /*echo ' - -';*/ - $pdfurl = $files['@microsoft.graph.downloadUrl']; - echo '
    -'; - } elseif (in_array($ext, $exts['office'])) { - echo ' -'; - } elseif (in_array($ext, $exts['txt'])) { - $txtstr = htmlspecialchars(curl_request($files['@microsoft.graph.downloadUrl'])['body']); -?> -
    - -
    - -     - - - -'; ?> -
    - - -
    -'; - }*/ else { - echo ''.getconstStr('FileNotSupport').''; - } ?> -
    -
    - - - - - - - - - - - - - - -'; - foreach ($files['children'] as $file) { - // Files - if (isset($file['file'])) { - if ($_SERVER['admin'] or (substr($file['name'],0,1) !== '.' and $file['name'] !== getConfig('passfile') ) ) { - if (strtolower($file['name']) === 'head.md') $head = $file; - if (strtolower($file['name']) === 'readme.md') $readme = $file; - if (strtolower($file['name']) === 'index.html' && !$_SERVER['admin']) { - $html = curl_request(fetch_files(spurlencode(path_format($path . '/' .$file['name']),'/'))['@microsoft.graph.downloadUrl'])['body']; - return output($html,200); - } - $filenum++; ?> - - - - - - -
       
    - -
  • -
      -
    • -
    • -
    • -
    • -
    • -
    -
  • - - - -
    - -
  • -
      -
    • -
    • -
    • -
    • -
    -
  • - - - - - - - - - - - - - - - - - - - - - - - -
    -200) { - $pagenum = $files['folder']['page']; - $maxpage = ceil($files['folder']['childCount']/200); - $prepagenext = ' - - - - - - - - -
    '; - if ($pagenum!=1) { - $prepagenum = $pagenum-1; - $prepagenext .= ' - '.getconstStr('PrePage').''; - } - $prepagenext .= ' - '; - for ($page=1;$page<=$maxpage;$page++) { - if ($page == $pagenum) { - $prepagenext .= ' - ' . $page . ' '; - } else { - $prepagenext .= ' - ' . $page . ' '; - } - } - $prepagenext = substr($prepagenext,0,-1); - $prepagenext .= ' - '; - if ($pagenum!=$maxpage) { - $nextpagenum = $pagenum+1; - $prepagenext .= ' - '.getconstStr('NextPage').''; - } - $prepagenext .= ' -
    - '; - echo $prepagenext; - } - if ($_SERVER['admin']) { ?> -
    -
    - - -
    -
    - -
    - -
    -
    -
    -
    - - -
    -'; - } - if ($readme) { - echo ' -
    -
    -
    -
    -
    -
    -
    - -
    - -
    -
    -'; - } - } - } else { - echo ' -
    -
    -
    - - -
    -
    -
    '; - $statusCode = 401; - } - } ?> -
    -
    -
    - - - -
    - - - - - - -
    - - - -
    - - - - -
    - - - - - - - - - - diff --git a/theme/nchyn_grey.html b/theme/nchyn_grey.html new file mode 100644 index 0000000..8dbed3b --- /dev/null +++ b/theme/nchyn_grey.html @@ -0,0 +1,1758 @@ + +{ + "music":"musical-notes", + "video":"logo-youtube", + "img":"image", + "office":"newspaper", + "txt":"clipboard", + "zip":"file-tray-full", + "iso":"disc", + "apk":"logo-android", + "exe":"logo-windows", + "default":"document" +} + + + + + <!--Title--> + + + + + + + + + + + + + + + +
    +
    +   +
    + +
    + +

    + +

    +
    +
    +
    +
    +
    + + + > + + + + + + + + + + +
    +
    +
    +
    + + + + +
    +
    +
    +
    + +
    +
    +
    +
    + + + + +
    +
    +
    + +
    +
    +
    + + + +
    +
    +
    + +
    + +
    + +
    +
    +
    + + +
    +
    +
    + + + +
    +
    + +
    +
    + + +
    +
    + +
    +
    +
    + + + + + +
    +
    + +   +
    +
    + + <!--FileName--> + + +
    + + + + + +
    + + + + + +
    + +
    + +     + + + + +
    + +
    + + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + +     + + +   + +
    + + + + + + +
    + + + + + + +
    + +
    + + + + + + + +
    + + + + + + + + + + + + + + +
    +
    + + + + + + + +
    +
    + +
    +
    + + +
    +
    + +
    +
    +
    + + + + + +
    +
    +
    + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + + + + +
    +
    +
    + +
    + + + + + + + + +
    +
    +
    + + + + +
    + +
    + +
    +
    +
    + +
    + +
    +
    + +
    + +
    + + + +
    + +
    + + +
    + + + + + +

    OneManager By 逸笙 Theme By Nchyn

    +

    + + + + + + + + + + + + + + + + + diff --git a/theme/nexmoe1.html b/theme/nexmoe1.html new file mode 100644 index 0000000..56998de --- /dev/null +++ b/theme/nexmoe1.html @@ -0,0 +1,377 @@ + +{ + "music":"audiotrack", + "video":"ondemand_video", + "img":"image", + "default":"insert_drive_file" +} + + + + + + + <!--Title--> + + + + + + + + +
    +
    +
    + + + chevron_right +
    + +
    + +
  • >
  • + +
    +
    + + + chevron_right + + +
    +
    + + +
    + +
    + +
    +
    + https + + +
    +
    + +
    +
    + + + +
    +
    + +
    +--> + + +
    + +
    + + +
    + +
    + + + +
    + +
    + + +
    +
    +
    + + +
    + +
    + + +
    + +
    + + + + +
    +
    +
    + + + +
    + + file_download + + + +
    + +
    + +
    +
    + +
    + +
    + + +
    + +
    + +
    + + format_list_bulleted + + + + + + + + diff --git a/theme/nexmoe2.html b/theme/nexmoe2.html new file mode 100644 index 0000000..3ed1f54 --- /dev/null +++ b/theme/nexmoe2.html @@ -0,0 +1,580 @@ + +{ + "music":"audiotrack", + "video":"ondemand_video", + "img":"image", + "default":"insert_drive_file" +} + + + + + + + <!--Title--> + + + + + + + + + + + + +
    +
    + menu + + + chevron_right + + +
    + + format_list_bulleted + +
    +
    + +
    +
    + +
    +
    +
    +
    OneManager
    +
    +
    +
    + +
    + + + + +
    + +
    +
    + https + + +
    +
    + +
    +
    + + + +
    + + + +--> + + + +
    + +
    + +
    + + +
    +
    +
    + + +
    + +
    + + +
    + +
    + + + + +
    +
    +
    + + + +
    + +
    +file_download + + + + +
    +
    +
    + +
    + +
    + + +
    + +
    + + + +
    +
    + +
    +
    + +
    + +
    + + +
    + +
    + +
    +
    + + + + + + + + + diff --git a/theme/nginx.html b/theme/nginx.html new file mode 100644 index 0000000..ee428c4 --- /dev/null +++ b/theme/nginx.html @@ -0,0 +1,24 @@ + + + <!--Sitename--> - /<!--PathArrayStart--><!--PathArrayName-->/<!--PathArrayEnd--> + + +

    - //


    + + + + + + + + + + + + + + +
    ../
    /-
    +
    + + diff --git a/theme/onemoe.html b/theme/onemoe.html new file mode 100644 index 0000000..656d64d --- /dev/null +++ b/theme/onemoe.html @@ -0,0 +1,1595 @@ + +{ + "music":"musical-notes", + "video":"logo-youtube", + "img":"image", + "office":"newspaper", + "txt":"clipboard", + "zip":"file-tray-full", + "iso":"disc", + "apk":"logo-android", + "exe":"logo-windows", + "default":"document" +} + + + + + <!--Title--> + + + + + + + + + + + + + + + + + + + +
    + + + + +
    • + +
    • +
    • +
    • + +
    • +
    • +
  • + +   + +
    + +
    + +

    + +

    + +
    +
    +
    +
    + + > + +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + +
    +
    +
    +
    + +
    +
    +
    +
    + + +
    +
    +
    +

    /

    +
    +
    + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + +
    +
    + + + +
    +
    + +   +
    +
    + + <!--FileName--> + + +
    + + + + + +
    Loading PDF
    + + + + + +
    + +
    + +     + + + + +
    + +
    + + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +
    + + +     + + + +   + +
    + +
  • +
      +
    • +
    • +
    • +
    • +
    • +
    +
  • + + + +
    + +
  • +
      +
    • +
    • +
    • +
    • +
    +
  • + + + + +
    + +
    + + + + + + + +
    + + + + + + + + + + + + + + +
    +
    + + +
    +
    + + + +
    +
    + + +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + + + + +
    + + + + + + +
    + + + + + +
    + + + + + + + + + + + + + + diff --git a/theme/onemoe.php b/theme/onemoe.php deleted file mode 100644 index 8567957..0000000 --- a/theme/onemoe.php +++ /dev/null @@ -1,1198 +0,0 @@ - - - - - <?php echo $pretitle; if ($_SERVER['base_disk_path']!=$_SERVER['base_path']) { if (getConfig('diskname')!='') $diskname = getConfig('diskname'); else $diskname = $_SERVER['disktag']; echo ' - ' . $diskname; } ?> - <?php echo $_SERVER['sitename'];?> - - - - - - - - - - - -
    - - - -
    • - -
    • -
    • -
    • - -
    • -
    • -
  • - -   - -
    - -
    - -

    - -

    -1) { ?> -
    -
    -
    -
    -'.$diskname.' -'; - } ?> -
    -
    -
    -
    - -
    -
    -
    -
    - -
    -
    -
    -
    - -
    -
    -
    - - - - - -

    -
    -
    - -
    -
    - - -
    -
    -' . $files['error']['message'] . '
    '; - $statusCode=404; - } else { - if (isset($files['file'])) { -?> -
    -
    - -   -
    -
    -document.getElementById(\'url\').offsetWidth) this.style.width=\'100%\';" /> -'; - } elseif (in_array($ext, $exts['video'])) { - //echo ''; - $DPvideo=$files['@microsoft.graph.downloadUrl']; - echo '
    -'; - } elseif (in_array($ext, $exts['music'])) { - echo ' -'; - } elseif (in_array($ext, ['pdf'])) { - /*echo ' - -';*/ - $pdfurl = $files['@microsoft.graph.downloadUrl']; - echo '
    -'; - } elseif (in_array($ext, $exts['office'])) { - echo ' -'; - } elseif (in_array($ext, $exts['txt'])) { - $txtstr = htmlspecialchars(curl_request($files['@microsoft.graph.downloadUrl'])['body']); -?> -
    - -
    - -     - - - -'; ?> -
    - - -
    -'; - }*/ else { - echo ''.getconstStr('FileNotSupport').''; - } ?> -
    -
    - - - - - - - - - - - - - - -'; - foreach ($files['children'] as $file) { - // Files - if (isset($file['file'])) { - if ($_SERVER['admin'] or !isHideFile($file['name'])) { - $filenum++; ?> - - - - - - -
        
    - -
  • -
      -
    • -
    • -
    • -
    • -
    • -
    -
  • - - - -
    - -
  • -
      -
    • -
    • -
    • -
    • -
    -
  • - - - - - - - - - - - - - - - - - - - - - - - -
    -200) { - $pagenum = $files['folder']['page']; - $maxpage = ceil($files['folder']['childCount']/200); - $prepagenext = ' - - - - - - - - -
    '; - if ($pagenum!=1) { - $prepagenum = $pagenum-1; - $prepagenext .= ' - '.getconstStr('PrePage').''; - } - $prepagenext .= ' - '; - for ($page=1;$page<=$maxpage;$page++) { - if ($page == $pagenum) { - $prepagenext .= ' - ' . $page . ' '; - } else { - $prepagenext .= ' - ' . $page . ' '; - } - } - $prepagenext = substr($prepagenext,0,-1); - $prepagenext .= ' - '; - if ($pagenum!=$maxpage) { - $nextpagenum = $pagenum+1; - $prepagenext .= ' - '.getconstStr('NextPage').''; - } - $prepagenext .= ' -
    - '; - echo $prepagenext; - } - if ($_SERVER['admin']) { ?> -
    -
    - - -
    -
    - -
    - -
    -
    -
    -
    -
    - -
    -
    -'; - } - } - } else { - echo ' -
    -
    -
    - - -
    -
    -
    '; - $statusCode = 401; - } - } ?> -
    -
    -
    - - - -
    - - - - - - -
    - - - -
    - - - - - - - - - - diff --git a/theme/classic.php b/theme/purecool.html similarity index 57% rename from theme/classic.php rename to theme/purecool.html index 88f9b39..72b8049 100644 --- a/theme/classic.php +++ b/theme/purecool.html @@ -1,53 +1,75 @@ - + +{ + "music":"musical-notes", + "video":"logo-youtube", + "img":"image", + "office":"newspaper", + "txt":"clipboard", + "zip":"file-tray-full", + "iso":"disc", + "apk":"logo-android", + "exe":"logo-windows", + "default":"document" +} + - + - <?php echo $pretitle; if ($_SERVER['base_disk_path']!=$_SERVER['base_path']) { if (getConfig('diskname')!='') $diskname = getConfig('diskname'); else $diskname = $_SERVER['disktag']; echo ' - ' . $diskname; } ?> - <?php echo $_SERVER['sitename'];?> + <!--Title--> - - - - + + + + + -
    - - - -
    • - -
    • -
    • -
    • - -
    • -
    • +
      + + + + +
      • + +
      • +
      • +
      • + +
      • +
    • - +  
      - -
      - -

      - + +
      + +

      +

      -1) { ?> -
      + +
      -'.$diskname.' -'; - } ?> + + > +
      - + + +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      + +
      - + +
      - - - - - -

      +

      /

      - -
      -
      - - -
      + +
      +
      +
      + + +
      +
      -' . $files['error']['message'] . '
      '; - $statusCode=404; - } else { - if (isset($files['file'])) { -?> + + +
      +
      + + +
      +
      + + +
      - -   + +  
      -document.getElementById(\'url\').offsetWidth) this.style.width=\'100%\';" /> -'; - } elseif (in_array($ext, $exts['video'])) { - //echo ''; - $DPvideo=$files[$_SERVER['DownurlStrName']]; - echo '
      -'; - } elseif (in_array($ext, $exts['music'])) { - echo ' -'; - } elseif (in_array($ext, ['pdf'])) { - /*echo ' - -';*/ - $pdfurl = $files[$_SERVER['DownurlStrName']]; - echo '
      -'; - } elseif (in_array($ext, $exts['office'])) { - echo ' -'; - } elseif (in_array($ext, $exts['txt'])) { - $txtstr = htmlspecialchars(curl_request($files[$_SERVER['DownurlStrName']])['body']); -?> + + <!--FileName--> + + +
      + + + + + +
      Loading PDF
      + + + + +
      - +
      - -     - - - -'; ?> + +     + + + + +
      +
      - - -
      -'; - }*/ else { - echo ''.getconstStr('FileNotSupport').''; - } ?> + + + +
      - + + - - - + + + - - + + - - + + -'; - foreach ($files['children'] as $file) { - // Files - if (isset($file['file'])) { - if ($_SERVER['admin'] or !isHideFile($file['name'])) { - $filenum++; ?> - + + + - - + + - +
           + + +     + + + +   + +
      - -
    • + +
      • -
      • -
      • -
      • -
      • -
      • +
      • +
      • +
      • +
      • +
    • - + - +
      - -
    • + +
      • -
      • -
      • -
      • -
      • +
      • +
      • +
      • +
    • - - - - - - - - - - - - - - - - - - - - - - - + + + +
      -200) { - $pagenum = $files['folder']['page']; - $maxpage = ceil($files['folder']['childCount']/200); - $prepagenext = ' +
      - + - - -
      '; - if ($pagenum!=1) { - $prepagenum = $pagenum-1; - $prepagenext .= ' - '.getconstStr('PrePage').''; - } - $prepagenext .= ' + + + + '; - for ($page=1;$page<=$maxpage;$page++) { - if ($page == $pagenum) { - $prepagenext .= ' - ' . $page . ' '; - } else { - $prepagenext .= ' - ' . $page . ' '; - } - } - $prepagenext = substr($prepagenext,0,-1); - $prepagenext .= ' + + + + + + + '; - if ($pagenum!=$maxpage) { - $nextpagenum = $pagenum+1; - $prepagenext .= ' - '.getconstStr('NextPage').''; - } - $prepagenext .= ' + + + +
      -
      '; - echo $prepagenext; - } - if ($_SERVER['admin']) { ?> + + +
      -
      +
      + - -
      +
      - + +
      -
      + + +
      - +
      -'; - } - } - } else { - echo ' -
      -
      -
      - - -
      -
      -
      '; - $statusCode = 401; - } - } ?>
      - + + +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      + + - + +
      - + + + - -
      + +
      - - - - - - + + + + + + + - + + diff --git a/theme/purenice.php b/theme/purenice.php deleted file mode 100644 index 1dba99e..0000000 --- a/theme/purenice.php +++ /dev/null @@ -1,1263 +0,0 @@ - - - - - <?php echo $pretitle; if ($_SERVER['base_disk_path']!=$_SERVER['base_path']) { if (getConfig('diskname')!='') $diskname = getConfig('diskname'); else $diskname = $_SERVER['disktag']; echo ' - ' . $diskname; } ?> - <?php echo $_SERVER['sitename'];?> - - - - - - - - - - -
      - - - -
      • - -
      • -
      • -
      • - -
      • -
      • -
    • - -   - -
      - - -
      - -

      - -

      -1) { ?> -
      -
      -
      -
      -'.$diskname.' -'; - } ?> -
      -
      -
      -
      - -
      -
      -
      -
      - -
      -
      -
      -
      - -
      -
      -
      - - - - - -

      -
      -
      - -
      - - -
      -' . $files['error']['message'] . '
      '; - $statusCode=404; - } else { - if (isset($files['file'])) { -?> -
      -
      - -   -
      -
      -document.getElementById(\'url\').offsetWidth) this.style.width=\'100%\';" /> -'; - } elseif (in_array($ext, $exts['video'])) { - //echo ''; - $DPvideo=$files['@microsoft.graph.downloadUrl']; - echo '
      -'; - } elseif (in_array($ext, $exts['music'])) { - echo ' -'; - } elseif (in_array($ext, ['pdf'])) { - /*echo ' - -';*/ - $pdfurl = $files['@microsoft.graph.downloadUrl']; - echo '
      -'; - } elseif (in_array($ext, $exts['office'])) { - echo ' -'; - } elseif (in_array($ext, $exts['txt'])) { - $txtstr = htmlspecialchars(curl_request($files['@microsoft.graph.downloadUrl'])['body']); -?> -
      - -
      - -     - - - -'; ?> -
      - - -
      -'; - }*/ else { - echo ''.getconstStr('FileNotSupport').''; - } ?> -
      -
      - - - - - - - - - - - - - - -'; - foreach ($files['children'] as $file) { - // Files - if (isset($file['file'])) { - if ($_SERVER['admin'] or !isHideFile($file['name'])) { - $filenum++; ?> - - - - - - -
          
      - -
    • -
        -
      • -
      • -
      • -
      • -
      • -
      -
    • - - - -
      - -
    • -
        -
      • -
      • -
      • -
      • -
      -
    • - - - - - - - - - - - - - - - - - - - - - - - -
      -200) { - $pagenum = $files['folder']['page']; - $maxpage = ceil($files['folder']['childCount']/200); - $prepagenext = ' - - - - - - - - -
      '; - if ($pagenum!=1) { - $prepagenum = $pagenum-1; - $prepagenext .= ' - '.getconstStr('PrePage').''; - } - $prepagenext .= ' - '; - for ($page=1;$page<=$maxpage;$page++) { - if ($page == $pagenum) { - $prepagenext .= ' - ' . $page . ' '; - } else { - $prepagenext .= ' - ' . $page . ' '; - } - } - $prepagenext = substr($prepagenext,0,-1); - $prepagenext .= ' - '; - if ($pagenum!=$maxpage) { - $nextpagenum = $pagenum+1; - $prepagenext .= ' - '.getconstStr('NextPage').''; - } - $prepagenext .= ' -
      - '; - echo $prepagenext; - } - if ($_SERVER['admin']) { ?> -
      - - - -
      - -
      -
      -
      -
      -
      -
      -
      - -
      -
      -'; - } - } - } else { - echo ' -
      -
      -
      - - -
      -
      -
      '; - $statusCode = 401; - } - } ?> -
      -
      -
      - - - -
      - - - - - - -
      - - - -
      - - - - - - - - - - diff --git a/theme/renexmoe.html b/theme/renexmoe.html new file mode 100644 index 0000000..35fcb73 --- /dev/null +++ b/theme/renexmoe.html @@ -0,0 +1,515 @@ + + + + + + + + + +<!--Title--> + + + + + + + + + + + + + +
      +
      + menu + + arrow_back + + + + + + chevron_right + + +
      + refresh + +
      + +
      + +
      +
      + +
    • + account_circle + 登录 +
    • + + +
    • + account_circle管理 +
    • +
    • + exit_to_app +
      退出登陆
      +
    • +
    • + update +
      检查主题更新
      +
    • +
      + + +
    • + brightness_4深色模式 +
    • +
    • + home + +
    • + +
      + +
    • + cloud + + + +
    • + +
      + + + code +
      Github
      +
      +
    • + info +
      关于该主题
      +
    • +
      +
      + +
      + + + +
      +
      登录
      +
      +
      + lock +
      +
      +
      + +
      +
      + +
      +
      +
      +
      + 这是一个受保护的文件夹,您需要提供访问密码才能查看。 +
      +
      +
      +
      + https +
      +
      +
      +
      + + + + +
      + +
      + + +
      + faceHEAD.md +
      + + + +
      + +
      + +
      + faceREADME.md +
      +
      +
      +
      + + +
      + +
      + + + + + + + + + + +
      + + + + + + + + + + + + + + + + + + +
      + + + + + + + +
      +file_download + + + +
      + + + + { "music":"audiotrack", "video":"ondemand_video", "img":"image", + "pdf":"picture_as_pdf", "default":"insert_drive_file"} + + + diff --git a/theme/ruoli_blue.php b/theme/ruoli_blue.php deleted file mode 100644 index 92c4659..0000000 --- a/theme/ruoli_blue.php +++ /dev/null @@ -1,1240 +0,0 @@ - - - - - <?php echo $pretitle;?> - <?php echo $_SERVER['sitename'];?> - - - - - - - - - - -
      - - - -
    • - -   - -
      - -
      - -

      - -

      -1) { ?> -
      -
      -
      -
      -'.$diskname.''; - } ?> -
      -
      -
      -
      - -
      -
      -
      - - - - - -

      -
      -
      - -
      -
      - - -
      -
      -' . $files['error']['message'] . '
      '; - $statusCode=404; - } else { - if (isset($files['file'])) { -?> -
      -
      - -   -
      -
      -document.getElementById(\'url\').offsetWidth) this.style.width=\'100%\';" /> -'; - } elseif (in_array($ext, $exts['video'])) { - //echo ''; - $DPvideo=$files['@microsoft.graph.downloadUrl']; - echo '
      -'; - } elseif (in_array($ext, $exts['music'])) { - echo ' -'; - } elseif (in_array($ext, ['pdf'])) { - /*echo ' - -';*/ - $pdfurl = $files['@microsoft.graph.downloadUrl']; - echo '
      -'; - } elseif (in_array($ext, $exts['office'])) { - echo ' -'; - } elseif (in_array($ext, $exts['txt'])) { - $txtstr = htmlspecialchars(curl_request($files['@microsoft.graph.downloadUrl'])['body']); -?> -
      - -
      - -     - - - -'; ?> -
      - - -
      -'; - }*/ else { - echo ''.getconstStr('FileNotSupport').''; - } ?> -
      -
      - - - - - - - - - - - - - - -'; - foreach ($files['children'] as $file) { - // Files - if (isset($file['file'])) { - if ($_SERVER['admin'] or (substr($file['name'],0,1) !== '.' and $file['name'] !== getConfig('passfile') ) ) { - if (strtolower($file['name']) === 'head.md') $head = $file; - if (strtolower($file['name']) === 'readme.md') $readme = $file; - if (strtolower($file['name']) === 'index.html' && !$_SERVER['admin']) { - $html = curl_request(fetch_files(spurlencode(path_format($path . '/' .$file['name']),'/'))['@microsoft.graph.downloadUrl'])['body']; - return output($html,200); - } - $filenum++; ?> - - - - - - -
         
      - -
    • - -
    •     - - - -
      - -
    • -
        -
      • -
      • -
      • -
      • -
      -
    •     - - - - - - - - - - - - - - - - - - - - - - - -
      -200) { - $pagenum = $files['folder']['page']; - $maxpage = ceil($files['folder']['childCount']/200); - $prepagenext = ' - - - - - - - - -
      '; - if ($pagenum!=1) { - $prepagenum = $pagenum-1; - $prepagenext .= ' - '.getconstStr('PrePage').''; - } - $prepagenext .= ' - '; - for ($page=1;$page<=$maxpage;$page++) { - if ($page == $pagenum) { - $prepagenext .= ' - ' . $page . ' '; - } else { - $prepagenext .= ' - ' . $page . ' '; - } - } - $prepagenext = substr($prepagenext,0,-1); - $prepagenext .= ' - '; - if ($pagenum!=$maxpage) { - $nextpagenum = $pagenum+1; - $prepagenext .= ' - '.getconstStr('NextPage').''; - } - $prepagenext .= ' -
      - '; - echo $prepagenext; - } - if ($_SERVER['admin']) { ?> -
      -
      - - -
      -
      - -
      -
  • -
    -
    -
    -
    - - -
    -'; - } - if ($readme) { - echo ' -
    -
    -
    -
    -
    -
    -
    - -
    - -
    -
    -'; - } - } - } else { - echo ' -
    -
    -
    - - -
    -
    -
    '; - $statusCode = 401; - } - } ?> -
    -
    -
    - - - -
    - - - - - - -
    - - - -
    OneManager by 逸笙 theme by 若离
    - - - - - - - - - - - diff --git a/theme/ruoli_violet.php b/theme/ruoli_violet.php deleted file mode 100644 index ce71dfc..0000000 --- a/theme/ruoli_violet.php +++ /dev/null @@ -1,1259 +0,0 @@ - - - - - <?php echo $pretitle;?> - <?php echo $_SERVER['sitename'];?> - - - - - - - - - - -
    - - - -
    • - -
    • -
    • -
    • - -
    • -
    • -
  • - - -
    - -
    - -

    - -

    -1) { ?> -
    -
    -
    -
    -=strlen(path_format($_SERVER['base_path'].'/'.$disk))){ - if(substr($_SERVER['REQUEST_URI'],0,strlen(path_format($_SERVER['base_path'].'/'.$disk)))===path_format($_SERVER['base_path'].'/'.$disk)) - echo ''.$diskname.''; - else - echo ''.$diskname.''; - } - else - echo ''.$diskname.''; - - } ?> -
    -
    -
    -
    - -
    -
    -
    - - - - - -

    -
    -
    - -
    -
    - - -
    -
    -' . $files['error']['message'] . '
    '; - $statusCode=404; - } else { - if (isset($files['file'])) { -?> -
    -
    - -   -
    -
    -document.getElementById(\'url\').offsetWidth) this.style.width=\'100%\';" /> -'; - } elseif (in_array($ext, $exts['video'])) { - //echo ''; - $DPvideo=$files['@microsoft.graph.downloadUrl']; - echo '
    -'; - } elseif (in_array($ext, $exts['music'])) { - echo ' -'; - } elseif (in_array($ext, ['pdf'])) { - /*echo ' - -';*/ - $pdfurl = $files['@microsoft.graph.downloadUrl']; - echo '
    -'; - } elseif (in_array($ext, $exts['office'])) { - echo ' -'; - } elseif (in_array($ext, $exts['txt'])) { - $txtstr = htmlspecialchars(curl_request($files['@microsoft.graph.downloadUrl'])['body']); -?> -
    - -
    - -     - - - -'; ?> -
    - - -
    -'; - }*/ else { - echo ''.getconstStr('FileNotSupport').''; - } ?> -
    -
    - - - - - - - - - - - - - - -'; - foreach ($files['children'] as $file) { - // Files - if (isset($file['file'])) { - if ($_SERVER['admin'] or (substr($file['name'],0,1) !== '.' and $file['name'] !== getConfig('passfile') ) ) { - if (strtolower($file['name']) === 'head.md') $head = $file; - if (strtolower($file['name']) === 'readme.md') $readme = $file; - if (strtolower($file['name']) === 'index.html' && !$_SERVER['admin']) { - $html = curl_request(fetch_files(spurlencode(path_format($path . '/' .$file['name']),'/'))['@microsoft.graph.downloadUrl'])['body']; - return output($html,200); - } - $filenum++; ?> - - - - - - - -
       
    - -
  • -
      -
    • -
    • -
    • -
    • -
    • -
    -
  • - - - -
    - -
  • -
      -
    • -
    • -
    • -
    • -
    -
  • - - - - - - - - - - - - - - - - - - - - - - -
    -200) { - $pagenum = $files['folder']['page']; - $maxpage = ceil($files['folder']['childCount']/200); - $prepagenext = ' - - - - - - - - -
    '; - if ($pagenum!=1) { - $prepagenum = $pagenum-1; - $prepagenext .= ' - '.getconstStr('PrePage').''; - } - $prepagenext .= ' - '; - for ($page=1;$page<=$maxpage;$page++) { - if ($page == $pagenum) { - $prepagenext .= ' - ' . $page . ' '; - } else { - $prepagenext .= ' - ' . $page . ' '; - } - } - $prepagenext = substr($prepagenext,0,-1); - $prepagenext .= ' - '; - if ($pagenum!=$maxpage) { - $nextpagenum = $pagenum+1; - $prepagenext .= ' - '.getconstStr('NextPage').''; - } - $prepagenext .= ' -
    - '; - echo $prepagenext; - } - if ($_SERVER['admin']) { ?> -
    -
    - - -
    -
    - -
    - -
    -
    -
    -
    - - -
    -'; - } - if ($readme) { - echo ' -
    -
    -
    -
    -
    -
    -
    - -
    - -
    -
    -'; - } - } - } else { - echo ' -
    -
    -
    - - -
    -
    -
    '; - $statusCode = 401; - } - } ?> -
    -
    -
    - - - -
    - - - - - - -
    - - - -
    -
    Powred by 逸笙 | Theme by 若离
    - - - - - - - - - - diff --git a/theme/tfo.html b/theme/tfo.html new file mode 100644 index 0000000..a2b0f8e --- /dev/null +++ b/theme/tfo.html @@ -0,0 +1,1809 @@ + +{ + "music":"musical-notes-outline", + "video":"videocam-outline", + "img":"image-outline", + "office":"newspaper-outline", + "txt":"reader-outline", + "zip":"albums-outline", + "iso":"disc-outline", + "apk":"logo-android", + "exe":"logo-windows", + "default":"document-outline" +} + + + + + <!--Title--> + + + + + + + + + + + + + + +
    +
    + + + + + + + + + +
    +
    + + + + +
    • + +
    • +
    • +
    • + + + +
    • + + + +
    •  
    • + +
    • +
    • +
    • +
  • + +   + +
    + +
    + +

    + +

    + +
    +
    +
    + + > + +
    +
    +
    +
    +
    +
    +
    +
    + + +
    +
    +
    +
    + +
    +
    +
    +
    + + +
    +
    +
    + +
    +
    +
    + + +
    +
    +

    /

    +
    +
    + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + +
    +
    + + + +
    +
    + + + --> +
    +
    + + <!--FileName--> + + +
    + + + + + +
    Loading PDF
    " style="width: 100%;height: 800px" frameborder="0">--> + + + + + +
    + +
    + + + +
    + +
    + + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +
    + Name ▲ + +    + + + +    + + Time      Size      
    + +
  • +
      +
    • +
    • +
    • +
    • +
    • +
    +
  • + + + +
    + +
  • +
      +
    • +
    • +
    • +
    • +
    +
  • + + + + +
    + +
    + + + + + + + +
    + + + + + + + + + + + + + + +
    +
    + + +
    +
    + + + +
    +
    + + +
    +
    + + +
    +
    +
    +
    + +
    +
    +
    +
    + + +
    +
    +
    +
    + +
    +
    +
    +
    + + + + +
    + + + + + + +
    + + + + + +
    Theme byTfo for OneManager-php
    +
    + + + + + + + + + + + + + diff --git a/update.sh b/update.sh index 23cc7c2..010cb60 100644 --- a/update.sh +++ b/update.sh @@ -11,7 +11,7 @@ example: "$0" -i "$0" -u "$0" -b master - "$0" -r -b master + "$0" -u -b master "$0" -ib test " # exit @@ -62,11 +62,10 @@ OneManagerPath=`cd $(dirname $0);pwd -P` cd ${OneManagerPath} git clone ${branch} ${gitsource} -[ g"$install" == g"1" ] || \mv -b config.php OneManager-php/ +[ g"$install" == g"1" ] || \mv -b .data/config.php OneManager-php/.data/ \mv -b OneManager-php/* ./ \mv -b OneManager-php/.[^.]* ./ rm -rf *~ -rm -rf .[^.]*~ +#rm -rf .[^.]*~ rm -rf OneManager-php -chmod 666 config.php - +chmod 666 .data/config.php diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ApcCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ApcCache.php deleted file mode 100644 index 0dfbd6a..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ApcCache.php +++ /dev/null @@ -1,118 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -/** - * APC cache provider. - * - * @link www.doctrine-project.org - * @deprecated since version 1.6, use ApcuCache instead - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author David Abdemoulaie - */ -class ApcCache extends CacheProvider -{ - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - return apc_fetch($id); - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - return apc_exists($id); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - return apc_store($id, $data, $lifeTime); - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - // apc_delete returns false if the id does not exist - return apc_delete($id) || ! apc_exists($id); - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - return apc_clear_cache() && apc_clear_cache('user'); - } - - /** - * {@inheritdoc} - */ - protected function doFetchMultiple(array $keys) - { - return apc_fetch($keys) ?: []; - } - - /** - * {@inheritdoc} - */ - protected function doSaveMultiple(array $keysAndValues, $lifetime = 0) - { - $result = apc_store($keysAndValues, null, $lifetime); - - return empty($result); - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $info = apc_cache_info('', true); - $sma = apc_sma_info(); - - // @TODO - Temporary fix @see https://github.com/krakjoe/apcu/pull/42 - if (PHP_VERSION_ID >= 50500) { - $info['num_hits'] = isset($info['num_hits']) ? $info['num_hits'] : $info['nhits']; - $info['num_misses'] = isset($info['num_misses']) ? $info['num_misses'] : $info['nmisses']; - $info['start_time'] = isset($info['start_time']) ? $info['start_time'] : $info['stime']; - } - - return array( - Cache::STATS_HITS => $info['num_hits'], - Cache::STATS_MISSES => $info['num_misses'], - Cache::STATS_UPTIME => $info['start_time'], - Cache::STATS_MEMORY_USAGE => $info['mem_size'], - Cache::STATS_MEMORY_AVAILABLE => $sma['avail_mem'], - ); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ApcuCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ApcuCache.php deleted file mode 100644 index 2a91752..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ApcuCache.php +++ /dev/null @@ -1,106 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -/** - * APCu cache provider. - * - * @link www.doctrine-project.org - * @since 1.6 - * @author Kévin Dunglas - */ -class ApcuCache extends CacheProvider -{ - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - return apcu_fetch($id); - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - return apcu_exists($id); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - return apcu_store($id, $data, $lifeTime); - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - // apcu_delete returns false if the id does not exist - return apcu_delete($id) || ! apcu_exists($id); - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - return apcu_clear_cache(); - } - - /** - * {@inheritdoc} - */ - protected function doFetchMultiple(array $keys) - { - return apcu_fetch($keys) ?: []; - } - - /** - * {@inheritdoc} - */ - protected function doSaveMultiple(array $keysAndValues, $lifetime = 0) - { - $result = apcu_store($keysAndValues, null, $lifetime); - - return empty($result); - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $info = apcu_cache_info(true); - $sma = apcu_sma_info(); - - return array( - Cache::STATS_HITS => $info['num_hits'], - Cache::STATS_MISSES => $info['num_misses'], - Cache::STATS_UPTIME => $info['start_time'], - Cache::STATS_MEMORY_USAGE => $info['mem_size'], - Cache::STATS_MEMORY_AVAILABLE => $sma['avail_mem'], - ); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ArrayCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ArrayCache.php deleted file mode 100644 index 6610cc2..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ArrayCache.php +++ /dev/null @@ -1,142 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -/** - * Array cache driver. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author David Abdemoulaie - */ -class ArrayCache extends CacheProvider -{ - /** - * @var array[] $data each element being a tuple of [$data, $expiration], where the expiration is int|bool - */ - private $data = []; - - /** - * @var int - */ - private $hitsCount = 0; - - /** - * @var int - */ - private $missesCount = 0; - - /** - * @var int - */ - private $upTime; - - /** - * {@inheritdoc} - */ - public function __construct() - { - $this->upTime = time(); - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - if (! $this->doContains($id)) { - $this->missesCount += 1; - - return false; - } - - $this->hitsCount += 1; - - return $this->data[$id][0]; - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - if (! isset($this->data[$id])) { - return false; - } - - $expiration = $this->data[$id][1]; - - if ($expiration && $expiration < time()) { - $this->doDelete($id); - - return false; - } - - return true; - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - $this->data[$id] = [$data, $lifeTime ? time() + $lifeTime : false]; - - return true; - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - unset($this->data[$id]); - - return true; - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - $this->data = []; - - return true; - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - return [ - Cache::STATS_HITS => $this->hitsCount, - Cache::STATS_MISSES => $this->missesCount, - Cache::STATS_UPTIME => $this->upTime, - Cache::STATS_MEMORY_USAGE => null, - Cache::STATS_MEMORY_AVAILABLE => null, - ]; - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ChainCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ChainCache.php deleted file mode 100644 index 96c9b54..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ChainCache.php +++ /dev/null @@ -1,147 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -/** - * Cache provider that allows to easily chain multiple cache providers - * - * @author Michaël Gallego - */ -class ChainCache extends CacheProvider -{ - /** - * @var CacheProvider[] - */ - private $cacheProviders = array(); - - /** - * Constructor - * - * @param CacheProvider[] $cacheProviders - */ - public function __construct($cacheProviders = array()) - { - $this->cacheProviders = $cacheProviders; - } - - /** - * {@inheritDoc} - */ - public function setNamespace($namespace) - { - parent::setNamespace($namespace); - - foreach ($this->cacheProviders as $cacheProvider) { - $cacheProvider->setNamespace($namespace); - } - } - - /** - * {@inheritDoc} - */ - protected function doFetch($id) - { - foreach ($this->cacheProviders as $key => $cacheProvider) { - if ($cacheProvider->doContains($id)) { - $value = $cacheProvider->doFetch($id); - - // We populate all the previous cache layers (that are assumed to be faster) - for ($subKey = $key - 1 ; $subKey >= 0 ; $subKey--) { - $this->cacheProviders[$subKey]->doSave($id, $value); - } - - return $value; - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - protected function doContains($id) - { - foreach ($this->cacheProviders as $cacheProvider) { - if ($cacheProvider->doContains($id)) { - return true; - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - $stored = true; - - foreach ($this->cacheProviders as $cacheProvider) { - $stored = $cacheProvider->doSave($id, $data, $lifeTime) && $stored; - } - - return $stored; - } - - /** - * {@inheritDoc} - */ - protected function doDelete($id) - { - $deleted = true; - - foreach ($this->cacheProviders as $cacheProvider) { - $deleted = $cacheProvider->doDelete($id) && $deleted; - } - - return $deleted; - } - - /** - * {@inheritDoc} - */ - protected function doFlush() - { - $flushed = true; - - foreach ($this->cacheProviders as $cacheProvider) { - $flushed = $cacheProvider->doFlush() && $flushed; - } - - return $flushed; - } - - /** - * {@inheritDoc} - */ - protected function doGetStats() - { - // We return all the stats from all adapters - $stats = array(); - - foreach ($this->cacheProviders as $cacheProvider) { - $stats[] = $cacheProvider->doGetStats(); - } - - return $stats; - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/CouchbaseCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/CouchbaseCache.php deleted file mode 100644 index c21691d..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/CouchbaseCache.php +++ /dev/null @@ -1,121 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -use \Couchbase; - -/** - * Couchbase cache provider. - * - * @link www.doctrine-project.org - * @since 2.4 - * @author Michael Nitschinger - */ -class CouchbaseCache extends CacheProvider -{ - /** - * @var Couchbase|null - */ - private $couchbase; - - /** - * Sets the Couchbase instance to use. - * - * @param Couchbase $couchbase - * - * @return void - */ - public function setCouchbase(Couchbase $couchbase) - { - $this->couchbase = $couchbase; - } - - /** - * Gets the Couchbase instance used by the cache. - * - * @return Couchbase|null - */ - public function getCouchbase() - { - return $this->couchbase; - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - return $this->couchbase->get($id) ?: false; - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - return (null !== $this->couchbase->get($id)); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - if ($lifeTime > 30 * 24 * 3600) { - $lifeTime = time() + $lifeTime; - } - return $this->couchbase->set($id, $data, (int) $lifeTime); - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - return $this->couchbase->delete($id); - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - return $this->couchbase->flush(); - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $stats = $this->couchbase->getStats(); - $servers = $this->couchbase->getServers(); - $server = explode(":", $servers[0]); - $key = $server[0] . ":" . "11210"; - $stats = $stats[$key]; - return array( - Cache::STATS_HITS => $stats['get_hits'], - Cache::STATS_MISSES => $stats['get_misses'], - Cache::STATS_UPTIME => $stats['uptime'], - Cache::STATS_MEMORY_USAGE => $stats['bytes'], - Cache::STATS_MEMORY_AVAILABLE => $stats['limit_maxbytes'], - ); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/MemcacheCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/MemcacheCache.php deleted file mode 100644 index 8afaeea..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/MemcacheCache.php +++ /dev/null @@ -1,126 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -use \Memcache; - -/** - * Memcache cache provider. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author David Abdemoulaie - */ -class MemcacheCache extends CacheProvider -{ - /** - * @var Memcache|null - */ - private $memcache; - - /** - * Sets the memcache instance to use. - * - * @param Memcache $memcache - * - * @return void - */ - public function setMemcache(Memcache $memcache) - { - $this->memcache = $memcache; - } - - /** - * Gets the memcache instance used by the cache. - * - * @return Memcache|null - */ - public function getMemcache() - { - return $this->memcache; - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - return $this->memcache->get($id); - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - $flags = null; - $this->memcache->get($id, $flags); - - //if memcache has changed the value of "flags", it means the value exists - return ($flags !== null); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - if ($lifeTime > 30 * 24 * 3600) { - $lifeTime = time() + $lifeTime; - } - return $this->memcache->set($id, $data, 0, (int) $lifeTime); - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - // Memcache::delete() returns false if entry does not exist - return $this->memcache->delete($id) || ! $this->doContains($id); - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - return $this->memcache->flush(); - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $stats = $this->memcache->getStats(); - return array( - Cache::STATS_HITS => $stats['get_hits'], - Cache::STATS_MISSES => $stats['get_misses'], - Cache::STATS_UPTIME => $stats['uptime'], - Cache::STATS_MEMORY_USAGE => $stats['bytes'], - Cache::STATS_MEMORY_AVAILABLE => $stats['limit_maxbytes'], - ); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/MemcachedCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/MemcachedCache.php deleted file mode 100644 index 5a0fc0e..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/MemcachedCache.php +++ /dev/null @@ -1,147 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -use \Memcached; - -/** - * Memcached cache provider. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author David Abdemoulaie - */ -class MemcachedCache extends CacheProvider -{ - /** - * @var Memcached|null - */ - private $memcached; - - /** - * Sets the memcache instance to use. - * - * @param Memcached $memcached - * - * @return void - */ - public function setMemcached(Memcached $memcached) - { - $this->memcached = $memcached; - } - - /** - * Gets the memcached instance used by the cache. - * - * @return Memcached|null - */ - public function getMemcached() - { - return $this->memcached; - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - return $this->memcached->get($id); - } - - /** - * {@inheritdoc} - */ - protected function doFetchMultiple(array $keys) - { - return $this->memcached->getMulti($keys) ?: []; - } - - /** - * {@inheritdoc} - */ - protected function doSaveMultiple(array $keysAndValues, $lifetime = 0) - { - if ($lifetime > 30 * 24 * 3600) { - $lifetime = time() + $lifetime; - } - - return $this->memcached->setMulti($keysAndValues, $lifetime); - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - $this->memcached->get($id); - - return $this->memcached->getResultCode() === Memcached::RES_SUCCESS; - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - if ($lifeTime > 30 * 24 * 3600) { - $lifeTime = time() + $lifeTime; - } - return $this->memcached->set($id, $data, (int) $lifeTime); - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - return $this->memcached->delete($id) - || $this->memcached->getResultCode() === Memcached::RES_NOTFOUND; - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - return $this->memcached->flush(); - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $stats = $this->memcached->getStats(); - $servers = $this->memcached->getServerList(); - $key = $servers[0]['host'] . ':' . $servers[0]['port']; - $stats = $stats[$key]; - return array( - Cache::STATS_HITS => $stats['get_hits'], - Cache::STATS_MISSES => $stats['get_misses'], - Cache::STATS_UPTIME => $stats['uptime'], - Cache::STATS_MEMORY_USAGE => $stats['bytes'], - Cache::STATS_MEMORY_AVAILABLE => $stats['limit_maxbytes'], - ); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/MongoDBCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/MongoDBCache.php deleted file mode 100644 index 75fe0ca..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/MongoDBCache.php +++ /dev/null @@ -1,197 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -use MongoBinData; -use MongoCollection; -use MongoCursorException; -use MongoDate; - -/** - * MongoDB cache provider. - * - * @since 1.1 - * @author Jeremy Mikola - */ -class MongoDBCache extends CacheProvider -{ - /** - * The data field will store the serialized PHP value. - */ - const DATA_FIELD = 'd'; - - /** - * The expiration field will store a MongoDate value indicating when the - * cache entry should expire. - * - * With MongoDB 2.2+, entries can be automatically deleted by MongoDB by - * indexing this field with the "expireAfterSeconds" option equal to zero. - * This will direct MongoDB to regularly query for and delete any entries - * whose date is older than the current time. Entries without a date value - * in this field will be ignored. - * - * The cache provider will also check dates on its own, in case expired - * entries are fetched before MongoDB's TTLMonitor pass can expire them. - * - * @see http://docs.mongodb.org/manual/tutorial/expire-data/ - */ - const EXPIRATION_FIELD = 'e'; - - /** - * @var MongoCollection - */ - private $collection; - - /** - * Constructor. - * - * This provider will default to the write concern and read preference - * options set on the MongoCollection instance (or inherited from MongoDB or - * MongoClient). Using an unacknowledged write concern (< 1) may make the - * return values of delete() and save() unreliable. Reading from secondaries - * may make contain() and fetch() unreliable. - * - * @see http://www.php.net/manual/en/mongo.readpreferences.php - * @see http://www.php.net/manual/en/mongo.writeconcerns.php - * @param MongoCollection $collection - */ - public function __construct(MongoCollection $collection) - { - $this->collection = $collection; - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - $document = $this->collection->findOne(array('_id' => $id), array(self::DATA_FIELD, self::EXPIRATION_FIELD)); - - if ($document === null) { - return false; - } - - if ($this->isExpired($document)) { - $this->doDelete($id); - return false; - } - - return unserialize($document[self::DATA_FIELD]->bin); - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - $document = $this->collection->findOne(array('_id' => $id), array(self::EXPIRATION_FIELD)); - - if ($document === null) { - return false; - } - - if ($this->isExpired($document)) { - $this->doDelete($id); - return false; - } - - return true; - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - try { - $result = $this->collection->update( - array('_id' => $id), - array('$set' => array( - self::EXPIRATION_FIELD => ($lifeTime > 0 ? new MongoDate(time() + $lifeTime) : null), - self::DATA_FIELD => new MongoBinData(serialize($data), MongoBinData::BYTE_ARRAY), - )), - array('upsert' => true, 'multiple' => false) - ); - } catch (MongoCursorException $e) { - return false; - } - - return isset($result['ok']) ? $result['ok'] == 1 : true; - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - $result = $this->collection->remove(array('_id' => $id)); - - return isset($result['ok']) ? $result['ok'] == 1 : true; - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - // Use remove() in lieu of drop() to maintain any collection indexes - $result = $this->collection->remove(); - - return isset($result['ok']) ? $result['ok'] == 1 : true; - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $serverStatus = $this->collection->db->command(array( - 'serverStatus' => 1, - 'locks' => 0, - 'metrics' => 0, - 'recordStats' => 0, - 'repl' => 0, - )); - - $collStats = $this->collection->db->command(array('collStats' => 1)); - - return array( - Cache::STATS_HITS => null, - Cache::STATS_MISSES => null, - Cache::STATS_UPTIME => (isset($serverStatus['uptime']) ? (int) $serverStatus['uptime'] : null), - Cache::STATS_MEMORY_USAGE => (isset($collStats['size']) ? (int) $collStats['size'] : null), - Cache::STATS_MEMORY_AVAILABLE => null, - ); - } - - /** - * Check if the document is expired. - * - * @param array $document - * - * @return bool - */ - private function isExpired(array $document) - { - return isset($document[self::EXPIRATION_FIELD]) && - $document[self::EXPIRATION_FIELD] instanceof MongoDate && - $document[self::EXPIRATION_FIELD]->sec < time(); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/PhpFileCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/PhpFileCache.php deleted file mode 100644 index 5e75196..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/PhpFileCache.php +++ /dev/null @@ -1,120 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -/** - * Php file cache driver. - * - * @since 2.3 - * @author Fabio B. Silva - */ -class PhpFileCache extends FileCache -{ - const EXTENSION = '.doctrinecache.php'; - - /** - * {@inheritdoc} - */ - public function __construct($directory, $extension = self::EXTENSION, $umask = 0002) - { - parent::__construct($directory, $extension, $umask); - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - $value = $this->includeFileForId($id); - - if (! $value) { - return false; - } - - if ($value['lifetime'] !== 0 && $value['lifetime'] < time()) { - return false; - } - - return $value['data']; - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - $value = $this->includeFileForId($id); - - if (! $value) { - return false; - } - - return $value['lifetime'] === 0 || $value['lifetime'] > time(); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - if ($lifeTime > 0) { - $lifeTime = time() + $lifeTime; - } - - if (is_object($data) && ! method_exists($data, '__set_state')) { - throw new \InvalidArgumentException( - "Invalid argument given, PhpFileCache only allows objects that implement __set_state() " . - "and fully support var_export(). You can use the FilesystemCache to save arbitrary object " . - "graphs using serialize()/deserialize()." - ); - } - - $filename = $this->getFilename($id); - - $value = array( - 'lifetime' => $lifeTime, - 'data' => $data - ); - - $value = var_export($value, true); - $code = sprintf('writeFile($filename, $code); - } - - /** - * @param string $id - * - * @return array|false - */ - private function includeFileForId($id) - { - $fileName = $this->getFilename($id); - - // note: error suppression is still faster than `file_exists`, `is_file` and `is_readable` - $value = @include $fileName; - - if (! isset($value['lifetime'])) { - return false; - } - - return $value; - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/PredisCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/PredisCache.php deleted file mode 100644 index bcd2749..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/PredisCache.php +++ /dev/null @@ -1,136 +0,0 @@ - - */ -class PredisCache extends CacheProvider -{ - /** - * @var ClientInterface - */ - private $client; - - /** - * @param ClientInterface $client - * - * @return void - */ - public function __construct(ClientInterface $client) - { - $this->client = $client; - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - $result = $this->client->get($id); - if (null === $result) { - return false; - } - - return unserialize($result); - } - - /** - * {@inheritdoc} - */ - protected function doFetchMultiple(array $keys) - { - $fetchedItems = call_user_func_array(array($this->client, 'mget'), $keys); - - return array_map('unserialize', array_filter(array_combine($keys, $fetchedItems))); - } - - /** - * {@inheritdoc} - */ - protected function doSaveMultiple(array $keysAndValues, $lifetime = 0) - { - if ($lifetime) { - $success = true; - - // Keys have lifetime, use SETEX for each of them - foreach ($keysAndValues as $key => $value) { - $response = $this->client->setex($key, $lifetime, serialize($value)); - - if ((string) $response != 'OK') { - $success = false; - } - } - - return $success; - } - - // No lifetime, use MSET - $response = $this->client->mset(array_map(function ($value) { - return serialize($value); - }, $keysAndValues)); - - return (string) $response == 'OK'; - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - return (bool) $this->client->exists($id); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - $data = serialize($data); - if ($lifeTime > 0) { - $response = $this->client->setex($id, $lifeTime, $data); - } else { - $response = $this->client->set($id, $data); - } - - return $response === true || $response == 'OK'; - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - return $this->client->del($id) >= 0; - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - $response = $this->client->flushdb(); - - return $response === true || $response == 'OK'; - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $info = $this->client->info(); - - return array( - Cache::STATS_HITS => $info['Stats']['keyspace_hits'], - Cache::STATS_MISSES => $info['Stats']['keyspace_misses'], - Cache::STATS_UPTIME => $info['Server']['uptime_in_seconds'], - Cache::STATS_MEMORY_USAGE => $info['Memory']['used_memory'], - Cache::STATS_MEMORY_AVAILABLE => false - ); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/RedisCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/RedisCache.php deleted file mode 100644 index 22add66..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/RedisCache.php +++ /dev/null @@ -1,180 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -use Redis; - -/** - * Redis cache provider. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Osman Ungur - */ -class RedisCache extends CacheProvider -{ - /** - * @var Redis|null - */ - private $redis; - - /** - * Sets the redis instance to use. - * - * @param Redis $redis - * - * @return void - */ - public function setRedis(Redis $redis) - { - $redis->setOption(Redis::OPT_SERIALIZER, $this->getSerializerValue()); - $this->redis = $redis; - } - - /** - * Gets the redis instance used by the cache. - * - * @return Redis|null - */ - public function getRedis() - { - return $this->redis; - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - return $this->redis->get($id); - } - - /** - * {@inheritdoc} - */ - protected function doFetchMultiple(array $keys) - { - $fetchedItems = array_combine($keys, $this->redis->mget($keys)); - - // Redis mget returns false for keys that do not exist. So we need to filter those out unless it's the real data. - $foundItems = array(); - - foreach ($fetchedItems as $key => $value) { - if (false !== $value || $this->redis->exists($key)) { - $foundItems[$key] = $value; - } - } - - return $foundItems; - } - - /** - * {@inheritdoc} - */ - protected function doSaveMultiple(array $keysAndValues, $lifetime = 0) - { - if ($lifetime) { - $success = true; - - // Keys have lifetime, use SETEX for each of them - foreach ($keysAndValues as $key => $value) { - if (!$this->redis->setex($key, $lifetime, $value)) { - $success = false; - } - } - - return $success; - } - - // No lifetime, use MSET - return (bool) $this->redis->mset($keysAndValues); - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - return $this->redis->exists($id); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - if ($lifeTime > 0) { - return $this->redis->setex($id, $lifeTime, $data); - } - - return $this->redis->set($id, $data); - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - return $this->redis->delete($id) >= 0; - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - return $this->redis->flushDB(); - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $info = $this->redis->info(); - return array( - Cache::STATS_HITS => $info['keyspace_hits'], - Cache::STATS_MISSES => $info['keyspace_misses'], - Cache::STATS_UPTIME => $info['uptime_in_seconds'], - Cache::STATS_MEMORY_USAGE => $info['used_memory'], - Cache::STATS_MEMORY_AVAILABLE => false - ); - } - - /** - * Returns the serializer constant to use. If Redis is compiled with - * igbinary support, that is used. Otherwise the default PHP serializer is - * used. - * - * @return integer One of the Redis::SERIALIZER_* constants - */ - protected function getSerializerValue() - { - if (defined('HHVM_VERSION')) { - return Redis::SERIALIZER_PHP; - } - - if (defined('Redis::SERIALIZER_IGBINARY') && extension_loaded('igbinary')) { - return Redis::SERIALIZER_IGBINARY; - } - - return Redis::SERIALIZER_PHP; - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/RiakCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/RiakCache.php deleted file mode 100644 index 0baa3f2..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/RiakCache.php +++ /dev/null @@ -1,250 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -use Riak\Bucket; -use Riak\Connection; -use Riak\Input; -use Riak\Exception; -use Riak\Object; - -/** - * Riak cache provider. - * - * @link www.doctrine-project.org - * @since 1.1 - * @author Guilherme Blanco - */ -class RiakCache extends CacheProvider -{ - const EXPIRES_HEADER = 'X-Riak-Meta-Expires'; - - /** - * @var \Riak\Bucket - */ - private $bucket; - - /** - * Sets the riak bucket instance to use. - * - * @param \Riak\Bucket $bucket - */ - public function __construct(Bucket $bucket) - { - $this->bucket = $bucket; - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - try { - $response = $this->bucket->get($id); - - // No objects found - if ( ! $response->hasObject()) { - return false; - } - - // Check for attempted siblings - $object = ($response->hasSiblings()) - ? $this->resolveConflict($id, $response->getVClock(), $response->getObjectList()) - : $response->getFirstObject(); - - // Check for expired object - if ($this->isExpired($object)) { - $this->bucket->delete($object); - - return false; - } - - return unserialize($object->getContent()); - } catch (Exception\RiakException $e) { - // Covers: - // - Riak\ConnectionException - // - Riak\CommunicationException - // - Riak\UnexpectedResponseException - // - Riak\NotFoundException - } - - return false; - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - try { - // We only need the HEAD, not the entire object - $input = new Input\GetInput(); - - $input->setReturnHead(true); - - $response = $this->bucket->get($id, $input); - - // No objects found - if ( ! $response->hasObject()) { - return false; - } - - $object = $response->getFirstObject(); - - // Check for expired object - if ($this->isExpired($object)) { - $this->bucket->delete($object); - - return false; - } - - return true; - } catch (Exception\RiakException $e) { - // Do nothing - } - - return false; - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - try { - $object = new Object($id); - - $object->setContent(serialize($data)); - - if ($lifeTime > 0) { - $object->addMetadata(self::EXPIRES_HEADER, (string) (time() + $lifeTime)); - } - - $this->bucket->put($object); - - return true; - } catch (Exception\RiakException $e) { - // Do nothing - } - - return false; - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - try { - $this->bucket->delete($id); - - return true; - } catch (Exception\BadArgumentsException $e) { - // Key did not exist on cluster already - } catch (Exception\RiakException $e) { - // Covers: - // - Riak\Exception\ConnectionException - // - Riak\Exception\CommunicationException - // - Riak\Exception\UnexpectedResponseException - } - - return false; - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - try { - $keyList = $this->bucket->getKeyList(); - - foreach ($keyList as $key) { - $this->bucket->delete($key); - } - - return true; - } catch (Exception\RiakException $e) { - // Do nothing - } - - return false; - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - // Only exposed through HTTP stats API, not Protocol Buffers API - return null; - } - - /** - * Check if a given Riak Object have expired. - * - * @param \Riak\Object $object - * - * @return bool - */ - private function isExpired(Object $object) - { - $metadataMap = $object->getMetadataMap(); - - return isset($metadataMap[self::EXPIRES_HEADER]) - && $metadataMap[self::EXPIRES_HEADER] < time(); - } - - /** - * On-read conflict resolution. Applied approach here is last write wins. - * Specific needs may override this method to apply alternate conflict resolutions. - * - * {@internal Riak does not attempt to resolve a write conflict, and store - * it as sibling of conflicted one. By following this approach, it is up to - * the next read to resolve the conflict. When this happens, your fetched - * object will have a list of siblings (read as a list of objects). - * In our specific case, we do not care about the intermediate ones since - * they are all the same read from storage, and we do apply a last sibling - * (last write) wins logic. - * If by any means our resolution generates another conflict, it'll up to - * next read to properly solve it.} - * - * @param string $id - * @param string $vClock - * @param array $objectList - * - * @return \Riak\Object - */ - protected function resolveConflict($id, $vClock, array $objectList) - { - // Our approach here is last-write wins - $winner = $objectList[count($objectList)]; - - $putInput = new Input\PutInput(); - $putInput->setVClock($vClock); - - $mergedObject = new Object($id); - $mergedObject->setContent($winner->getContent()); - - $this->bucket->put($mergedObject, $putInput); - - return $mergedObject; - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/SQLite3Cache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/SQLite3Cache.php deleted file mode 100644 index 0bf6e4d..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/SQLite3Cache.php +++ /dev/null @@ -1,220 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -use SQLite3; -use SQLite3Result; - -/** - * SQLite3 cache provider. - * - * @since 1.4 - * @author Jake Bell - */ -class SQLite3Cache extends CacheProvider -{ - /** - * The ID field will store the cache key. - */ - const ID_FIELD = 'k'; - - /** - * The data field will store the serialized PHP value. - */ - const DATA_FIELD = 'd'; - - /** - * The expiration field will store a date value indicating when the - * cache entry should expire. - */ - const EXPIRATION_FIELD = 'e'; - - /** - * @var SQLite3 - */ - private $sqlite; - - /** - * @var string - */ - private $table; - - /** - * Constructor. - * - * Calling the constructor will ensure that the database file and table - * exist and will create both if they don't. - * - * @param SQLite3 $sqlite - * @param string $table - */ - public function __construct(SQLite3 $sqlite, $table) - { - $this->sqlite = $sqlite; - $this->table = (string) $table; - - list($id, $data, $exp) = $this->getFields(); - - return $this->sqlite->exec(sprintf( - 'CREATE TABLE IF NOT EXISTS %s(%s TEXT PRIMARY KEY NOT NULL, %s BLOB, %s INTEGER)', - $table, - $id, - $data, - $exp - )); - } - - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - if ($item = $this->findById($id)) { - return unserialize($item[self::DATA_FIELD]); - } - - return false; - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - return null !== $this->findById($id, false); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - $statement = $this->sqlite->prepare(sprintf( - 'INSERT OR REPLACE INTO %s (%s) VALUES (:id, :data, :expire)', - $this->table, - implode(',', $this->getFields()) - )); - - $statement->bindValue(':id', $id); - $statement->bindValue(':data', serialize($data), SQLITE3_BLOB); - $statement->bindValue(':expire', $lifeTime > 0 ? time() + $lifeTime : null); - - return $statement->execute() instanceof SQLite3Result; - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - list($idField) = $this->getFields(); - - $statement = $this->sqlite->prepare(sprintf( - 'DELETE FROM %s WHERE %s = :id', - $this->table, - $idField - )); - - $statement->bindValue(':id', $id); - - return $statement->execute() instanceof SQLite3Result; - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - return $this->sqlite->exec(sprintf('DELETE FROM %s', $this->table)); - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - // no-op. - } - - /** - * Find a single row by ID. - * - * @param mixed $id - * @param bool $includeData - * - * @return array|null - */ - private function findById($id, $includeData = true) - { - list($idField) = $fields = $this->getFields(); - - if (!$includeData) { - $key = array_search(static::DATA_FIELD, $fields); - unset($fields[$key]); - } - - $statement = $this->sqlite->prepare(sprintf( - 'SELECT %s FROM %s WHERE %s = :id LIMIT 1', - implode(',', $fields), - $this->table, - $idField - )); - - $statement->bindValue(':id', $id, SQLITE3_TEXT); - - $item = $statement->execute()->fetchArray(SQLITE3_ASSOC); - - if ($item === false) { - return null; - } - - if ($this->isExpired($item)) { - $this->doDelete($id); - - return null; - } - - return $item; - } - - /** - * Gets an array of the fields in our table. - * - * @return array - */ - private function getFields() - { - return array(static::ID_FIELD, static::DATA_FIELD, static::EXPIRATION_FIELD); - } - - /** - * Check if the item is expired. - * - * @param array $item - * - * @return bool - */ - private function isExpired(array $item) - { - return isset($item[static::EXPIRATION_FIELD]) && - $item[self::EXPIRATION_FIELD] !== null && - $item[self::EXPIRATION_FIELD] < time(); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/Version.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/Version.php deleted file mode 100644 index a6399ec..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/Version.php +++ /dev/null @@ -1,25 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -class Version -{ - const VERSION = '1.6.1-DEV'; -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/VoidCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/VoidCache.php deleted file mode 100644 index 65e8456..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/VoidCache.php +++ /dev/null @@ -1,78 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -/** - * Void cache driver. The cache could be of use in tests where you don`t need to cache anything. - * - * @link www.doctrine-project.org - * @since 1.5 - * @author Kotlyar Maksim - */ -class VoidCache extends CacheProvider -{ - /** - * {@inheritDoc} - */ - protected function doFetch($id) - { - return false; - } - - /** - * {@inheritDoc} - */ - protected function doContains($id) - { - return false; - } - - /** - * {@inheritDoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - return true; - } - - /** - * {@inheritDoc} - */ - protected function doDelete($id) - { - return true; - } - - /** - * {@inheritDoc} - */ - protected function doFlush() - { - return true; - } - - /** - * {@inheritDoc} - */ - protected function doGetStats() - { - return; - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/WinCacheCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/WinCacheCache.php deleted file mode 100644 index 8a250b2..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/WinCacheCache.php +++ /dev/null @@ -1,109 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -/** - * WinCache cache provider. - * - * @link www.doctrine-project.org - * @since 2.2 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author David Abdemoulaie - */ -class WinCacheCache extends CacheProvider -{ - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - return wincache_ucache_get($id); - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - return wincache_ucache_exists($id); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - return wincache_ucache_set($id, $data, $lifeTime); - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - return wincache_ucache_delete($id); - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - return wincache_ucache_clear(); - } - - /** - * {@inheritdoc} - */ - protected function doFetchMultiple(array $keys) - { - return wincache_ucache_get($keys); - } - - /** - * {@inheritdoc} - */ - protected function doSaveMultiple(array $keysAndValues, $lifetime = 0) - { - $result = wincache_ucache_set($keysAndValues, null, $lifetime); - - return empty($result); - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $info = wincache_ucache_info(); - $meminfo = wincache_ucache_meminfo(); - - return array( - Cache::STATS_HITS => $info['total_hit_count'], - Cache::STATS_MISSES => $info['total_miss_count'], - Cache::STATS_UPTIME => $info['total_cache_uptime'], - Cache::STATS_MEMORY_USAGE => $meminfo['memory_total'], - Cache::STATS_MEMORY_AVAILABLE => $meminfo['memory_free'], - ); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/XcacheCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/XcacheCache.php deleted file mode 100644 index a2c4ca5..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/XcacheCache.php +++ /dev/null @@ -1,112 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -/** - * Xcache cache driver. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - * @author David Abdemoulaie - */ -class XcacheCache extends CacheProvider -{ - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - return $this->doContains($id) ? unserialize(xcache_get($id)) : false; - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - return xcache_isset($id); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - return xcache_set($id, serialize($data), (int) $lifeTime); - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - return xcache_unset($id); - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - $this->checkAuthorization(); - - xcache_clear_cache(XC_TYPE_VAR); - - return true; - } - - /** - * Checks that xcache.admin.enable_auth is Off. - * - * @return void - * - * @throws \BadMethodCallException When xcache.admin.enable_auth is On. - */ - protected function checkAuthorization() - { - if (ini_get('xcache.admin.enable_auth')) { - throw new \BadMethodCallException( - 'To use all features of \Doctrine\Common\Cache\XcacheCache, ' - . 'you must set "xcache.admin.enable_auth" to "Off" in your php.ini.' - ); - } - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - $this->checkAuthorization(); - - $info = xcache_info(XC_TYPE_VAR, 0); - return array( - Cache::STATS_HITS => $info['hits'], - Cache::STATS_MISSES => $info['misses'], - Cache::STATS_UPTIME => null, - Cache::STATS_MEMORY_USAGE => $info['size'], - Cache::STATS_MEMORY_AVAILABLE => $info['avail'], - ); - } -} diff --git a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ZendDataCache.php b/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ZendDataCache.php deleted file mode 100644 index 6e35ac8..0000000 --- a/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ZendDataCache.php +++ /dev/null @@ -1,83 +0,0 @@ -. - */ - -namespace Doctrine\Common\Cache; - -/** - * Zend Data Cache cache driver. - * - * @link www.doctrine-project.org - * @since 2.0 - * @author Ralph Schindler - * @author Guilherme Blanco - */ -class ZendDataCache extends CacheProvider -{ - /** - * {@inheritdoc} - */ - protected function doFetch($id) - { - return zend_shm_cache_fetch($id); - } - - /** - * {@inheritdoc} - */ - protected function doContains($id) - { - return (false !== zend_shm_cache_fetch($id)); - } - - /** - * {@inheritdoc} - */ - protected function doSave($id, $data, $lifeTime = 0) - { - return zend_shm_cache_store($id, $data, $lifeTime); - } - - /** - * {@inheritdoc} - */ - protected function doDelete($id) - { - return zend_shm_cache_delete($id); - } - - /** - * {@inheritdoc} - */ - protected function doFlush() - { - $namespace = $this->getNamespace(); - if (empty($namespace)) { - return zend_shm_cache_clear(); - } - return zend_shm_cache_clear($namespace); - } - - /** - * {@inheritdoc} - */ - protected function doGetStats() - { - return null; - } -} diff --git a/version b/version index e439bf6..2c2075c 100644 --- a/version +++ b/version @@ -1,7 +1,106 @@ +20220127-1234.43 +change login page, default not '?admin' but '?login=admin' now! and if set adminloginpage, it will be '?login=[value]'. rm JumpFirstDisk, 403 in operating root, change sorting disk, remake disktags tab, add global md config. Allow Preview when enable downloadencrypt. some change in adding Onedrive disk. show upload progress in table background. fix some bugs. +更改登录地址,默认不再是'?admin'而是'?login=admin',如果设置了adminloginpage,那登录地址会是'?login=值'。移除 JumpFirstDisk,在root操作时返回403,更改盘排序,重做盘符排列,添加全局md配置。在开启downloadencrypt后可以网页预览了。添加onedrive盘时稍做修改。上传时以背景做进度条。修复其它bug。 + +20211220-1100.42 +Add new platform Replit. Add a git source for update. sha1.js use jsdelivr cdn. fix some bugs. +新增Replit平台。新增国内git源,以后国内可以选择从HIT源更新。sha1.js换成jsdelivr CDN。修复bug。 +20211201-1602.41 +add a latent function, you can edit platform token(or API key) via '?setup=auth' when the token invalid, not need edit it in Environment(or Config Var) manually, (even in Vercel, config saved in file, and can't modiy it manually). +新增隐藏功能,在平台操作代码的token或API key失效时,可以在 '?setup=auth' 修改它,不用去环境变量修改了(特别地,Vercel保存在代码中时都改不到)。 +20211129 +check if there is another deployment building when start deploy. +Vercel部署时检测是否有另一个部署。 +20211104 +check if exist php-curl or not in php host and VPS. +在VPS中检测是否有php-curl。 +20211021 +specialchars, fix: list folder, encrypt folder, preview files, rename, show in title, error on back link after login at specialchars folder, etc. +针对特殊字符,解决目录的列表,目录的加密,文件的预览,目录与文件重命名,在网页标题的显示,在特殊字符处登录后跳转出错等问题。 +20211006 +oprate files by fileID, write a localStorage when login to anti CSRF. +管理时对文件id操作,管理登录时写入一个localStorage预防CSRF。 +20210908 +add fileConduitSize&fileConduitCacheTime, little files can stream from program, better to show html/js as local file. +增加fileConduitSize,fileConduitCacheTime,小文件可以从服务器中转,以对html/js本地化更好的支持。 +20210903 +add a latent function, you can run some command by '?setup=cmd', be care, please dont try "top", and set times by "ping -c 4". +新增隐藏功能,你可以通过'?setup=cmd'来跑一些命令,注意不要试图跑top,另外ping请-c设置次数。 +20210820-1810.40 +because Vercel must redeploy after change Environment Variables, and it must <4k, so decide that, save config in code file. in Vercel, after update, please install again. if you want continue use Environment, please add a ( name: "ONEMANAGER_CONFIG_SAVE", value: "env" ) in Environment Variables in Project Settings before update. +因为Vercel修改环境变量也必须重新部署才生效,而且环境变量只能小于4k,所以决定将配置保存在代码文件中。升级更新后,用Vercel的请重新安装。如果还想继续使用环境变量,请在更新前,在Project Settings的Environment Variables中,新增一个( name: "ONEMANAGER_CONFIG_SAVE", value: "env" )的环境变量。 +20210817-2030.39 +fix bugs in Vercel. add wait function in operating. change update method in SCF. add payme in readme. +修复一些Vercel上的bug。在操作完后添加等待功能,确认平台已经准备好。SCF的更新方式改变。在readme中添加讨饭链接。 +20210804-1535.38 +try fix "&"/"&" in filename. try show an img too height. change upload chunk size when upload speed>10M/s. fix forceHttps when custom domain in Glitch. fix ionicons svg lost.try use file id when rename. background (or other) based on width/height not only width. fix some bugs. Pre-Add platform Vercel, just wait bugs fixed. +尝试修复文件名含 "&"/"&"。尝试在一屏内显示过长的图片。上传时分割的块大小随着上传速度改变。修复Glitch中使用自定义域名时forceHttps问题。修复ionicons图标失踪。尝试在重命名时使用file id来操作。背景(或其它)基于长宽来看是竖屏还是横屏,不再只看宽度。修复其它bug。预加入Vercel平台,等修复bugs。 +20210512-1648.37 +add setting "forceHttps", can force 302 jump to https. fix preview office files. fix manage in safari.fix disktag can be "home". fix some bugs. +新增一个设置,可以强制跳转https。修复office文档预览。修复safari上点不了管理。盘的标签可以是home了,随便命名了。修复一些其它问题。 +20210331-1530.36 +admin can only use classic theme after admin login, and guest can not change theme now. fix: Sharelink can not work in php8. show disk space. limit 5 files in uploading. do with activityLimitReached. fix some bugs. +暂时解决昨天阿里云盘最新防盗链。管理登录后只能用classic主题,游客不能再切换主题了。修复Sharelink在php8下不能正常工作。显示盘空间。同时上传文件数限制5个。对activityLimitReached稍微处理。修复一些bug。 +20210313-1352.35 +use driveId, after update, Aliyundrive and Googledrive please click the Change link after Driver type. try fix: php8 will run error 500. change layout in settup. fix: uploading non-englist file name. try fix: sha1 a big file. +换用driveId,更新后Aliyundrive与Googledrive请点一下那个切换链接。尝试修复php8的500 ERROR。改变设置页面的布局。修复上传中文名文件时最终文件以url代码命名。阿里云盘上传时可以sha1大文件了。 +20210311-2004.34 +try fix: can not login, sha1.js not loaded(changed a cdn), show error log. +尝试修复登录不了的情况:可能sha1.js没有载入(换了源),在登录页显示出错信息。 +20210309-1718.33 +Googledrive can operate now, but the uploading can not done on explorer without token. Onedrive try deal with activeLimit. Can change admin password now. Admin password will sha1 when submitting. Fix some bugs. +Googledrive可以管理操作了,但因为没法在浏览器端不带token上传,所以上传操作作罢。Onedrive尝试处理activeLimit。可以修改admin密码了。登录等提交admin密码时,会sha1加密再提交。修复一些bug。 +20210301-1745.32 +Onedrive client secret extend. export&import config. adding Googledrive. add reffer: only listing domains can refer. add diskDescription: tips of disk. Heroku change function_name to HerokuappId. try fix domainforproxy. fix create in Aliyundrive. fix other bugs. +Onedrive 的client延期。可以导入导出配置了。初步添加Googledrive。添加reffer:只有指定域名能引用。添加diskDescription:可以对盘备注了。Heroku中将function_name改为使用HerokuappId。尝试修复domainforproxy在个人帐号时的问题。修复阿里云盘不能新建与加密。修复其它bug。 +20210118-1600.31 +can change Ondrive to Sharepoint, can copy a disk. fix a bug that 500 error in setup. +Onedrive跟Sharepoint可以切换了,可以复制一个盘。修复bug。 +20210115-1111.30 +v3, after update, please AddDisk again, please set passfile again. themes of php deleted, or you can use branch v2_last. +v3,一键升级后请重新添加盘,passfile失效,重新设置。php主题删掉了,要么就用v2_last分支。 +20201229.29 +Modify tags, change sequence of disk. +可以修改标签,移动标签顺序。 +20201215-1400.28 +fix: hackers can upload files to ANY folder (or create a new folder) in your Onedrive. add language zh-tw. now, on heroku, xhr can post. fix: 2 or more space in file name cause bugs. +修复:构造代码后可以上传文件到你Onedrive的任意目录(甚至创建新目录)。新增zh-tw语言。xhr的post在heroku会接收了,改回post。修复:文件名有多个空格相连时造成bug。 +20201106-1730.27 +Add theme. A code used in CloudFlare Workers. Admin not need password in folder. Add caddy2 rewrite rule. Add new platform Glitch. web hosting and VPS user should backup your config.php, after update, copy it to .data foloder. +添加主题。添加一段用于CF workers的代码。加密目录管理员不需要密码了。添加caddy2伪静态。新增Glitch平台。虚拟主机与VPS用户请备份config.php,升级后,手动将它覆盖到.data目录。 +20200828-1420.26 +nginx rewrite rule exclude .well-known folder, as auto SSL. add web.config to rewrite in IIS. now in windwos can do with \ in path. in aliyun FC & huawei FG API, use my code. CN 21Vianet client_id&secret expire. update description now only show new. +nginx的伪静态中排除.well-known目录,方便自动SSL。添加IIS的伪静态。与linux不同,处理windows下目录用\分隔。FC、FG中使用自己代码对接平台。世纪互联旧API即将过期失效,升级后世纪互联的盘需要删除重新添加。更新说明只显示部分。 +20200817-1740.25 +when multy disks, now will default show disks as folders in root, if set autoJumpFirstDisk 1, it will auto jump to first disk. +多盘时,在网站根目录,默认会将各盘当成文件夹显示,可以去设置中设置autoJumpFirstDisk为1,这样可以跟以前一样自动跳到第一个盘。 +20200816-1145.24 +add platform: Baidu CFC. add setting: mobile background. +新增百度CFC平台。可以分别设置PC与手机的背景。 +20200808-1130.23 +FG: select save in env or file. +在FG中安装时,选择配置保存在环境变量还是文件中。 +20200806-1130.23 +SCF: select save in env or file. +在SCF中安装时,选择配置保存在环境变量还是文件中。 +20200804-1453.22 +fix: once error will stop the after files in uploading multy files. SCF can get region now, change install. SCF config save in code file now not in env, if use SCF, you must reinstall after update. +修复,当上传多个文件时,一个文件出错将导致后续文件不再上传。SCF可以获取到region了,安装过程修改。在SCF中,现在将配置保存到代码文件中,不受环境变量4K大小限制,升级后,用SCF的要重装。 +20200723-1430.21 +fix content-type in "?json". can not custom microsoft API id & secret by a link now, so show the return uri. +当使用"?json"时,现在content-type是json了。现在微软不能一键创建API应用了,提供回调URI。 +20200713-1800.20 +add platform: Huawei cloud Function Graph. now you can use "?json" to get a json of folder or file. fix some bug. +新增白嫖平台:华为云函数工作流FG。可以用"?json"来获得目录或文件的json。修复bug。 +20200607-1856.19 +add platform: Aliyun Function Compute. add setting: replace sharepoint.com to a proxy server name. add setting: disableShowThumb,customTheme. add function: php hosting website can update by a click +现在可以安装到阿里函数计算FC了。php空间可以一键更新了。可以设置某个盘替换sharpoint.com域名为你的反代域名。新增disableShowThumb,customTheme。 +20200503-1848.18 +Rebuild theme. Add custom Css & custom Script, add FunctionalityFile: head.omf & foot.omf. +重建主题文件结构。增加自定义css与自定义script。增加2个功能文件:head.omf、foot.omf。 20200402-1830.17 Oneclick update can select which branch to update. Now use the accept language instead of the language config. 一键更新可以选择哪个分支了。现在开始使用浏览器语言,抛弃language设置。 - 20200326-0001.16 You can add sharepoint site drive as a disk, you must reinstall after update. 可以将sharepoint网站添加成一个盘,由于结构改变,升级后只能重装。 diff --git a/web.config b/web.config new file mode 100644 index 0000000..18e4239 --- /dev/null +++ b/web.config @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/writeable.sh b/writeable.sh index 8d3b5dc..44da92b 100644 --- a/writeable.sh +++ b/writeable.sh @@ -1,3 +1,3 @@ OneManagerPath=`cd $(dirname $0);pwd -P` cd ${OneManagerPath} -chmod 666 config.php +chmod 666 .data/config.php