common.php 73.7 KB
Newer Older
Q
qkqpttgf 已提交
1 2
<?php

3 4 5 6 7 8 9 10
$Base64Env = [
    //'APIKey', // used in heroku.
    //'Region', // used in SCF.
    //'SecretId', // used in SCF.
    //'SecretKey', // used in SCF.
    //'admin',
    //'adminloginpage',
    'background',
11
    'diskname',
12
    //'disktag',
13
    //'downloadencrypt',
14
    //'function_name', // used in heroku.
Q
qkqpttgf 已提交
15
    //'hideFunctionalityFile',
Q
qkqpttgf 已提交
16
    //'timezone',
17 18 19
    //'passfile',
    'sitename',
    //'theme',
Q
qkqpttgf 已提交
20 21
    //'Drive_ver',
    //'Drive_custom',
22 23 24 25
    //'client_id',
    'client_secret',
    'domain_path',
    'guestup_path',
Q
qkqpttgf 已提交
26 27
    //'usesharepoint',
    'sharepointname',
28
    'shareurl',
Q
qkqpttgf 已提交
29
    //'sharecookie',
30
    'shareapiurl',
Q
qkqpttgf 已提交
31
    //'siteid',
32 33 34 35 36
    'public_path',
    //'refresh_token',
    //'token_expires',
];

Q
qkqpttgf 已提交
37 38 39 40 41 42 43 44 45 46
$CommonEnv = [
    '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.
Q
qkqpttgf 已提交
47
    'hideFunctionalityFile',
Q
qkqpttgf 已提交
48
    'timezone',
Q
qkqpttgf 已提交
49 50 51 52 53 54
    'passfile',
    'sitename',
    'theme',
];

$ShowedCommonEnv = [
Q
qkqpttgf 已提交
55 56 57 58 59 60 61 62 63
    //'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.
Q
qkqpttgf 已提交
64
    'hideFunctionalityFile',
Q
qkqpttgf 已提交
65
    'timezone',
Q
qkqpttgf 已提交
66 67 68 69 70
    'passfile',
    'sitename',
    'theme',
];

Q
qkqpttgf 已提交
71
$InnerEnv = [
Q
qkqpttgf 已提交
72 73
    'Drive_ver',
    'Drive_custom',
Q
qkqpttgf 已提交
74 75
    'client_id',
    'client_secret',
76
    'diskname',
Q
qkqpttgf 已提交
77
    'domain_path',
78
    'downloadencrypt',
Q
qkqpttgf 已提交
79
    'guestup_path',
Q
qkqpttgf 已提交
80 81 82
    'usesharepoint',
    'sharepointname',
    'siteid',
83
    'shareurl',
Q
qkqpttgf 已提交
84
    //'sharecookie',
85
    'shareapiurl',
Q
qkqpttgf 已提交
86 87 88 89 90
    'public_path',
    'refresh_token',
    'token_expires',
];

Q
qkqpttgf 已提交
91
$ShowedInnerEnv = [
Q
qkqpttgf 已提交
92 93
    //'Drive_ver',
    //'Drive_custom',
Q
qkqpttgf 已提交
94 95
    //'client_id',
    //'client_secret',
96
    'diskname',
Q
qkqpttgf 已提交
97
    'domain_path',
98
    'downloadencrypt',
Q
qkqpttgf 已提交
99
    'guestup_path',
Q
qkqpttgf 已提交
100 101 102
    //'usesharepoint',
    //'sharepointname',
    //'siteid',
103 104 105
    //'shareurl',
    //'sharecookie',
    //'shareapiurl',
Q
qkqpttgf 已提交
106 107 108 109 110
    'public_path',
    //'refresh_token',
    //'token_expires',
];

Q
qkqpttgf 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
$timezones = array( 
    '-12'=>'Pacific/Kwajalein', 
    '-11'=>'Pacific/Samoa', 
    '-10'=>'Pacific/Honolulu', 
    '-9'=>'America/Anchorage', 
    '-8'=>'America/Los_Angeles', 
    '-7'=>'America/Denver', 
    '-6'=>'America/Mexico_City', 
    '-5'=>'America/New_York', 
    '-4'=>'America/Caracas', 
    '-3.5'=>'America/St_Johns', 
    '-3'=>'America/Argentina/Buenos_Aires', 
    '-2'=>'America/Noronha',
    '-1'=>'Atlantic/Azores', 
    '0'=>'UTC', 
    '1'=>'Europe/Paris', 
    '2'=>'Europe/Helsinki', 
    '3'=>'Europe/Moscow', 
    '3.5'=>'Asia/Tehran', 
    '4'=>'Asia/Baku', 
    '4.5'=>'Asia/Kabul', 
    '5'=>'Asia/Karachi', 
    '5.5'=>'Asia/Calcutta', //Asia/Colombo
    '6'=>'Asia/Dhaka',
    '6.5'=>'Asia/Rangoon', 
    '7'=>'Asia/Bangkok', 
    '8'=>'Asia/Shanghai', 
    '9'=>'Asia/Tokyo', 
    '9.5'=>'Australia/Darwin', 
    '10'=>'Pacific/Guam', 
    '11'=>'Asia/Magadan', 
    '12'=>'Asia/Kamchatka'
);

145 146 147 148 149
function main($path)
{
    global $exts;
    global $constStr;

Q
qkqpttgf 已提交
150 151 152 153 154 155 156 157 158 159 160
    if (in_array($_SERVER['firstacceptlanguage'], array_keys($constStr['languages']))) {
        $constStr['language'] = $_SERVER['firstacceptlanguage'];
    } else {
        $prelang = splitfirst($_SERVER['firstacceptlanguage'], '-')[0];
        foreach ( array_keys($constStr['languages']) as $lang) {
            if ($prelang == splitfirst($lang, '-')[0]) {
                $constStr['language'] = $lang;
                break;
            }
        }
    }
Q
qkqpttgf 已提交
161 162 163 164
    if (isset($_COOKIE['language'])&&$_COOKIE['language']!='') $constStr['language'] = $_COOKIE['language'];
    //if (!$constStr['language']) $constStr['language'] = getConfig('language');
    /*echo 'firstacceptlanguage:'.$_SERVER['firstacceptlanguage'].'
    '.'lan:'.$constStr['language'];*/
165 166
    if ($constStr['language']=='') $constStr['language'] = 'en-us';
    $_SERVER['language'] = $constStr['language'];
Q
qkqpttgf 已提交
167 168 169
    $_SERVER['timezone'] = getConfig('timezone');
    if (isset($_COOKIE['timezone'])&&$_COOKIE['timezone']!='') $_SERVER['timezone'] = $_COOKIE['timezone'];
    if ($_SERVER['timezone']=='') $_SERVER['timezone'] = 0;
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    $_SERVER['PHP_SELF'] = path_format($_SERVER['base_path'] . $path);

    if (getConfig('admin')=='') 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);
            } else return adminform();
        } else {
            return output('', 302, [ 'Location' => $url ]);
        }
    }
    if (getConfig('admin')!='')
        if ( (isset($_COOKIE['admin'])&&$_COOKIE['admin']==md5(getConfig('admin'))) || (isset($_POST['password1'])&&$_POST['password1']==getConfig('admin')) ) {
            $_SERVER['admin']=1;
            $_SERVER['needUpdate'] = needUpdate();
        } else {
            $_SERVER['admin']=0;
        }
    if (isset($_GET['setup']))
        if ($_SERVER['admin']) {
            // setup Environments. 设置,对环境变量操作
            return EnvOpt($_SERVER['needUpdate']);
        } else {
            $url = path_format($_SERVER['PHP_SELF'] . '/');
            return output('<script>alert(\''.getconstStr('SetSecretsFirst').'\');</script>', 302, [ 'Location' => $url ]);
        }

    $_SERVER['base_disk_path'] = $_SERVER['base_path'];
    $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('<meta http-equiv="refresh" content="2;URL='.$_SERVER['base_path'].'">Please visit from <a href="'.$_SERVER['base_path'].'">Home Page</a>.', 'Error', 404);
        $path = substr($path, strlen('/'.$_SERVER['disktag']));
        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.'
