This commit is contained in:
root
2021-01-15 11:10:08 +08:00
parent 372a42bc05
commit e8f1fd7175
26 changed files with 2652 additions and 13168 deletions
+715
View File
@@ -0,0 +1,715 @@
<?php
class Aliyundrive {
protected $access_token;
protected $disktag;
function __construct($tag) {
$this->disktag = $tag;
$this->auth_url = 'https://websv.aliyundrive.com/token/refresh';
$this->api_url = 'https://api.aliyundrive.com/v2';
$this->access_token = $this->get_access_token(getConfig('refresh_token', $tag));
$this->default_drive_id = getConfig('default_drive_id', $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 list_files($path = '/')
{
$files = $this->list_path($path);
return $this->files_format($files);
}
protected function files_format($files)
{
//return $files;
if ($files['type']=='file') {
$tmp['type'] = 'file';
$tmp['id'] = $files['file_id'];
if (isset($files['name'])) $tmp['name'] = $files['name'];
elseif (isset($files['file_name'])) $tmp['name'] = $files['file_name'];
$tmp['time'] = $files['updated_at'];
$tmp['size'] = $files['size'];
$tmp['mime'] = $files['file']['mimeType'];
$tmp['url'] = $files['download_url'];
$tmp['content'] = $files['content'];
if (isset($files['exist'])) $tmp['exist'] = $files['exist'];
if (isset($files['rapid_upload'])) $tmp['rapid_upload'] = $files['rapid_upload'];
} elseif ($files['type']=='folder'||isset($files['items'])) {
$tmp['type'] = 'folder';
$tmp['id'] = $files['file_id'];
if (isset($files['name'])) $tmp['name'] = $files['name'];
elseif (isset($files['file_name'])) $tmp['name'] = $files['file_name'];
$tmp['time'] = $files['updated_at'];
$tmp['size'] = $files['size'];
//$tmp['page'] = $files['folder']['page'];
foreach ($files['items'] as $file) {
if ($file['type']=='file') {
$tmp['list'][$file['name']]['type'] = 'file';
$tmp['list'][$file['name']]['url'] = $file['download_url'];
$tmp['list'][$file['name']]['mime'] = $file['file']['content_type'];
} elseif ($file['type']=='folder') {
$tmp['list'][$file['name']]['type'] = 'folder';
}
//$tmp['id'] = $file['parent_file_id'];
$tmp['list'][$file['name']]['id'] = $file['file_id'];
$tmp['list'][$file['name']]['name'] = $file['name'];
$tmp['list'][$file['name']]['time'] = $file['updated_at'];
$tmp['list'][$file['name']]['size'] = $file['size'];
$tmp['childcount']++;
}
} elseif (isset($files['code'])) {
return $files;
}
//error_log(json_encode($tmp));
return $tmp;
}
protected function list_path($path = '/')
{
global $exts;
while (substr($path, -1)=='/') $path = substr($path, 0, -1);
//$files = getcache('path_' . $path, $this->disktag);
//if (!$files) {
//if (!($files = getcache('path_' . $path, $this->disktag))) {
if ($path == '/' || $path == '') {
$files = $this->fileList('root');
//error_log('root_id' . $files['id']);
$files['file_id'] = 'root';
$files['type'] = 'folder';
} else {
$tmp = splitlast($path, '/');
$parent_path = $tmp[0];
$filename = urldecode($tmp[1]);
$parent_folder = $this->list_path($parent_path);
foreach ($parent_folder['items'] as $item) {
if ($item['name']==$filename) {
if ($item['type']=='folder') {
$files = $this->fileList($item['file_id']);
$files['type'] = 'folder';
$files['file_id'] = $item['file_id'];
$files['name'] = $item['name'];
$files['time'] = $item['updated_at'];
$files['size'] = $item['size'];
} else $files = $item;
}
}
//echo $files['name'];
}
if ($files['type']=='file') {
if (in_array(splitlast($files['name'],'.')[1], $exts['txt'])) {
if (!(isset($files['content'])&&$files['content']['stat']==200)) {
$content1 = curl('GET', $files['download_url']);
$files['content'] = $content1;
savecache('path_' . $path, $files, $this->disktag);
}
}
}
if (!$files) {
$files['error']['code'] = 'Not Found';
$files['error']['message'] = 'Not Found';
$files['error']['stat'] = 404;
} elseif (isset($files['stat'])) {
$tmp['error']['stat'] = $files['stat'];
$files['error']['code'] = 'Error';
$files['error']['message'] = $files['body'];
} else {
savecache('path_' . $path, $files, $this->disktag, 600);
}
//}
//error_log('path:' . $path . ', files:' . json_encode($files));
return $files;
}
protected function fileGet($file_id)
{
$url = $this->api_url . '/file/get';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['drive_id'] = $this->default_drive_id;
$data['file_id'] = $file_id;
$res = curl('POST', $url, json_encode($data), $header);
if ($res['stat']==200) return json_decode($res['body'], true);
else return $res;
}
protected function fileList($parent_file_id)
{
$url = $this->api_url . '/file/list';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['limit'] = 50;
$data['marker'] = NULL;
$data['drive_id'] = $this->default_drive_id;
$data['parent_file_id'] = $parent_file_id;
$data['image_thumbnail_process'] = 'image/resize,w_160/format,jpeg';
$data['image_url_process'] = 'image/resize,w_1920/format,jpeg';
$data['video_thumbnail_process'] = 'video/snapshot,t_0,f_jpg,w_300';
$data['fields'] = '*';
$data['order_by'] = 'updated_at';
$data['order_direction'] = 'DESC';
$res = curl('POST', $url, json_encode($data), $header);
if ($res['stat']==200) return json_decode($res['body'], true);
else return $res;
}
public function Rename($file, $newname) {
$url = $this->api_url . '/file/update';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['check_name_mode'] = 'refuse';
$data['drive_id'] = $this->default_drive_id;
$data['file_id'] = $file['id'];
$data['name'] = $newname;
//$data['parent_file_id'] = 'root';
$result = curl('POST', $url, json_encode($data), $header);
//savecache('path_' . $file['path'], json_decode('{}',true), $this->disktag, 1);
//error_log('decode:' . json_encode($result));
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
//return output($result['body'], $result['stat']);
}
public function Delete($file) {
$url = $this->api_url . '/batch';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['resource'] = 'file';
$data['requests'][0]['url'] = '/file/delete';
$data['requests'][0]['method'] = 'DELETE';
$data['requests'][0]['id'] = $file['id'];
$data['requests'][0]['headers']['Content-Type'] = 'application/json';
$data['requests'][0]['body']['drive_id'] = $this->default_drive_id;
$data['requests'][0]['body']['file_id'] = $file['id'];
$result = curl('POST', $url, json_encode($data), $header);
//savecache('path_' . $file['path'], json_decode('{}',true), $this->disktag, 1);
//error_log('result:' . json_encode($result));
//return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
$res = json_decode($result['body'], true)['responses'][0];
if (isset($res['status'])) return output($res['id'], $res['status']);
else return output($result['body'], $result['stat']);
}
public function Encrypt($folder, $passfilename, $pass) {
$existfile = $this->list_path($folder['path'] . '/' . $passfilename);
if (isset($existfile['type'])) { // 删掉原文件
$this->Delete(['id'=>$existfile['file_id']]);
}
if (!$folder['id']) {
$res = $this->list_path($folder['path']);
//error_log('res:' . json_encode($res));
$folder['id'] = $res['file_id'];
}
$tmp = '/tmp/' . $passfilename;
file_put_contents($tmp, $pass);
$result = $this->tmpfileCreate($folder['id'], $tmp, $passfilename);
if ($result['stat']==201) {
//error_log('1,url:' . $url .' res:' . json_encode($result));
$res = json_decode($result['body'], true);
$url = $res['part_info_list'][0]['upload_url'];
if (!$url) { // 无url,应该算秒传
return output('no up url', 200);
}
$file_id = $res['file_id'];
$upload_id = $res['upload_id'];
$result = curl('PUT', $url, $pass, [], 1);
if ($result['stat']==200) { // 块1传好
$tmp1['part_number'] = 1;
$tmp1['etag'] = $result['returnhead']['ETag'];
$result = $this->fileComplete($file_id, $upload_id, [ $tmp1 ]);
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
}
}
//error_log('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) {
if (!$folder['id']) {
$res = $this->list_path($folder['path']);
//error_log('res:' . json_encode($res));
$folder['id'] = $res['file_id'];
}
$url = $this->api_url . '/batch';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['resource'] = 'file';
$data['requests'][0]['url'] = '/file/move';
$data['requests'][0]['method'] = 'POST';
$data['requests'][0]['id'] = $file['id'];
$data['requests'][0]['headers']['Content-Type'] = 'application/json';
$data['requests'][0]['body']['drive_id'] = $this->default_drive_id;
$data['requests'][0]['body']['file_id'] = $file['id'];
$data['requests'][0]['body']['auto_rename'] = true;
$data['requests'][0]['body']['to_parent_file_id'] = $folder['id'];
$result = curl('POST', $url, json_encode($data), $header);
//savecache('path_' . $file['path'], json_decode('{}',true), $this->disktag, 1);
//error_log('result:' . json_encode($result));
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
}
public function Copy($file) {
if (!$file['id']) {
$oldfile = $this->list_path($file['path'] . '/' . $file['name']);
//error_log('res:' . json_encode($res));
//$file['id'] = $res['file_id'];
} else {
$oldfile = $this->fileGet($file['id']);
}
$url = $this->api_url . '/file/create';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['check_name_mode'] = 'auto_rename'; // ignore, auto_rename, refuse.
$data['content_hash'] = $oldfile['content_hash'];
$data['content_hash_name'] = 'sha1';
$data['content_type'] = $oldfile['content_type'];
$data['drive_id'] = $this->default_drive_id;
$data['ignoreError'] = false;
$data['name'] = $oldfile['name'];
$data['parent_file_id'] = $oldfile['parent_file_id'];
$data['part_info_list'][0]['part_number'] = 1;
$data['size'] = $oldfile['size'];
$data['type'] = 'file';
$result = curl('POST', $url, json_encode($data), $header);
if ($result['stat']==201) {
//error_log('1,url:' . $url .' res:' . json_encode($result));
$res = json_decode($result['body'], true);
$url = $res['part_info_list'][0]['upload_url'];
if (!$url) { // 无url,应该算秒传
return output('no up url', 200);
} else {
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
}
/*$file_id = $res['file_id'];
$upload_id = $res['upload_id'];
$result = curl('PUT', $url, $content, [], 1);
if ($result['stat']==200) { // 块1传好
$etag = $result['returnhead']['ETag'];
$result = $this->fileComplete($file_id, $upload_id, $etag);
if ($result['stat']!=200) return output($result['body'], $result['stat']);
else return output('success', 0);
}*/
}
//error_log('2,url:' . $url .' res:' . json_encode($result));
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['type'])) { // 删掉原文件
$this->Delete(['id'=>$existfile['file_id']]);
}
$tmp1 = '/tmp/' . $filename;
file_put_contents($tmp1, $content);
$result = $this->tmpfileCreate($this->list_path($folderpath)['file_id'], $tmp1, $filename);
if ($result['stat']==201) {
//error_log('1,url:' . $url .' res:' . json_encode($result));
$res = json_decode($result['body'], true);
$url = $res['part_info_list'][0]['upload_url'];
if (!$url) { // 无url,应该算秒传
return output('no up url', 0);
}
$file_id = $res['file_id'];
$upload_id = $res['upload_id'];
$result = curl('PUT', $url, $content, [], 1);
if ($result['stat']==200) { // 块1传好
$tmp2['part_number'] = 1;
$tmp2['etag'] = $result['returnhead']['ETag'];
$result = $this->fileComplete($file_id, $upload_id, [ $tmp2 ]);
if ($result['stat']!=200) return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
else return output('success', 0);
}
}
//error_log('2,url:' . $url .' res:' . json_encode($result));
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
}
public function Create($folder, $type, $name, $content = '') {
if (!$folder['id']) {
$res = $this->list_path($folder['path']);
//error_log('res:' . json_encode($res));
$folder['id'] = $res['file_id'];
}
if ($type=='folder') {
$result = $this->folderCreate($folder['id'], $name);
//error_log('res:' . json_encode($result));
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
}
if ($type=='file') {
$tmp = '/tmp/' . $name;
file_put_contents($tmp, $content);
$result = $this->tmpfileCreate($folder['id'], $tmp, $name);
if ($result['stat']==201) {
//error_log('1,url:' . $url .' res:' . json_encode($result));
$res = json_decode($result['body'], true);
if (isset($res['exist'])&&$res['exist']!=false) {
// 已经有
//error_log('exist:' . json_encode($res));
return output('{"type":"file","name":"' . $name . '", "exist":true}', 200);
}
if (isset($res['rapid_upload'])&&$res['rapid_upload']!=false) {
// 秒传
//error_log('rapid up:' . json_encode($res));
return output('{"type":"file","name":"' . $name . '", "rapid_upload":true}', 200);
}
$url = $res['part_info_list'][0]['upload_url'];
$file_id = $res['file_id'];
$upload_id = $res['upload_id'];
$result = curl('PUT', $url, $content, [], 1);
//error_log('2,url:' . $url .' res:' . json_encode($result));
if ($result['stat']==200) { // 块1传好
$tmp1['part_number'] = 1;
$tmp1['etag'] = $result['returnhead']['ETag'];
$result = $this->fileComplete($file_id, $upload_id, [ $tmp1 ]);
//error_log('3,url:' . $url .' res:' . json_encode($result));
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
}
}
//error_log('4,url:' . $url .' res:' . json_encode($result));
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
}
return output('Type not folder or file.', 500);
}
protected function folderCreate($parentId, $folderName) {
if (strrpos($folderName, '/')) {
$tmp = splitlast($folderName, '/');
$parentId = json_decode($this->folderCreate($parentId, $tmp[0])['body'], true)['file_id'];
$folderName = $tmp[1];
}
$url = $this->api_url . '/file/create';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['check_name_mode'] = 'refuse'; // ignore, auto_rename, refuse.
$data['drive_id'] = $this->default_drive_id;
$data['name'] = $folderName;
$data['parent_file_id'] = $parentId;
$data['type'] = 'folder';
return curl('POST', $url, json_encode($data), $header);
}
protected function fileCreate($parentId, $fileName, $sha1, $size) {
$url = $this->api_url . '/file/create';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['check_name_mode'] = 'refuse'; // ignore, auto_rename, refuse.
$data['content_hash'] = $sha1;
$data['content_hash_name'] = 'sha1';
$data['content_type'] = '';
$data['drive_id'] = $this->default_drive_id;
$data['ignoreError'] = false;
$data['name'] = $fileName;
$data['parent_file_id'] = $parentId;
$data['part_info_list'][0]['part_number'] = 1;
$data['size'] = (int)$size;
$data['type'] = 'file';
return curl('POST', $url, json_encode($data), $header);
}
protected function tmpfileCreate($parentId, $tmpFilePath, $tofileName = '') {
$sha1 = sha1_file($tmpFilePath);
if ($tofileName == '') $tofileName = splitlast($tmpFilePath, '/')[1];
$url = $this->api_url . '/file/create';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['check_name_mode'] = 'refuse'; // ignore, auto_rename, refuse.
$data['content_hash'] = $sha1;
$data['content_hash_name'] = 'sha1';
$data['content_type'] = 'text/plain'; // now only txt
$data['drive_id'] = $this->default_drive_id;
$data['ignoreError'] = false;
$data['name'] = $tofileName;
$data['parent_file_id'] = $parentId;
$data['part_info_list'][0]['part_number'] = 1; // now only txt
$data['size'] = filesize($tmpFilePath);
$data['type'] = 'file';
return curl('POST', $url, json_encode($data), $header);
}
protected function fileComplete($file_id, $upload_id, $etags) {
$url = $this->api_url . '/file/complete';
$header["content-type"] = "application/json; charset=utf-8";
$header['authorization'] = 'Bearer ' . $this->access_token;
$data['drive_id'] = $this->default_drive_id;
$data['file_id'] = $file_id;
$data['ignoreError'] = false;
foreach ($etags as $etag) {
$data['part_info_list'][$etag['part_number'] - 1]['part_number'] = $etag['part_number'];
$data['part_info_list'][$etag['part_number'] - 1]['etag'] = $etag['etag'];
}
$data['upload_id'] = $upload_id;
return curl('POST', $url, json_encode($data), $header);
}
public function get_thumbnails_url($path = '/')
{
$res = $this->list_path($path);
$thumb_url = $res['thumbnail'];
return $thumb_url;
}
public function bigfileupload($path)
{
if (isset($_POST['uploadid'])) {
// Complete
$result = $this->fileComplete($_POST['fileid'], $_POST['uploadid'], $_POST['etag']);
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
} else {
if ($_POST['upbigfilename']=='') return output('error: no file name', 400);
if (!is_numeric($_POST['filesize'])) return output('error: no file size', 400);
if (!isset($_POST['filesha1'])) return output('error: no file sha1', 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 = $fileinfo['name'];
} else {
$tmp1 = splitlast($fileinfo['name'], '.');
if ($tmp1[0]==''||$tmp1[1]=='') $filename = $_POST['filesha1'];
else $filename = $_POST['filesha1'] . '.' . $tmp1[1];
}
/*if ($fileinfo['size']>10*1024*1024) {
$cachefilename = spurlencode( $fileinfo['path'] . '/.' . $fileinfo['filelastModified'] . '_' . $fileinfo['size'] . '_' . $fileinfo['name'] . '.tmp', '/');
$getoldupinfo=$this->list_path(path_format($path . '/' . $cachefilename));
//echo json_encode($getoldupinfo, JSON_PRETTY_PRINT);
if ($getoldupinfo['type']=='file'&&$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']);
}
}*/
$parent = $this->list_path($path . '/' . $fileinfo['path']);
if (isset($parent['file_id'])) {
$parent_file_id = $parent['file_id'];
} else {
$res = $this->folderCreate($this->list_path($path)['file_id'], $fileinfo['path']);
//error_log($res['body']);
$parent_file_id = json_decode($res['body'], true)['file_id'];
}
$response = $this->fileCreate($parent_file_id, $filename, $_POST['filesha1'], $fileinfo['size']);
$res = json_decode($response['body'], true);
if (isset($res['exist'])) {
// 已经有
//error_log('exist:' . json_encode($res));
return output(json_encode($this->files_format(json_decode($response['body'], true))), $response['stat']);
//return output('{"type":"file","name":"' . $_POST['upbigfilename'] . '", "exist":true}', 200);
}
if (isset($res['rapid_upload'])&&$res['rapid_upload']!=false) {
// 秒传
//error_log('rapid up:' . json_encode($res));
return output(json_encode($this->files_format(json_decode($response['body'], true))), $response['stat']);
//return output('{"type":"file","name":"' . $_POST['upbigfilename'] . '", "rapid upload":true}', 200);
}
//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), $this->access_token);
//}
return output($response['body'], $response['stat']);
}
}
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['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 . '<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>
<script>
var expd = new Date();
expd.setTime(expd.getTime()+1);
var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=; path=/; \'+expires;
</script>', 'Error', 201);
} elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) {
return message('Please start with letters<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>
<script>
var expd = new Date();
expd.setTime(expd.getTime()+1);
var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=; path=/; \'+expires;
</script>', 'Error', 201);
}
$tmp['refresh_token'] = $_POST['refresh_token'];
$res = curl('POST', $this->auth_url, json_encode($tmp), ["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;
foreach ($EnvConfigs as $env => $v) if (isInnerEnv($env)) $tmp[$env] = '';
$tmp['refresh_token'] = $result['refresh_token'];
$tmp['default_drive_id'] = $result['default_drive_id'];
$tmp['default_sbox_drive_id'] = $result['default_sbox_drive_id'];
$tmp['token_expires'] = time()+7*24*60*60;
$tmp['Driver'] = 'Aliyundrive';
$tmp['disktag_add'] = $_POST['disktag_add'];
$tmp['diskname'] = $_POST['diskname'];
$response = setConfigResponse( setConfig($tmp, $this->disktag) );
if (api_error($response)) {
$html = api_error_msg($response);
$title = 'Error';
return message($html, $title, 201);
} else {
savecache('access_token', $result['access_token'], $this->disktag, $result['expires_in'] - 60);
$str .= '<meta http-equiv="refresh" content="5;URL=' . $url . '">
<script>
var expd = new Date();
expd.setTime(expd.getTime()+1);
var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=; path=/; \'+expires;
</script>';
return message($str, getconstStr('WaitJumpIndex'), 201);
}
/*$api = $this->api_url . '/user/get';
$header['authorization'] = 'Bearer ' . $this->access_token;
return json_encode(curl('GET', $api, '', $header));*/
}
$html = '
<div>
<form id="form1" action="" method="post" onsubmit="return notnull(this);">
' . getconstStr('DiskTag') . ': (' . getConfig('disktag') . ')
<input type="text" name="disktag_add" placeholder="' . getconstStr('EnvironmentsDescription')['disktag'] . '" style="width:100%"><br>
' . getconstStr('DiskName') . ':
<input type="text" name="diskname" placeholder="' . getconstStr('EnvironmentsDescription')['diskname'] . '" style="width:100%"><br>
<br>
<div>填入refresh_token:
<input type="text" name="refresh_token" placeholder="' . getconstStr(' ') . '" style="width:100%"><br>
</div>
<br>
<input type="submit" value="' . getconstStr('Submit') . '">
</form>
</div>
<script>
function notnull(t)
{
if (t.disktag_add.value==\'\') {
alert(\'' . getconstStr('DiskTag') . '\');
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;
}
if (t.refresh_token.value==\'\') {
alert(\'Input refresh_token\');
return false;
}
document.getElementById("form1").action="?install0&AddDisk=Aliyundrive";
var expd = new Date();
expd.setTime(expd.getTime()+(2*60*60*1000));
var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=\'+t.disktag_add.value+\'; path=/; \'+expires;
return true;
}
</script>';
$title = 'Select Account Type';
return message($html, $title, 201);
}
protected function get_access_token($refresh_token) {
if (!($this->access_token = getcache('access_token', $this->disktag))) {
$p=0;
$tmp1['refresh_token'] = $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_log(json_encode($response));
if ($response['stat']==200) $ret = json_decode($response['body'], true);
if (!isset($ret['access_token'])) {
error_log('failed to get [' . $this->disktag . '] access_token. response' . json_encode($ret));
$response['body'] = json_encode(json_decode($response['body']), JSON_PRETTY_PRINT);
$response['body'] .= '\nfailed to get [' . $this->disktag . '] access_token.';
return $response;
}
$tmp = $ret;
$tmp['access_token'] = '******';
$tmp['refresh_token'] = '******';
error_log('[' . $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 $this->access_token;
}
}
+915
View File
@@ -0,0 +1,915 @@
<?php
class Onedrive {
protected $access_token;
protected $disktag;
function __construct($tag) {
$this->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 = ':EK[e0/4vQ@mQgma8LmnWb6j4_C1CSIW';
}
$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 offline_access';
$this->access_token = $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';
}
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 list_files($path = '/')
{
global $exts;
if (!($files = getcache('path_' . $path, $this->disktag))) {
// 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, $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);
}
}
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.')';
$retry = 0;
$arr = [];
while ($retry<3&&!$arr['stat']) {
$arr = curl('GET', $url, '', ['Authorization' => 'Bearer ' . $this->access_token], 1);
$retry++;
}
//echo $url . '<br><pre>' . json_encode($arr, JSON_PRETTY_PRINT) . '</pre>';
if ($arr['stat']<500) {
$files = json_decode($arr['body'], true);
//echo '<pre>' . json_encode($files, JSON_PRETTY_PRINT) . '</pre>';
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_' . $path . '_' . $page, $this->disktag))) {
$files = $this->fetch_files_children($files, $path, $page);
//$files['children'] = children_name($files['children']);
/*$url = $_SERVER['api_url'];
if ($path !== '/') {
$url .= ':' . $path;
if (substr($url,-1)=='/') $url=substr($url,0,-1);
$url .= ':/children?$top=9999&$select=id,name,size,file,folder,parentReference,lastModifiedDateTime,'.$this->DownurlStrName;
} else {
$url .= '/children?$top=9999&$select=id,name,size,file,folder,parentReference,lastModifiedDateTime,'.$this->DownurlStrName;
}
$children = json_decode(curl_request($url, false, ['Authorization' => 'Bearer ' . $this->access_token])['body'], true);
$files['children'] = $children['value'];*/
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(splitlast($files['name'],'.')[1], $exts['txt'])) {
if (!(isset($files['content'])&&$files['content']['stat']==200)) {
$content1 = curl('GET', $files[$this->DownurlStrName]);
$files['content'] = $content1;
savecache('path_' . $path, $files, $this->disktag);
}
}
}
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));
}
}
//echo '<pre>' . json_encode($files, JSON_PRETTY_PRINT) . '</pre>';
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) {
if (isset($file['file'])) {
$tmp['list'][$file['name']]['type'] = 'file';
//var_dump($file);
//echo $file['name'] . ':' . $this->DownurlStrName . ':' . $file[$this->DownurlStrName] . PHP_EOL;
$tmp['list'][$file['name']]['url'] = $file[$this->DownurlStrName];
$tmp['list'][$file['name']]['mime'] = $file['file']['mimeType'];
} elseif (isset($file['folder'])) {
$tmp['list'][$file['name']]['type'] = 'folder';
}
$tmp['list'][$file['name']]['id'] = $file['id'];
$tmp['list'][$file['name']]['name'] = $file['name'];
$tmp['list'][$file['name']]['time'] = $file['lastModifiedDateTime'];
$tmp['list'][$file['name']]['size'] = $file['size'];
}
} elseif (isset($files['error'])) {
return $files;
}
//error_log(json_encode($tmp));
return $tmp;
}
protected function fetch_files_children($files, $path, $page)
{
$cachefilename = '.SCFcache_'.$_SERVER['function_name'];
$maxpage = ceil($files['folder']['childCount']/200);
if (!($files['children'] = getcache('files_' . $path . '_page_' . $page, $this->disktag))) {
// down cache file get jump info. 下载cache文件获取跳页链接
$cachefile = $this->list_files(path_format($path . '/' .$cachefilename));
if ($cachefile['size']>0) {
$pageinfo = curl('GET', $cachefile[$this->DownurlStrName])['body'];
$pageinfo = json_decode($pageinfo,true);
for ($page4=1;$page4<$maxpage;$page4++) {
savecache('nextlink_' . $path . '_page_' . $page4, $pageinfo['nextlink_' . $path . '_page_' . $page4], $this->disktag);
$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, $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(curl('GET', $url, false, ['Authorization' => 'Bearer ' . $this->access_token])['body'], true);
// echo $url . '<br><pre>' . json_encode($children, JSON_PRETTY_PRINT) . '</pre>';
savecache('files_' . $path . '_page_' . $page1, $children['value'], $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(curl('GET', $url, false, ['Authorization' => 'Bearer ' . $this->access_token])['body'], true);
savecache('files_' . $path . '_page_' . $page2, $children['value'], $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 . '<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) $this->MSAPI('PUT', path_format($path.'/'.$cachefilename), json_encode($pageinfocache, JSON_PRETTY_PRINT), $this->access_token)['body'];
return $files;
}
} else {
for ($page2=$page3+1;$page2<=$page;$page2++) {
sleep(1);
$children = json_decode(curl('GET', $url, false, ['Authorization' => 'Bearer ' . $this->access_token])['body'], true);
savecache('files_' . $path . '_page_' . $page2, $children['value'], $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 . '<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) $this->MSAPI('PUT', path_format($path.'/'.$cachefilename), json_encode($pageinfocache, JSON_PRETTY_PRINT), $this->access_token)['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 $files;
}
public function Rename($file, $newname) {
$oldname = spurlencode($file['name']);
$oldname = path_format($file['path'] . '/' . $oldname);
$data = '{"name":"' . $newname . '"}';
//echo $oldname;
$result = $this->MSAPI('PATCH', $oldname, $data, $this->access_token);
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;
$result = $this->MSAPI('DELETE', $filename, '', $this->access_token);
return output(json_encode($this->files_format(json_decode($result['body'], true))), $result['stat']);
return output($result['body'], $result['stat']);
}
public function Encrypt($folder, $passfilename, $pass) {
$filename = path_format($folder['path'] . '/' . urlencode($passfilename));
$result = $this->MSAPI('PUT', $filename, $pass, $this->access_token);
$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'] . '"}}';
$result = $this->MSAPI('PATCH', $filename, $data, $this->access_token);
$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 . '" }';
$result = $this->MSAPI('copy', $filename, $data, $this->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 = $this->MSAPI('copy', $filename, $data, $this->access_token);
}*/
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, $this->access_token);
//return output($result['body'], $result['stat']);
//echo $result;
$resultarry = json_decode($result['body'],true);
if (isset($resultarry['error'])) return message($resultarry['error']['message']. '<hr><a href="javascript:history.back(-1)">'.getconstStr('Back').'</a>','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, $this->access_token);
}
if ($type=='folder') {
$data = '{ "name": "' . $name . '", "folder": { }, "@microsoft.graph.conflictBehavior": "rename" }';
$result = $this->MSAPI('children', $parent['path'], $data, $this->access_token);
}
//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 = path_format($_SERVER['PHP_SELF'] . '/');
//$this->api_url = splitfirst($_SERVER['api_url'], '/v1.0')[0] . '/v1.0';
if (isset($_GET['install4'])) {
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.<br>' . $this->disktag;
$title = 'Error';
return message($html, $title, 201);
}
$response = $this->get_access_token($refresh_token);
if (isset($response['stat'])) return message($response['body'], 'Error', $response['stat']);
}
$tmp = null;
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'] . '<br>' . $api . '<br>' . $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']);
}
} 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'];
//$tmp['DriveId'] = json_decode($arr['body'], true)['id'];
if (get_class($this)=='Onedrive') $tmp['Driver'] = 'Sharepoint';
elseif (get_class($this)=='OnedriveCN') $tmp['Driver'] = 'SharepointCN';
} else {
// 直接是siteid
//$api = $this->api_url . '/sites/' . $_POST['DriveType'] . '/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'] = $_POST['DriveType'];
$tmp['sharepointSite'] = $_POST['sharepointSiteUrl'];
//$tmp['DriveId'] = json_decode($arr['body'], true)['id'];
if (get_class($this)=='Onedrive') $tmp['Driver'] = 'Sharepoint';
elseif (get_class($this)=='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 {
$str .= '<meta http-equiv="refresh" content="5;URL=' . $url . '">
<script>
var expd = new Date();
expd.setTime(expd.getTime()+1);
var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=; path=/; \'+expires;
</script>';
return message($str, getconstStr('WaitJumpIndex'), 201);
}
}
if (isset($_GET['install3'])) {
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.<br>' . $this->disktag;
$title = 'Error';
return message($html, $title, 201);
}
$response = $this->get_access_token($refresh_token);
if (isset($response['stat'])) return message($response['body'], 'Error', $response['stat']);
}
$api = $this->api_url . '/sites/root';
$arr = curl('GET', $api, '', [ 'Authorization' => 'Bearer ' . $this->access_token ]);
$Tenant = json_decode($arr['body'], true)['webUrl'];
$api = $this->api_url . '/me/followedSites';
$arr = curl('GET', $api, '', [ 'Authorization' => 'Bearer ' . $this->access_token ]);
if (!($arr['stat']==200||$arr['stat']==403||$arr['stat']==400)) return message($arr['stat'] . json_encode(json_decode($arr['body']), JSON_PRETTY_PRINT), 'Get followedSites', $arr['stat']);
error_log($arr['body']);
$sites = json_decode($arr['body'], true)['value'];
$title = 'Select Disk';
$html = '
<div>
<form action="?install4&AddDisk=' . get_class($this) . '" method="post" onsubmit="return notnull(this);">
<label><input type="radio" name="DriveType" value="Onedrive" checked>' . 'Use Onedrive ' . getconstStr(' ') . '</label><br>';
if ($sites[0]!='') foreach ($sites as $k => $v) {
$html .= '
<label>
<input type="radio" name="DriveType" value="' . $v['id'] . '" onclick="document.getElementById(\'sharepointSiteUrl\').value=\'' . $v['webUrl'] . '\';">' . 'Use Sharepoint: <br><div style="width:100%;margin:0px 35px">webUrl: ' . $v['webUrl'] . '<br>siteid: ' . $v['id'] . '</div>
</label>';
}
$html .= '
<input type="hidden" id="sharepointSiteUrl" name="sharepointSiteUrl" value="">
<label>
<input type="radio" name="DriveType" value="Custom" id="Custom">' . 'Use Other Sharepoint:' . getconstStr(' ') . '<br>
<div style="width:100%;margin:0px 35px"><a href="' . $Tenant . '/_layouts/15/sharepoint.aspx" target="_blank">' . getconstStr('GetSharepointSiteAddress') . '</a><br>
<input type="text" name="sharepointSite" style="width:100%;" placeholder="' . getconstStr('InputSharepointSiteAddress') . '" onclick="document.getElementById(\'Custom\').checked=\'checked\';">
</div>
</label><br>
';
$html .= '
<input type="submit" value="' . getconstStr('Submit') . '">
</form>
</div>
<script>
function notnull(t)
{
if (t.DriveType.value==\'\') {
alert(\'Select a Disk\');
return false;
}
if (t.DriveType.value==\'Custom\') {
if (t.sharepointSite.value==\'\') {
alert(\'sharepoint Site Address\');
return false;
}
}
return true;
}
</script>
';
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 :<br>';
$str .= '
<textarea readonly style="width: 95%">' . $refresh_token . '</textarea><br><br>
' . getconstStr('SavingToken') . '
<script>
var texta=document.getElementsByTagName(\'textarea\');
for(i=0;i<texta.length;i++) {
texta[i].style.height = texta[i].scrollHeight + \'px\';
}
</script>';
$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 .= '
<meta http-equiv="refresh" content="3;URL=' . $url . '?AddDisk=' . get_class($this) . '&install3">';
return message($str, getconstStr('Wait') . ' 3s', 201);
}
}
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);
}
if (isset($_GET['install1'])) {
if (get_class($this)=='Onedrive' || get_class($this)=='OnedriveCN') {
return message('
<a href="" id="a1">' . getconstStr('JumptoOffice') . '</a>
<script>
url=location.protocol + "//" + location.host + "' . $url . '?install2&AddDisk=' . get_class($this) . '";
url="' . $this->oauth_url . 'authorize?scope=' . $this->scope . '&response_type=code&client_id=' . $this->client_id . '&redirect_uri=' . $this->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, 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 . '<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>
<script>
var expd = new Date();
expd.setTime(expd.getTime()+1);
var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=; path=/; \'+expires;
</script>', 'Error', 201);
} elseif (!(('a'<=$f && $f<='z') || ('A'<=$f && $f<='Z'))) {
return message('Please start with letters<br><button onclick="location.href = location.href;">'.getconstStr('Refresh').'</button>
<script>
var expd = new Date();
expd.setTime(expd.getTime()+1);
var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=; path=/; \'+expires;
</script>', 'Error', 201);
}
$tmp = null;
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'];
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';
} else {
$title = getconstStr('MayinEnv');
$html = getconstStr('Wait') . ' 3s<meta http-equiv="refresh" content="3;URL=' . $url . '?install1&AddDisk=' . $_POST['Drive_ver'] . '">';
if ($_POST['Drive_ver']=='Sharelink') $html = getconstStr('Wait') . ' 3s<meta http-equiv="refresh" content="3;URL=' . $url . '">';
}
return message($html, $title, 201);
}
}
$html = '
<div>
<form id="form1" action="" method="post" onsubmit="return notnull(this);">
' . getconstStr('DiskTag') . ': (' . getConfig('disktag') . ')
<input type="text" name="disktag_add" placeholder="' . getconstStr('EnvironmentsDescription')['disktag'] . '" style="width:100%"><br>
' . getconstStr('DiskName') . ':
<input type="text" name="diskname" placeholder="' . getconstStr('EnvironmentsDescription')['diskname'] . '" style="width:100%"><br>
<br>
<div>
<label><input type="radio" name="Drive_ver" value="Onedrive" onclick="document.getElementById(\'NT_custom\').style.display=\'\';document.getElementById(\'CN_custom\').style.display=\'none\';document.getElementById(\'inputshareurl\').style.display=\'none\';">MS: ' . getconstStr('DriveVerMS') . '</label><br>
<div id="NT_custom" style="display:none;margin:0px 35px">
<label><input type="checkbox" name="NT_Drive_custom" onclick="document.getElementById(\'NT_secret\').style.display=(this.checked?\'\':\'none\');">' . getconstStr('CustomIdSecret') . '</label><br>
<div id="NT_secret" style="display:none;margin:10px 35px">
<a href="https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps" target="_blank">' . getconstStr('GetSecretIDandKEY') . '</a><br>
return_uri(Reply URL):<br>https://scfonedrive.github.io/<br>
client_id:<input type="text" name="NT_client_id" style="width:100%" placeholder="a1b2c345-90ab-cdef-ghij-klmnopqrstuv"><br>
client_secret:<input type="text" name="NT_client_secret" style="width:100%"><br>
</div>
</div><br>
<label><input type="radio" name="Drive_ver" value="OnedriveCN" onclick="document.getElementById(\'CN_custom\').style.display=\'\';document.getElementById(\'NT_custom\').style.display=\'none\';document.getElementById(\'inputshareurl\').style.display=\'none\';">CN: ' . getconstStr('DriveVerCN') . '</label><br>
<div id="CN_custom" style="display:none;margin:0px 35px">
<label><input type="checkbox" name="CN_Drive_custom" onclick="document.getElementById(\'CN_secret\').style.display=(this.checked?\'\':\'none\');">' . getconstStr('CustomIdSecret') . '</label><br>
<div id="CN_secret" style="display:none;margin:10px 35px">
<a href="https://portal.azure.cn/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps" target="_blank">' . getconstStr('GetSecretIDandKEY') . '</a><br>
return_uri(Reply URL):<br>https://scfonedrive.github.io/<br>
client_id:<input type="text" name="CN_client_id" style="width:100%" placeholder="a1b2c345-90ab-cdef-ghij-klmnopqrstuv"><br>
client_secret:<input type="text" name="CN_client_secret" style="width:100%"><br>
</div>
</div><br>
<label><input type="radio" name="Drive_ver" value="Sharelink" onclick="document.getElementById(\'CN_custom\').style.display=\'none\';document.getElementById(\'inputshareurl\').style.display=\'\';document.getElementById(\'NT_custom\').style.display=\'none\';">Sharelink: ' . getconstStr('DriveVerShareurl') . '</label><br>
<div id="inputshareurl" style="display:none;margin:0px 35px">
' . getconstStr('UseShareLink') . '
<input type="text" name="shareurl" style="width:100%" placeholder="https://xxxx.sharepoint.com/:f:/g/personal/xxxxxxxx/mmmmmmmmm?e=XXXX"><br>
</div>
</div>
<br>';
if ($_SERVER['language']=='zh-cn') $html .= '你要理解 scfonedrive.github.io 是github上的静态网站,<br>除非github真的挂掉了,<br>不然,稍后你如果连不上,请检查你的运营商或其它“你懂的”问题!<br>';
$html .='
<input type="submit" value="' . getconstStr('Submit') . '">
</form>
</div>
<script>
function notnull(t)
{
if (t.disktag_add.value==\'\') {
alert(\'' . getconstStr('DiskTag') . '\');
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;
}
if (t.Drive_ver.value==\'\') {
alert(\'Select a Driver\');
return false;
}
if (t.Drive_ver.value==\'Sharelink\') {
if (t.shareurl.value==\'\') {
alert(\'shareurl\');
return false;
}
} else {
if ((t.Drive_ver.value==\'Onedrive\') && t.NT_Drive_custom.checked==true) {
if (t.NT_client_secret.value==\'\'||t.NT_client_id.value==\'\') {
alert(\'client_id & client_secret\');
return false;
}
}
if ((t.Drive_ver.value==\'OnedriveCN\') && t.CN_Drive_custom.checked==true) {
if (t.CN_client_secret.value==\'\'||t.CN_client_id.value==\'\') {
alert(\'client_id & client_secret\');
return false;
}
}
}
document.getElementById("form1").action="?install0&AddDisk=" + t.Drive_ver.value;
var expd = new Date();
expd.setTime(expd.getTime()+(2*60*60*1000));
var expires = "expires="+expd.toGMTString();
document.cookie=\'disktag=\'+t.disktag_add.value+\'; path=/; \'+expires;
return true;
}
</script>';
$title = 'Select Account Type';
return message($html, $title, 201);
}
protected function get_access_token($refresh_token) {
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_log($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_log('failed to get [' . $this->disktag . '] access_token. response' . json_encode($ret));
$response['body'] = json_encode(json_decode($response['body']), JSON_PRETTY_PRINT);
$response['body'] .= '\nfailed to get [' . $this->disktag . '] access_token.';
return $response;
//throw new Exception($response['stat'].', failed to get ['.$this->disktag.'] access_token.'.$response['body']);
}
$tmp = $ret;
$tmp['access_token'] = '******';
$tmp['refresh_token'] = '******';
error_log('[' . $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 $this->access_token;
}
protected function get_siteid($sharepointSite)
{
//$sharepointSite = getConfig('sharepointSite', $this->disktag);
while (substr($sharepointSite, -1)=='/') $sharepointSite = substr($sharepointSite, 0, -1);
$tmp = splitlast($sharepointSite, '/');
$sharepointname = urlencode($tmp[1]);
$tmp = splitlast($tmp[0], '/');
$sharepointname = $tmp[1] . '/' . $sharepointname;
if (getConfig('Driver', $this->disktag)=='Onedrive') $url = 'https://graph.microsoft.com/v1.0/sites/root:/' . $sharepointname;
if (getConfig('Driver', $this->disktag)=='OnedriveCN') $url = 'https://microsoftgraph.chinacloudapi.cn/v1.0/sites/root:/' . $sharepointname;
$i=0;
$response = [];
while ($url!=''&&$response['stat']!=200&&$i<4) {
$response = curl('GET', $url, false, ['Authorization' => 'Bearer ' . $this->access_token]);
$i++;
}
if ($response['stat']!=200) {
error_log('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()
{
error_log('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, '', $this->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), $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(curl('GET', $url, false, ['Authorization' => 'Bearer ' . $this->access_token])['body'], true);
if (isset($files['url'])) {
savecache('thumb_' . $path, $files['url'], $this->disktag);
$thumb_url = $files['url'];
}
}
return $thumb_url;
}
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));
//echo json_encode($getoldupinfo, JSON_PRETTY_PRINT);
if (isset($getoldupinfo['file'])&&$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" }}', $this->access_token);
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), $this->access_token);
}
return output($response['body'], $response['stat']);
}
protected 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 = $this->api_url . $this->ext_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'].'
'.$url.'
');
return $response;
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
if (!class_exists('Onedrive')) require 'Onedrive.php';
class OnedriveCN extends Onedrive {
function __construct($tag) {
$this->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 offline_access';
$this->access_token = getcache('access_token', $tag);
if (!$this->access_token) $this->access_token = $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';
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
if (!class_exists('Onedrive')) require 'Onedrive.php';
class Sharelink extends Onedrive {
function __construct($tag) {
$this->disktag = $tag;
$this->redirect_uri = 'https://scfonedrive.github.io';
$this->api_url = getConfig('shareapiurl', $tag);
$this->access_token = $this->get_access_token(1);
//$this->ext_api_url = '/me/drive/root';
$this->DownurlStrName = '@content.downloadUrl';
}
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))) {
$this->sharecookie = curl('GET', $shareurl, false, [], 1)['returnhead']['Set-Cookie'];
//$tmp = curl_request($shareurl, false, [], 1);
//$tmp['body'] .= json_encode($tmp['returnhead'],JSON_PRETTY_PRINT);
//return $tmp;
//$_SERVER['sharecookie'] = $tmp['returnhead']['Set-Cookie'];
//if ($tmp['stat']==302) $url = $tmp['returnhead']['Location'];
//return curl('GET', $url, [ 'Accept' => 'application/json;odata=verbose', 'Content-Type' => 'application/json;odata=verbose', 'Cookie' => $_SERVER['sharecookie'] ]);
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_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));
$response['body'] = json_encode(json_decode($response['body']), JSON_PRETTY_PRINT);
$response['body'] .= '\nfailed to get shareurl access_token.';
return $response;
//throw new Exception($response['stat'].', failed to get share access_token.'.$response['body']);
}
//$tmp = $ret;
//$tmp['access_token'] = '******';
//error_log('['.$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);
}
return $this->access_token;
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
if (!class_exists('Onedrive')) require 'Onedrive.php';
class Sharepoint extends Onedrive {
function __construct($tag) {
$this->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 = ':EK[e0/4vQ@mQgma8LmnWb6j4_C1CSIW';
}
$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 offline_access';
$this->access_token = getcache('access_token', $tag);
if (!$this->access_token) $this->access_token = $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';
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
if (!class_exists('Onedrive')) require 'Onedrive.php';
class SharepointCN extends Onedrive {
function __construct($tag) {
$this->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 offline_access';
$this->access_token = getcache('access_token', $tag);
if (!$this->access_token) $this->access_token = $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';
}
}