//';
    $_SERVER['list_path'] = getListpath($_SERVER['HTTP_HOST']);
    if ($_SERVER['list_path']=='') $_SERVER['list_path'] = '/';
    $_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();
    } else {
        if (!($_SERVER['access_token'] = getcache('access_token'))) {
            get_access_token($refresh_token);
        }

        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 .'<br>'. $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);
                }
                $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);
        }

        $files = list_files($path);
        //echo json_encode(array_keys($files['children']), JSON_PRETTY_PRINT);
        if (isset($_GET['random'])&&$_GET['random']!=='') {
            if ($_SERVER['ishidden']<4) {
                $tmp = [];
                foreach (array_keys($files['children']) as $filename) {
                    if (strtolower(splitlast($filename,'.')[1])==strtolower($_GET['random'])) $tmp[$filename] = $files['children'][$filename][$_SERVER['DownurlStrName']];
                }
                $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;
            }
            return message('<a href="'.$_SERVER['base_path'].'">'.getconstStr('Back').getconstStr('Home').'</a><div style="margin:8px;"><pre>' . $files['error']['message'] . '</pre></div><a href="javascript:history.back(-1)">'.getconstStr('Back').'</a>', $files['error']['code'], $files['error']['stat']);
        }
    }
}

function get_access_token($refresh_token)
{
    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");
Q
qkqpttgf 已提交
343 344
            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']);
345 346 347
        }
        error_log('Get access token:'.json_encode($ret, JSON_PRETTY_PRINT));
        savecache('access_token', $_SERVER['access_token']);
Q
qkqpttgf 已提交
348 349 350
        $tmp = [];
        $tmp['shareapiurl'] = $_SERVER['api_url'];
        if (getConfig('shareapiurl')=='') setConfig($tmp);
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    } 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 ]);
    }
}

function list_files($path)
{
    $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);
    }
    return $files;
}

Q
qkqpttgf 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393
function isHideFile($name)
{
    $FunctionalityFile = [
        'head.md',
        'readme.md',
        'favicon.ico',
    ];

    if ($name == getConfig('passfile')) return true;
    if (substr($name,0,1) == '.') return true;
    if (getConfig('hideFunctionalityFile')) if (in_array(strtolower($name), $FunctionalityFile)) return true;
    return false;
}

Q
qkqpttgf 已提交
394 395
function getcache($str)
{
Q
qkqpttgf 已提交
396
    $cache = new \Doctrine\Common\Cache\FilesystemCache(sys_get_temp_dir(), __DIR__.'/Onedrive/'.$_SERVER['disktag']);
Q
qkqpttgf 已提交
397 398 399
    return $cache->fetch($str);
}

Q
qkqpttgf 已提交
400
function savecache($key, $value, $exp = 1800)
Q
qkqpttgf 已提交
401
{
Q
qkqpttgf 已提交
402
    $cache = new \Doctrine\Common\Cache\FilesystemCache(sys_get_temp_dir(), __DIR__.'/Onedrive/'.$_SERVER['disktag']);
Q
qkqpttgf 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    $cache->save($key, $value, $exp);
}

function getconstStr($str)
{
    global $constStr;
    if ($constStr[$str][$constStr['language']]!='') return $constStr[$str][$constStr['language']];
    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';
418 419 420 421 422 423
    if (getConfig('Drive_ver')=='shareurl') {
        $_SERVER['api_url'] = getConfig('shareapiurl');
        $_SERVER['sharecookie'] = getConfig('sharecookie');
        $_SERVER['DownurlStrName'] = '@content.downloadUrl';
        return 0;
    }
Q
qkqpttgf 已提交
424
    if (getConfig('Drive_ver')=='MS') {
Q
qkqpttgf 已提交
425 426
        // MS
        // https://portal.azure.com
Q
qkqpttgf 已提交
427 428 429 430
        //$_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';
Q
qkqpttgf 已提交
431 432 433
        $_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';
Q
qkqpttgf 已提交
434
        if (getConfig('usesharepoint')=='on') $_SERVER['api_url'] = 'https://graph.microsoft.com/v1.0/sites/' . getConfig('siteid') . '/drive/root';
Q
qkqpttgf 已提交
435
    }
Q
qkqpttgf 已提交
436
    if (getConfig('Drive_ver')=='CN') {
Q
qkqpttgf 已提交
437 438 439 440 441 442 443
        // 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';
Q
qkqpttgf 已提交
444
        if (getConfig('usesharepoint')=='on') $_SERVER['api_url'] = 'https://microsoftgraph.chinacloudapi.cn/v1.0/sites/' . getConfig('siteid') . '/drive/root';
Q
qkqpttgf 已提交
445
    }
Q
qkqpttgf 已提交
446 447 448

    if (getConfig('Drive_custom')=='on') {
        // Customer
Q
qkqpttgf 已提交
449
        $_SERVER['client_id'] = getConfig('client_id');
450
        $_SERVER['client_secret'] = getConfig('client_secret');
Q
qkqpttgf 已提交
451 452 453
    }
    $_SERVER['client_secret'] = urlencode($_SERVER['client_secret']);
    $_SERVER['scope'] = urlencode($_SERVER['scope']);
454
    $_SERVER['DownurlStrName'] = '@microsoft.graph.downloadUrl';
Q
qkqpttgf 已提交
455 456
}

Q
qkqpttgf 已提交
457 458
function get_siteid($access_token)
{
Q
qkqpttgf 已提交
459 460
    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');
Q
qkqpttgf 已提交
461 462
    $i=0;
    $response = [];
Q
qkqpttgf 已提交
463 464
    while ($url!=''&&$response['stat']!=200&&$i<4) {
        $response = curl_request($url, false, ['Authorization' => 'Bearer ' . $access_token]);
Q
qkqpttgf 已提交
465
        $i++;
Q
qkqpttgf 已提交
466 467 468 469
    }
    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']);
Q
qkqpttgf 已提交
470 471 472 473
    }
    return json_decode($response['body'],true)['id'];
}

Q
qkqpttgf 已提交
474 475
function getListpath($domain)
{
Q
qkqpttgf 已提交
476 477 478 479 480
    $domain_path1 = getConfig('domain_path');
    $public_path = getConfig('public_path');
    $tmp_path='';
    if ($domain_path1!='') {
        $tmp = explode("|",$domain_path1);
Q
qkqpttgf 已提交
481 482
        foreach ($tmp as $multidomain_paths){
            $pos = strpos($multidomain_paths,":");
Q
qkqpttgf 已提交
483 484 485 486 487
            if ($pos>0) {
                $domain1 = substr($multidomain_paths,0,$pos);
                $tmp_path = path_format(substr($multidomain_paths,$pos+1));
                $domain_path[$domain1] = $tmp_path;
                if ($public_path=='') $public_path = $tmp_path;
Q
qkqpttgf 已提交
488
            //if (substr($multidomain_paths,0,$pos)==$host_name) $private_path=$tmp_path;
Q
qkqpttgf 已提交
489
            }
Q
qkqpttgf 已提交
490
        }
Q
qkqpttgf 已提交
491
    }
Q
qkqpttgf 已提交
492
    if (isset($domain_path[$domain])) return spurlencode($domain_path[$domain],'/');
Q
qkqpttgf 已提交
493
    return spurlencode($public_path,'/');
Q
qkqpttgf 已提交
494 495 496 497 498 499 500 501 502 503 504
}

function path_format($path)
{
    $path = '/' . $path;
    while (strpos($path, '//') !== FALSE) {
        $path = str_replace('//', '/', $path);
    }
    return $path;
}

Q
qkqpttgf 已提交
505
function spurlencode($str,$split='')
Q
qkqpttgf 已提交
506 507 508
{
    $str = str_replace(' ', '%20',$str);
    $tmp='';
Q
qkqpttgf 已提交
509 510
    if ($split!='') {
        $tmparr=explode($split,$str);
Q
qkqpttgf 已提交
511
        for($x=0;$x<count($tmparr);$x++) {
Q
qkqpttgf 已提交
512
            if ($tmparr[$x]!='') $tmp .= $split . urlencode($tmparr[$x]);
Q
qkqpttgf 已提交
513 514 515 516 517 518 519 520
        }
    } else {
        $tmp = urlencode($str);
    }
    $tmp = str_replace('%2520', '%20',$tmp);
    return $tmp;
}

Q
qkqpttgf 已提交
521 522 523 524
function equal_replace($str, $add = false)
{
    if ($add) {
        while(strlen($str)%4) $str .= '=';
Q
fix bug  
qkqpttgf 已提交
525
        $str = urldecode(base64_decode($str));
Q
qkqpttgf 已提交
526
    } else {
Q
fix bug  
qkqpttgf 已提交
527
        $str = base64_encode(urlencode($str));
Q
qkqpttgf 已提交
528 529 530 531 532
        while(substr($str,-1)=='=') $str=substr($str,0,-1);
    }
    return $str;
}

Q
qkqpttgf 已提交
533 534
function is_guestup_path($path)
{
Q
qkqpttgf 已提交
535 536
    $a1 = path_format(path_format(urldecode($_SERVER['list_path'].path_format($path))).'/');
    $a2 = path_format(path_format(getConfig('guestup_path')).'/');
Q
qkqpttgf 已提交
537
    if (getConfig('guestup_path')!=''&&strtolower($a1)==strtolower($a2)) return 1;
Q
qkqpttgf 已提交
538 539 540
    return 0;
}

Q
qkqpttgf 已提交
541 542 543 544 545
function array_value_isnot_null($arr)
{
    return $arr!=='';
}

Q
qkqpttgf 已提交
546
function curl_request($url, $data = false, $headers = [], $returnheader = 0)
Q
qkqpttgf 已提交
547 548
{
    if (!isset($headers['Accept'])) $headers['Accept'] = '*/*';
Q
qkqpttgf 已提交
549
    //if (!isset($headers['Referer'])) $headers['Referer'] = $url;
Q
qkqpttgf 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563
    if (!isset($headers['Content-Type'])) $headers['Content-Type'] = 'application/x-www-form-urlencoded';
    $sendHeaders = array();
    foreach ($headers as $headerName => $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_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
Q
qkqpttgf 已提交
564
    curl_setopt($ch, CURLOPT_HEADER, $returnheader);
Q
qkqpttgf 已提交
565 566 567
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders);
Q
qkqpttgf 已提交
568 569 570 571 572 573 574 575 576 577 578
    //$response['body'] = curl_exec($ch);
    if ($returnheader) {
        list($returnhead, $response['body']) = explode("\r\n\r\n", curl_exec($ch));
        foreach (explode("\r\n", $returnhead) as $head) {
            $tmp = explode(': ', $head);
            $heads[$tmp[0]] = $tmp[1];
        }
        $response['returnhead'] = $heads;
    } else {
        $response['body'] = curl_exec($ch);
    }
Q
qkqpttgf 已提交
579 580 581 582 583 584 585 586 587 588
    $response['stat'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $response;
}

function clearbehindvalue($path,$page1,$maxpage,$pageinfocache)
{
    for ($page=$page1+1;$page<$maxpage;$page++) {
        $pageinfocache['nextlink_' . $path . '_page_' . $page] = '';
    }
Q
qkqpttgf 已提交
589
    $pageinfocache = array_filter($pageinfocache, 'array_value_isnot_null');
Q
qkqpttgf 已提交
590 591 592 593 594 595 596 597
    return $pageinfocache;
}

function comppass($pass)
{
    if ($_POST['password1'] !== '') if (md5($_POST['password1']) === $pass ) {
        date_default_timezone_set('UTC');
        $_SERVER['Set-Cookie'] = 'password='.$pass.'; expires='.date(DATE_COOKIE,strtotime('+1hour'));
Q
qkqpttgf 已提交
598
        date_default_timezone_set(get_timezone($_SERVER['timezone']));
Q
qkqpttgf 已提交
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
        return 2;
    }
    if ($_COOKIE['password'] !== '') if ($_COOKIE['password'] === $pass ) return 3;
    return 4;
}

function encode_str_replace($str)
{
    $str = str_replace('&','&amp;',$str);
    $str = str_replace('+','%2B',$str);
    $str = str_replace('#','%23',$str);
    return $str;
}

function gethiddenpass($path,$passfile)
{
Q
qkqpttgf 已提交
615
    $path1 = path_format($_SERVER['list_path'] . path_format($path));
Q
qkqpttgf 已提交
616
    if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1);
Q
qkqpttgf 已提交
617
    $password=getcache('path_' . $path1 . '/?password');
Q
qkqpttgf 已提交
618
    if ($password=='') {
Q
qkqpttgf 已提交
619 620 621
        $ispassfile = fetch_files(path_format($path . '/' . urlencode($passfile)));
        //echo $path . '<pre>' . json_encode($ispassfile, JSON_PRETTY_PRINT) . '</pre>';
        if (isset($ispassfile['file'])) {
622
            $arr = curl_request($ispassfile[$_SERVER['DownurlStrName']]);
Q
qkqpttgf 已提交
623 624 625 626 627 628 629 630 631 632
            if ($arr['stat']==200) {
                $passwordf=explode("\n",$arr['body']);
                $password=$passwordf[0];
                if ($password!='') $password=md5($password);
                savecache('path_' . $path1 . '/?password', $password);
                return $password;
            } else {
                //return md5('DefaultP@sswordWhenNetworkError');
                return md5( md5(time()).rand(1000,9999) );
            }
Q
qkqpttgf 已提交
633
        } else {
Q
qkqpttgf 已提交
634 635 636 637 638 639 640
            savecache('path_' . $path1 . '/?password', 'null');
            if ($path !== '' ) {
                $path = substr($path,0,strrpos($path,'/'));
                return gethiddenpass($path,$passfile);
            } else {
                return '';
            }
Q
qkqpttgf 已提交
641
        }
Q
qkqpttgf 已提交
642 643 644 645 646 647 648 649 650
    } elseif ($password==='null') {
        if ($path !== '' ) {
            $path = substr($path,0,strrpos($path,'/'));
            return gethiddenpass($path,$passfile);
        } else {
            return '';
        }
    } else return $password;
    // return md5('DefaultP@sswordWhenNetworkError');
Q
qkqpttgf 已提交
651 652 653 654
}

function get_timezone($timezone = '8')
{
Q
qkqpttgf 已提交
655
    global $timezones;
Q
qkqpttgf 已提交
656 657 658 659 660 661
    if ($timezone=='') $timezone = '8';
    return $timezones[$timezone];
}

function message($message, $title = 'Message', $statusCode = 200)
{
Q
qkqpttgf 已提交
662
    return output('
Q
qkqpttgf 已提交
663
<html lang="' . $_SERVER['language'] . '">
Q
qkqpttgf 已提交
664 665
<html>
    <meta charset=utf-8>
Q
qkqpttgf 已提交
666
    <meta name=viewport content="width=device-width,initial-scale=1">
Q
qkqpttgf 已提交
667 668 669
    <body>
        <h1>' . $title . '</h1>
        <p>
Q
qkqpttgf 已提交
670

Q
qkqpttgf 已提交
671
' . $message . '
Q
qkqpttgf 已提交
672

Q
qkqpttgf 已提交
673 674
        </p>
    </body>
Q
qkqpttgf 已提交
675 676
</html>
', $statusCode);
Q
qkqpttgf 已提交
677 678 679 680
}

function needUpdate()
{
681
    $current_ver = file_get_contents(__DIR__ . '/version');
Q
qkqpttgf 已提交
682 683 684 685 686 687 688 689 690 691
    $current_ver = substr($current_ver, strpos($current_ver, '.')+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');
    $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;
        return 1;
Q
qkqpttgf 已提交
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    }
    return 0;
}

function output($body, $statusCode = 200, $headers = ['Content-Type' => 'text/html'], $isBase64Encoded = false)
{
    return [
        'isBase64Encoded' => $isBase64Encoded,
        'statusCode' => $statusCode,
        'headers' => $headers,
        'body' => $body
    ];
}

function passhidden($path)
{
    $path = str_replace('+','%2B',$path);
    $path = str_replace('&amp;','&', path_format(urldecode($path)));
    if (getConfig('passfile') != '') {
Q
qkqpttgf 已提交
711
        $path = spurlencode($path,'/');
Q
qkqpttgf 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        if (substr($path,-1)=='/') $path=substr($path,0,-1);
        $hiddenpass=gethiddenpass($path,getConfig('passfile'));
        if ($hiddenpass != '') {
            return comppass($hiddenpass);
        } else {
            return 1;
        }
    } else {
        return 0;
    }
    return 4;
}

function size_format($byte)
{
    $i = 0;
    while (abs($byte) >= 1024) {
        $byte = $byte / 1024;
        $i++;
        if ($i == 3) break;
    }
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $ret = round($byte, 2);
    return ($ret . ' ' . $units[$i]);
}

function time_format($ISO)
{
    $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 = '/')
{
    $path1 = path_format($path);
    $path = path_format($_SERVER['list_path'] . path_format($path));
Q
qkqpttgf 已提交
750 751
    if ($path!='/'&&substr($path,-1)=='/') $path=substr($path,0,-1);
    $thumb_url = getcache('thumb_'.$path);
Q
qkqpttgf 已提交
752
    if ($thumb_url!='') return output($thumb_url);
Q
qkqpttgf 已提交
753 754 755 756 757 758 759
    $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);
Q
qkqpttgf 已提交
760
    if (isset($files['url'])) {
Q
qkqpttgf 已提交
761
        savecache('thumb_'.$path, $files['url']);
Q
qkqpttgf 已提交
762 763
        return output($files['url']);
    }
Q
qkqpttgf 已提交
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    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) {
780
            $getoldupinfo_j = curl_request($getoldupinfo[$_SERVER['DownurlStrName']]);
Q
qkqpttgf 已提交
781 782
            $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']);
Q
qkqpttgf 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
        }
        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 = '<html><head><title>'.getconstStr('AdminLogin').'</title><meta charset=utf-8></head>';
    if ($name!=''&&$pass!='') {
        $html .= '<body>'.getconstStr('LoginSuccess').'</body></html>';
        $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 .= '
    <body>
	<div>
	  <center><h4>'.getconstStr('InputPassword').'</h4>
	  <form action="" method="post">
		  <div>
		    <input name="password1" type="password"/>
		    <input type="submit" value="'.getconstStr('Login').'">
          </div>
	  </form>
      </center>
	</div>
';
    $html .= '</body></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);
    $tmparr['statusCode'] = 0;
Q
qkqpttgf 已提交
832
    if (isset($_GET['rename_newname'])&&$_GET['rename_newname']!=$_GET['rename_oldname'] && $_GET['rename_newname']!='') {
Q
qkqpttgf 已提交
833 834 835 836 837 838 839 840 841
        // 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']);
    }
Q
qkqpttgf 已提交
842
    if (isset($_GET['delete_name'])) {
Q
qkqpttgf 已提交
843 844 845 846 847 848 849 850
        // 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']);
    }
Q
qkqpttgf 已提交
851
    if (isset($_GET['operate_action'])&&$_GET['operate_action']==getconstStr('encrypt')) {
Q
qkqpttgf 已提交
852 853 854 855 856 857 858
        // 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']);
Q
qkqpttgf 已提交
859
        $path1 = path_format($path1 . '/' . $foldername );
Q
qkqpttgf 已提交
860
        if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1);
Q
qkqpttgf 已提交
861
        savecache('path_' . $path1 . '/?password', '', 1);
Q
qkqpttgf 已提交
862 863
        return output($result['body'], $result['stat']);
    }
Q
qkqpttgf 已提交
864
    if (isset($_GET['move_folder'])) {
Q
qkqpttgf 已提交
865 866 867 868 869 870 871 872 873 874 875 876 877
        // move 移动
        $moveable = 1;
        if ($path == '/' && $_GET['move_folder'] == '/../') $moveable=0;
        if ($_GET['move_folder'] == $_GET['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'] . '/' );
Q
qkqpttgf 已提交
878
            if ($path2!='/'&&substr($path2,-1)=='/') $path2=substr($path2,0,-1);
Q
qkqpttgf 已提交
879 880 881
            savecache('path_' . $path2, json_decode('{}',true), 1);
            return output($result['body'], $result['stat']);
        } else {
Q
qkqpttgf 已提交
882
            return output('{"error":"'.getconstStr('CannotMove').'"}', 403);
Q
qkqpttgf 已提交
883 884
        }
    }
Q
qkqpttgf 已提交
885
    if (isset($_GET['copy_name'])) {
Q
qkqpttgf 已提交
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
        // 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);
Q
qkqpttgf 已提交
919
        return output($result['body'], $result['stat']);
Q
qkqpttgf 已提交
920
    }
Q
qkqpttgf 已提交
921
    if (isset($_POST['editfile'])) {
Q
qkqpttgf 已提交
922 923 924 925 926 927 928 929 930 931
        // 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);
Q
qkqpttgf 已提交
932
        if (isset($resultarry['error'])) return message($resultarry['error']['message']. '<hr><a href="javascript:history.back(-1)">'.getconstStr('Back').'</a>','Error',403);
Q
qkqpttgf 已提交
933
    }
Q
qkqpttgf 已提交
934
    if (isset($_GET['create_name'])) {
Q
qkqpttgf 已提交
935 936 937 938 939 940 941 942 943 944 945 946 947
        // 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']);
    }
Q
qkqpttgf 已提交
948
    if (isset($_GET['RefreshCache'])) {
Q
qkqpttgf 已提交
949
        $path1 = path_format($_SERVER['list_path'] . path_format($path));
Q
qkqpttgf 已提交
950
        if ($path1!='/'&&substr($path1,-1)=='/') $path1=substr($path1,0,-1);
Q
qkqpttgf 已提交
951
        savecache('path_' . $path1 . '/?password', '', 1);
952
        return message('<meta http-equiv="refresh" content="2;URL=./">', getconstStr('RefreshCache'), 302);
Q
qkqpttgf 已提交
953 954 955 956
    }
    return $tmparr;
}

Q
qkqpttgf 已提交
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
function splitfirst($str, $split)
{
    $len = strlen($split);
    $pos = strpos($str, $split);
    if ($pos===false) {
        $tmp[0] = $str;
        $tmp[1] = '';
    } elseif ($pos>0) {
        $tmp[0] = substr($str, 0, $pos);
        $tmp[1] = substr($str, $pos+$len);
    } else {
        $tmp[0] = '';
        $tmp[1] = substr($str, $len);
    }
    return $tmp;
}

Q
qkqpttgf 已提交
974 975
function splitlast($str, $split)
{
Q
qkqpttgf 已提交
976
    $len = strlen($split);
Q
qkqpttgf 已提交
977 978 979 980 981 982
    $pos = strrpos($str, $split);
    if ($pos===false) {
        $tmp[0] = $str;
        $tmp[1] = '';
    } elseif ($pos>0) {
        $tmp[0] = substr($str, 0, $pos);
Q
qkqpttgf 已提交
983
        $tmp[1] = substr($str, $pos+$len);
Q
qkqpttgf 已提交
984 985
    } else {
        $tmp[0] = '';
Q
qkqpttgf 已提交
986
        $tmp[1] = substr($str, $len);
Q
qkqpttgf 已提交
987 988 989 990
    }
    return $tmp;
}

Q
qkqpttgf 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
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'] = '*/*';
Q
qkqpttgf 已提交
1032
    //if (!isset($headers['Referer'])) $headers['Referer'] = $url;*
Q
qkqpttgf 已提交
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    $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);
Q
qkqpttgf 已提交
1047
    //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
Q
qkqpttgf 已提交
1048 1049 1050
    curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders);
    $response['body'] = curl_exec($ch);
    $response['stat'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
Q
qkqpttgf 已提交
1051
    //$response['Location'] = curl_getinfo($ch);
Q
qkqpttgf 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060
    curl_close($ch);
    error_log($response['stat'].'
'.$response['body'].'
');
    return $response;
}

function fetch_files($path = '/')
{
1061
    global $exts;
Q
qkqpttgf 已提交
1062 1063
    $path1 = path_format($path);
    $path = path_format($_SERVER['list_path'] . path_format($path));
Q
qkqpttgf 已提交
1064
    if ($path!='/'&&substr($path,-1)=='/') $path=substr($path,0,-1);
Q
qkqpttgf 已提交
1065 1066 1067 1068
    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
Q
qkqpttgf 已提交
1069 1070
        $pos = splitlast($path, '/');
        $parentpath = $pos[0];
Q
qkqpttgf 已提交
1071
        if ($parentpath=='') $parentpath = '/';
Q
qkqpttgf 已提交
1072
        $filename = $pos[1];
Q
qkqpttgf 已提交
1073
        if ($parentfiles = getcache('path_' . $parentpath)) {
1074
            if (isset($parentfiles['children'][$filename][$_SERVER['DownurlStrName']])) {
Q
qkqpttgf 已提交
1075 1076
                if (in_array(splitlast($filename,'.')[1], $exts['txt'])) {
                    if (!(isset($parentfiles['children'][$filename]['content'])&&$parentfiles['children'][$filename]['content']['stat']==200)) {
1077
                        $content1 = curl_request($parentfiles['children'][$filename][$_SERVER['DownurlStrName']]);
Q
qkqpttgf 已提交
1078
                        $parentfiles['children'][$filename]['content'] = $content1;
Q
qkqpttgf 已提交
1079
                        savecache('path_' . $parentpath, $parentfiles);
1080 1081
                    }
                }
Q
qkqpttgf 已提交
1082
                return $parentfiles['children'][$filename];
1083
            }
Q
qkqpttgf 已提交
1084
        }
Q
qkqpttgf 已提交
1085

Q
qkqpttgf 已提交
1086 1087 1088 1089 1090
        $url = $_SERVER['api_url'];
        if ($path !== '/') {
            $url .= ':' . $path;
            if (substr($url,-1)=='/') $url=substr($url,0,-1);
        }
1091
        $url .= '?expand=children(select=name,size,file,folder,parentReference,lastModifiedDateTime,'.$_SERVER['DownurlStrName'].')';
1092 1093
        $retry = 0;
        $arr = [];
Q
qkqpttgf 已提交
1094
        while ($retry<3&&!$arr['stat']) {
1095
            $arr = curl_request($url, false, ['Authorization' => 'Bearer ' . $_SERVER['access_token']],1);
Q
qkqpttgf 已提交
1096 1097
            $retry++;
        }
Q
qkqpttgf 已提交
1098 1099
        if ($arr['stat']<500) {
            $files = json_decode($arr['body'], true);
1100
            //echo $path . '<br><pre>' . json_encode($arr, JSON_PRETTY_PRINT) . '</pre>';
Q
qkqpttgf 已提交
1101 1102
            if (isset($files['folder'])) {
                if ($files['folder']['childCount']>200) {
Q
qkqpttgf 已提交
1103
                    // files num > 200 , then get nextlink
Q
qkqpttgf 已提交
1104
                    $page = $_POST['pagenum']==''?1:$_POST['pagenum'];
Q
qkqpttgf 已提交
1105 1106
                    if ($page>1) $files=fetch_files_children($files, $path1, $page);
                    $files['children'] = children_name($files['children']);
Q
qkqpttgf 已提交
1107 1108
                } else {
                // files num < 200 , then cache
Q
qkqpttgf 已提交
1109 1110 1111
                    //if (isset($files['children'])) {
                        $files['children'] = children_name($files['children']);
                    //}
Q
qkqpttgf 已提交
1112 1113 1114 1115 1116 1117 1118
                    savecache('path_' . $path, $files);
                }
            }
            if (isset($files['error'])) {
                $files['error']['stat'] = $arr['stat'];
            }
        } else {
Q
qkqpttgf 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
            //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));
Q
qkqpttgf 已提交
1130 1131
        }
    }
1132

Q
qkqpttgf 已提交
1133 1134 1135
    return $files;
}

Q
qkqpttgf 已提交
1136 1137 1138 1139
function children_name($children)
{
    $tmp = [];
    foreach ($children as $file) {
1140
        $tmp[strtolower($file['name'])] = $file;
Q
qkqpttgf 已提交
1141 1142 1143 1144
    }
    return $tmp;
}

Q
qkqpttgf 已提交
1145 1146
function fetch_files_children($files, $path, $page)
{
Q
qkqpttgf 已提交
1147 1148
    $path1 = path_format($path);
    $path = path_format($_SERVER['list_path'] . path_format($path));
Q
qkqpttgf 已提交
1149
    if ($path!='/'&&substr($path,-1)=='/') $path=substr($path,0,-1);
Q
qkqpttgf 已提交
1150 1151 1152 1153 1154 1155
    $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) {
1156
            $pageinfo = curl_request($cachefile[$_SERVER['DownurlStrName']])['body'];
Q
qkqpttgf 已提交
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
            $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);
1173
                        $url .= ':/children?$select=name,size,file,folder,parentReference,lastModifiedDateTime,'.$_SERVER['DownurlStrName'];
Q
qkqpttgf 已提交
1174
                    } else {
1175
                        $url .= '/children?$select=name,size,file,folder,parentReference,lastModifiedDateTime,'.$_SERVER['DownurlStrName'];
Q
qkqpttgf 已提交
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
                    }
                    $children = json_decode(curl_request($url, false, ['Authorization' => 'Bearer ' . $_SERVER['access_token']])['body'], true);
                    // echo $url . '<br><pre>' . json_encode($children, JSON_PRETTY_PRINT) . '</pre>';
                    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 . '<br><pre>' . json_encode($children, JSON_PRETTY_PRINT) . '</pre>';
                    $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 . '<br><pre>' . json_encode($children, JSON_PRETTY_PRINT) . '</pre>';
                $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;
}

Q
qkqpttgf 已提交
1249
function render_list($path = '', $files = '')
Q
qkqpttgf 已提交
1250 1251 1252 1253
{
    global $exts;
    global $constStr;

1254 1255 1256 1257
    if (isset($files['children']['index.html']) && !$_SERVER['admin']) {
        $htmlcontent = fetch_files(spurlencode(path_format($path . '/index.html'),'/'))['content'];
        return output($htmlcontent['body'], $htmlcontent['stat']);
    }
Q
qkqpttgf 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266
    $path = str_replace('%20','%2520',$path);
    $path = str_replace('+','%2B',$path);
    $path = str_replace('&','&amp;',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('&','&amp;', $files['name']);
Q
qkqpttgf 已提交
1267 1268 1269 1270 1271 1272 1273
            $n_path = $pretitle;
            $tmp = splitlast(splitlast($path,'/')[0],'/');
            if ($tmp[1]=='') {
                $p_path = $tmp[0];
            } else {
                $p_path = $tmp[1];
            }
Q
qkqpttgf 已提交
1274
        } else {
Q
qkqpttgf 已提交
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
            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];
                }
            }
Q
qkqpttgf 已提交
1289 1290 1291 1292 1293 1294 1295 1296 1297
        }
    } else {
      $pretitle = getconstStr('Home');
      $n_path=$pretitle;
    }
    $n_path=str_replace('&amp;','&',$n_path);
    $p_path=str_replace('&amp;','&',$p_path);
    $pretitle = str_replace('%23','#',$pretitle);
    $statusCode=200;
Q
qkqpttgf 已提交
1298
    date_default_timezone_set(get_timezone($_SERVER['timezone']));
Q
qkqpttgf 已提交
1299 1300 1301 1302
    @ob_start();

    $theme = getConfig('theme');
    if ( $theme=='' || !file_exists('theme/'.$theme) ) $theme = 'classic.php';
1303
    include 'theme/'.$theme;
Q
qkqpttgf 已提交
1304 1305

    $html = '<!--
Q
qkqpttgf 已提交
1306
    Github : https://github.com/qkqpttgf/OneManager-php
Q
qkqpttgf 已提交
1307
-->' . ob_get_clean();
1308
    //if (isset($htmlpage['statusCode'])) return $htmlpage;
Q
qkqpttgf 已提交
1309
    if (isset($_SERVER['Set-Cookie'])) return output($html, $statusCode, [ 'Set-Cookie' => $_SERVER['Set-Cookie'], 'Content-Type' => 'text/html' ]);
Q
qkqpttgf 已提交
1310 1311
    return output($html,$statusCode);
}
1312 1313 1314 1315 1316

function get_refresh_token()
{
    global $constStr;
    global $CommonEnv;
Q
qkqpttgf 已提交
1317
    $envs = '';
1318 1319
    foreach ($CommonEnv as $env) $envs .= '\'' . $env . '\', ';
    $url = path_format($_SERVER['PHP_SELF'] . '/');
Q
qkqpttgf 已提交
1320
    if (isset($_GET['authorization_code']) && isset($_GET['code'])) {
1321 1322 1323 1324 1325
        $_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'])) {
Q
qkqpttgf 已提交
1326
            $refresh_token = $ret['refresh_token'];
1327 1328 1329
            $str = '
        refresh_token :<br>';
            $str .= '
Q
qkqpttgf 已提交
1330
        <textarea readonly style="width: 95%">' . $refresh_token . '</textarea><br><br>
1331 1332 1333 1334 1335 1336 1337 1338 1339
        '.getconstStr('SavingToken').'
        <script>
            var texta=document.getElementsByTagName(\'textarea\');
            for(i=0;i<texta.length;i++) {
                texta[i].style.height = texta[i].scrollHeight + \'px\';
            }
            document.cookie=\'language=; path=/\';
            document.cookie=\'disktag=; path=/\';
        </script>';
Q
qkqpttgf 已提交
1340 1341 1342 1343
            $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']);
1344 1345 1346 1347 1348 1349 1350 1351 1352
            savecache('access_token', $ret['access_token'], $ret['expires_in'] - 60);
            //WaitSCFStat();
            $str .= '
            <meta http-equiv="refresh" content="5;URL=' . $url . '">';
            return message($str, getconstStr('WaitJumpIndex'));
        }
        return message('<pre>' . json_encode(json_decode($tmp['body']), JSON_PRETTY_PRINT) . '</pre>', $tmp['stat']);
        //return message('<pre>' . json_encode($ret, JSON_PRETTY_PRINT) . '</pre>', 500);
    }
Q
qkqpttgf 已提交
1353
    if (isset($_GET['install1'])) {
1354 1355
        $_SERVER['disktag'] = $_COOKIE['disktag'];
        config_oauth();
Q
qkqpttgf 已提交
1356
        if (getConfig('Drive_ver')=='MS' || getConfig('Drive_ver')=='CN') {
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
            return message('
    <a href="" id="a1">'.getconstStr('JumptoOffice').'</a>
    <script>
        url=location.protocol + "//" + location.host + "'.$url.'";
        url="'. $_SERVER['oauth_url'] .'authorize?scope='. $_SERVER['scope'] .'&response_type=code&client_id='. $_SERVER['client_id'] .'&redirect_uri='. $_SERVER['redirect_uri'] . '&state=' .'"+encodeURIComponent(url);
        document.getElementById(\'a1\').href=url;
        //window.open(url,"_blank");
        location.href = url;
    </script>
    ', getconstStr('Wait').' 1s', 201);
        } else {
            return message('something error, try after a few seconds.', 'retry', 201);
        }
    }
Q
qkqpttgf 已提交
1371
    if (isset($_GET['install0'])) {
1372
        if ($_POST['disktag_add']!='') {
1373 1374 1375 1376 1377 1378
            if (in_array($_COOKIE['disktag'], $CommonEnv)) {
                return message('Do not input ' . $envs . '<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button><script>document.cookie=\'disktag=; path=/\';</script>', 'Error', 201);
            }
            $_SERVER['disktag'] = $_COOKIE['disktag'];
            $tmp['disktag_add'] = $_POST['disktag_add'];
            $tmp['diskname'] = $_POST['diskname'];
Q
qkqpttgf 已提交
1379
            $tmp['Drive_ver'] = $_POST['Drive_ver'];
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
            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'];
                }
Q
qkqpttgf 已提交
1393
            }
1394 1395 1396 1397
            $response = setConfigResponse( setConfig($tmp, $_COOKIE['disktag']) );
            if (api_error($response)) {
                $html = api_error_msg($response);
                $title = 'Error';
Q
qkqpttgf 已提交
1398 1399 1400
            } else {
                $title = getconstStr('MayinEnv');
                $html = getconstStr('Wait') . ' 3s<meta http-equiv="refresh" content="3;URL=' . $url . '?AddDisk&install1">';
1401
                if ($_POST['Drive_ver']=='shareurl') $html = getconstStr('Wait') . ' 3s<meta http-equiv="refresh" content="3;URL=' . $url . '">';
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
            }
            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 = '
Q
qkqpttgf 已提交
1414
<div>
1415
    <form action="?AddDisk&install0" method="post" onsubmit="return notnull(this);">
Q
qkqpttgf 已提交
1416
        '.getconstStr('OnedriveDiskTag').': ('.getConfig('disktag').')<input type="text" name="disktag_add" placeholder="' . getconstStr('EnvironmentsDescription')['disktag'] . '" style="width:100%"><br>
1417
        '.getconstStr('OnedriveDiskName').':<input type="text" name="diskname" placeholder="' . getconstStr('EnvironmentsDescription')['diskname'] . '" style="width:100%"><br>
Q
qkqpttgf 已提交
1418 1419
        <br>
        <div>
1420 1421 1422
            <label><input type="radio" name="Drive_ver" value="MS" checked onclick="document.getElementById(\'morecustom\').style.display=\'\';document.getElementById(\'inputshareurl\').style.display=\'none\';">MS: '.getconstStr('DriveVerMS').'</label><br>
            <label><input type="radio" name="Drive_ver" value="CN" onclick="document.getElementById(\'morecustom\').style.display=\'\';document.getElementById(\'inputshareurl\').style.display=\'none\';">CN: '.getconstStr('DriveVerCN').'</label><br>
            <label><input type="radio" name="Drive_ver" value="shareurl" onclick="document.getElementById(\'inputshareurl\').style.display=\'\';document.getElementById(\'morecustom\').style.display=\'none\';">shareurl: '.getconstStr('DriveVerShareurl').'</label><br>
Q
qkqpttgf 已提交
1423 1424
        </div>
        <br>
1425
        <div id="inputshareurl" style="display:none;margin:10px 35px">
Q
qkqpttgf 已提交
1426
            '.getconstStr('UseShareLink').'
1427 1428 1429 1430
            <input type="text" name="shareurl" style="width:100%" placeholder="https://xxxx.sharepoint.com/:f:/g/personal/xxxxxxxx/mmmmmmmmm?e=XXXX"><br>
        </div>
        <div id="morecustom">
            <label><input type="checkbox" name="Drive_custom" onclick="document.getElementById(\'secret\').style.display=(this.checked?\'\':\'none\');">'.getconstStr('CustomIdSecret').'</label><br>
Q
qkqpttgf 已提交
1431
            <div id="secret" style="display:none;margin:10px 35px">
1432 1433 1434 1435
                <a href="'.$app_url.'" target="_blank">'.getconstStr('GetSecretIDandKEY').'</a><br>
                client_secret:<input type="text" name="client_secret"><br>
                client_id:<input type="text" name="client_id" placeholder="12345678-90ab-cdef-ghij-klmnopqrstuv"><br>
            </div>
Q
qkqpttgf 已提交
1436
            <label><input type="checkbox" name="usesharepoint" onclick="document.getElementById(\'sharepoint\').style.display=(this.checked?\'\':\'none\');">'.getconstStr('UseSharepointInstead').'</label><br>
Q
qkqpttgf 已提交
1437 1438 1439 1440 1441 1442
            <div id="sharepoint" style="display:none;margin:10px 35px">
                '.getconstStr('GetSharepointName').'<br>
                <input type="text" name="sharepointname" placeholder="'.getconstStr('InputSharepointName').'"><br>
            </div>
        </div>
        <br>
1443 1444
        <input type="submit" value="'.getconstStr('Submit').'">
    </form>
Q
qkqpttgf 已提交
1445
</div>
1446 1447 1448 1449
    <script>
        function notnull(t)
        {
            if (t.disktag_add.value==\'\') {
Q
qkqpttgf 已提交
1450
                alert(\''.getconstStr('OnedriveDiskTag').'\');
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
                return false;
            }
            envs = [' . $envs . '];
            if (envs.indexOf(t.disktag_add.value)>-1) {
                alert("Do not input ' . $envs . '");
                return false;
            }
            var reg = /^[a-zA-Z]([-_a-zA-Z0-9]{1,20})$/;
            if (!reg.test(t.disktag_add.value)) {
                alert(\''.getconstStr('TagFormatAlert').'\');
                return false;
            }
1463 1464 1465
            if (t.Drive_ver.value==\'shareurl\') {
                if (t.shareurl.value==\'\') {
                    alert(\'shareurl\');
Q
qkqpttgf 已提交
1466 1467
                    return false;
                }
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
            } else {
                if (t.Drive_custom.checked==true) {
                    if (t.client_secret.value==\'\'||t.client_id.value==\'\') {
                        alert(\'client_id & client_secret\');
                        return false;
                    }
                }
                if (t.usesharepoint.checked==true) {
                    if (t.sharepointname.value==\'\') {
                        alert(\''.getconstStr('InputSharepointName').'\');
                        return false;
                    }
Q
qkqpttgf 已提交
1480 1481
                }
            }
1482 1483 1484 1485
            document.cookie=\'disktag=\'+t.disktag_add.value+\'; path=/\';
            return true;
        }
    </script>';
1486
    $title = 'Bind Disk';
1487 1488 1489 1490 1491 1492 1493 1494
    return message($html, $title, 201);
}

function EnvOpt($needUpdate = 0)
{
    global $constStr;
    global $ShowedCommonEnv;
    global $ShowedInnerEnv;
Q
qkqpttgf 已提交
1495
    global $timezones;
1496 1497 1498
    asort($ShowedCommonEnv);
    asort($ShowedInnerEnv);
    $html = '<title>OneManager '.getconstStr('Setup').'</title>';
Q
qkqpttgf 已提交
1499
    if (isset($_POST['updateProgram'])&&$_POST['updateProgram']==getconstStr('updateProgram')) {
1500
        $response = OnekeyUpate($_POST['auth'], $_POST['project'], $_POST['branch']);
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
        if (api_error($response)) {
            $html = api_error_msg($response);
            $title = 'Error';
        } else {
            //WaitSCFStat();
            $html .= getconstStr('UpdateSuccess') . '<br>
<button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>';
            $title = getconstStr('Setup');
        }
        return message($html, $title);
    }
Q
qkqpttgf 已提交
1512
    if (isset($_POST['submit1'])) {
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
        $_SERVER['disk_oprating'] = '';
        foreach ($_POST as $k => $v) {
            if (in_array($k, $ShowedCommonEnv)||in_array($k, $ShowedInnerEnv)||$k=='disktag_del' || $k=='disktag_add') {
                $tmp[$k] = $v;
            }
            if ($k == 'disk') $_SERVER['disk_oprating'] = $v;
        }
        /*if ($tmp['domain_path']!='') {
            $tmp1 = explode("|",$tmp['domain_path']);
            $tmparr = [];
            foreach ($tmp1 as $multidomain_paths){
                $pos = strpos($multidomain_paths,":");
                if ($pos>0) $tmparr[substr($multidomain_paths, 0, $pos)] = path_format(substr($multidomain_paths, $pos+1));
            }
            $tmp['domain_path'] = $tmparr;
        }*/
        $response = setConfigResponse( setConfig($tmp, $_SERVER['disk_oprating']) );
        if (api_error($response)) {
                $html = api_error_msg($response);
                $title = 'Error';
            } else {
                //WaitSCFStat();
                //sleep(3);
Q
qkqpttgf 已提交
1536
            $html .= getconstStr('Success') . '!<br>
1537 1538 1539 1540 1541
<button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>';
            $title = getconstStr('Setup');
        }
        return message($html, $title);
    }
Q
qkqpttgf 已提交
1542
    if (isset($_GET['preview'])) {
1543 1544 1545 1546 1547 1548 1549
        $preurl = $_SERVER['PHP_SELF'] . '?preview';
    } else {
        $preurl = path_format($_SERVER['PHP_SELF'] . '/');
    }
    $html .= '
<a href="'.$preurl.'">'.getconstStr('Back').'</a>&nbsp;&nbsp;&nbsp;<a href="'.$_SERVER['base_path'].'">'.getconstStr('Back').getconstStr('Home').'</a><br>
<a href="https://github.com/qkqpttgf/OneManager-php">Github</a><br>';
1550

1551 1552 1553 1554 1555 1556 1557
    $html .= '
<table border=1 width=100%>
    <form name="common" action="" method="post">
        <tr>
            <td colspan="2">'.getconstStr('PlatformConfig').'</td>
        </tr>';
    foreach ($ShowedCommonEnv as $key) {
Q
qkqpttgf 已提交
1558
        if ($key=='timezone') {
1559 1560 1561 1562 1563
            $html .= '
        <tr>
            <td><label>' . $key . '</label></td>
            <td width=100%>
                <select name="' . $key .'">';
Q
qkqpttgf 已提交
1564
            foreach (array_keys($timezones) as $zone) {
1565
                $html .= '
Q
qkqpttgf 已提交
1566
                    <option value="'.$zone.'" '.($zone==getConfig($key)?'selected="selected"':'').'>'.$zone.'</option>';
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
            }
            $html .= '
                </select>
            </td>
        </tr>';
        } elseif ($key=='theme') {
            $theme_arr = scandir('theme');
            $html .= '
        <tr>
            <td><label>' . $key . '</label></td>
            <td width=100%>
                <select name="' . $key .'">
1579
                    <option value=""></option>';
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
            foreach ($theme_arr as $v1) {
                if ($v1!='.' && $v1!='..') $html .= '
                    <option value="'.$v1.'" '.($v1==getConfig($key)?'selected="selected"':'').'>'.$v1.'</option>';
            }
            $html .= '
                </select>
            </td>
        </tr>';
        } /*elseif ($key=='domain_path') {
            $tmp = getConfig($key);
            $domain_path = '';
            foreach ($tmp as $k1 => $v1) {
                $domain_path .= $k1 . ':' . $v1 . '|';
            }
            $domain_path = substr($domain_path, 0, -1);
            $html .= '
        <tr>
            <td><label>' . $key . '</label></td>
            <td width=100%><input type="text" name="' . $key .'" value="' . $domain_path . '" placeholder="' . getconstStr('EnvironmentsDescription')[$key] . '" style="width:100%"></td>
        </tr>';
        }*/ else $html .= '
        <tr>
            <td><label>' . $key . '</label></td>
            <td width=100%><input type="text" name="' . $key .'" value="' . getConfig($key) . '" placeholder="' . getconstStr('EnvironmentsDescription')[$key] . '" style="width:100%"></td>
        </tr>';
    }
    $html .= '
        <tr><td><input type="submit" name="submit1" value="'.getconstStr('Setup').'"></td></tr>
    </form>
</table><br>';
    foreach (explode("|",getConfig('disktag')) as $disktag) {
        if ($disktag!='') {
            $html .= '
<table border=1 width=100%>
    <form action="" method="post">
        <tr>
            <td colspan="2">'.$disktag.':
            <input type="hidden" name="disktag_del" value="'.$disktag.'">
            <input type="submit" name="submit1" value="'.getconstStr('DelDisk').'">
            </td>
        </tr>
    </form>';
            if (getConfig('refresh_token', $disktag)!='') {
                $html .= '
    <form name="'.$disktag.'" action="" method="post">
        <input type="hidden" name="disk" value="'.$disktag.'">';
                foreach ($ShowedInnerEnv as $key) {
                    $html .= '
        <tr>
            <td><label>' . $key . '</label></td>
            <td width=100%><input type="text" name="' . $key .'" value="' . getConfig($key, $disktag) . '" placeholder="' . getconstStr('EnvironmentsDescription')[$key] . '" style="width:100%"></td>
        </tr>';
                }
                $html .= '
        <tr><td><input type="submit" name="submit1" value="'.getconstStr('Setup').'"></td></tr>
    </form>';
            }
            $html .= '
</table><br>';
        }
    }
    $html .= '
1642 1643 1644
<a href="?AddDisk">'.getconstStr('AddDisk').'</a><br><br>';
    if (!((isset($_SERVER['USER'])&&$_SERVER['USER']==='qcloud')||(isset($_SERVER['HEROKU_APP_DIR'])&&$_SERVER['HEROKU_APP_DIR']==='/app'))) {
        $html .= '
Q
qkqpttgf 已提交
1645
'.getconstStr('VPSnotupdate').'<br>';
1646 1647 1648 1649 1650
    } else {
        $html .= '
<form name="updateform" action="" method="post">
    <input type="text" name="auth" placeholder="auth" value="qkqpttgf">
    <input type="text" name="project" placeholder="project" value="OneManager-php">
Q
qkqpttgf 已提交
1651 1652
    <button onclick="querybranchs();return false">'.getconstStr('QueryBranchs').'</button>
    <!--<input type="text" name="branch" placeholder="branch" value="master">-->
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
    <select name="branch">
        <option value="master">master</option>
    </select>
    <input type="submit" name="updateProgram" value="'.getconstStr('updateProgram').'">
</form>
<script>
    function querybranchs()
    {
        //alert(document.updateform.auth.value);
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "https://api.github.com/repos/"+document.updateform.auth.value+"/"+document.updateform.project.value+"/branches");
        //xhr.setRequestHeader("User-Agent","qkqpttgf/OneManager");
        xhr.send(null);
        xhr.onload = function(e){
            console.log(xhr.responseText+","+xhr.status);
            if (xhr.status==200) {
                document.updateform.branch.options.length=0;
                JSON.parse(xhr.responseText).forEach( function (e) {
                    //alert(e.name);
                    document.updateform.branch.options.add(new Option(e.name,e.name));
                    if ("master"==e.name) document.updateform.branch.options[document.updateform.branch.options.length-1].selected = true; 
                });
            } else {
                alert(xhr.responseText+"\n"+xhr.status);
            }
        }
        xhr.onerror = function(e){
            alert("Network Error "+xhr.status);
        }
    }
</script>
';
    }
    if ($needUpdate) {
        $html .= '<div style="position:relative;word-wrap: break-word;">
        ' . str_replace("\r", '<br>',$_SERVER['github_version']) . '
</div>';
    } else {
        $html .= getconstStr('NotNeedUpdate');
    }
1693 1694
    return message($html, getconstStr('Setup'));
}