-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.lib.php
208 lines (195 loc) · 6.37 KB
/
reader.lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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
<?php
require_once "config.php";
global $CONFIG, $GOOGLE;
// Google Drive API v3 - https://developers.google.com/drive/v3/web/quickstart/php
require_once __DIR__ . '/vendor/autoload.php';
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE,
Google_Service_Drive::DRIVE_METADATA_READONLY,
Google_Service_Drive::DRIVE_READONLY,
Google_Service_Drive::DRIVE_FILE
)));
function readGoogleToken($client) {
global $CONFIG,$MANAGER_MODE;
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
if (php_sapi_name() == 'cli') {
// cli mode (command line mode)
print "Google Auth";
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
} else {
// web mode (html mode)
if (empty($MANAGER_MODE))
return false;
$now1 = floor(time() / 60);
$now2 = 1 + $now1;
$prefix = 'verificationcode';
if (empty($_POST["$prefix-$now1"]) && empty($_POST["$prefix-$now2"])) {
echo "<h1>Google Auth</h1>";
echo "Open the following link: <A target=_blank href='$authUrl'>$authUrl</a><br>";
echo "<form method=POST><label>Enter verification code: <input name='$prefix-$now2'></label><input type=submit value=Go></form>";
return false;
} else {
$authCode = @$_POST["$prefix-$now1"] ?: @$_POST["$prefix-$now2"];
}
}
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
if (! empty($accessToken['error'])) {
log("Google Token Error: " . $accessToken['error']);
return false;
} else {
return $accessToken;
}
}
/**
* Returns an authorized API client.
*
* @return Google_Client the authorized client object
*/
function getGoogleClient() {
global $CONFIG;
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$accessToken = readGoogleToken($client);
if ($accessToken) {
// Store the credentials to disk.
if (! file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0777, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
chmod($credentialsPath, 0777);
}
}
if ($accessToken) {
$client->setAccessToken($accessToken);
// handle refresh token
if (! file_exists(REFRESH_TOKEN_PATH)) {
$refreshToken = $client->getRefreshToken();
if ($refreshToken) {
file_put_contents(REFRESH_TOKEN_PATH, json_encode($refreshToken));
chmod(REFRESH_TOKEN_PATH, 0777);
} else {
mylog("Google Auth Error: client->getRefreshToken() returned empty result");
}
}
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
if (file_exists(REFRESH_TOKEN_PATH)) {
$refreshToken = json_decode(file_get_contents(REFRESH_TOKEN_PATH));
$client->fetchAccessTokenWithRefreshToken($refreshToken);
$accessToken = $client->getAccessToken();
if ($accessToken) {
file_put_contents($credentialsPath, json_encode($accessToken));
chmod($credentialsPath, 0777);
} else {
mylog("Google Auth Error: client->fetchAccessTokenWithRefreshToken() called, getAccessToken() returned empty result");
}
} else {
if (file_exists($credentialsPath)) {
unlink($credentialsPath);
return getGoogleClient();
} else {
mylog("Google Auth Error: no refresh token");
return false;
}
}
$refreshToken = $client->getRefreshToken();
if ($refreshToken) {
$client->fetchAccessTokenWithRefreshToken($refreshToken);
} else {
mylog("Google Auth Error: client->getRefreshToken() returned empty result");
}
}
return $client;
} else {
return false;
}
}
/**
* Expands the home directory alias '~' to the full path.
*
* @param string $path
* the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$GOOGLE = array();
$GOOGLE['client'] = getGoogleClient();
if (empty($GOOGLE['client'])) {
exit();
}
$GOOGLE['service'] = new Google_Service_Drive($GOOGLE['client']);
function get_files($q = '',$optParams = null) {
global $CONFIG, $GOOGLE;
// Get the names and IDs of all files
if ($optParams === null)
$optParams = $CONFIG["list"];
if (! empty($q)) {
if ($optParams['q'])
$optParams['q'] .= " AND ";
$optParams['q'].="($q)";
}
return retrieveAllFiles($GOOGLE['service'],$optParams,$CONFIG["max_results"]);
}
function get_file_as($id, $mime = 'text/html') {
global $CONFIG, $GOOGLE;
// $id = $file->getId();
$optParams = array(
"fileId" => $id,
"mimeType" => $mime
);
$results = $GOOGLE['service']->files->export($id, $mime);
return $results;
}
/**
* Retrieve a list of File resources.
* from: https://developers.google.com/drive/v2/reference/files/list
*
* @param Google_Service_Drive $service Drive API service instance.
* @param Google_Service_Drive $parameters Drive API options.
* @param Google_Service_Drive $max_results Read pages up to this amount of results.
* @return Array List of Google_Service_Drive_DriveFile resources.
*/
function retrieveAllFiles($service, $parameters = array(), $max_results = 1000) {
$result = array();
$pageToken = NULL;
if (isset($parameters['q']) && stripos($parameters['q'],'fullText contains')!==false){
// google does not support orderBy when there's a fullText search going on
unset($parameters['orderBy']);
}
do {
try {
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getFiles());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
mylog("retrieveAllFiles error: " . $e->getMessage());
$pageToken = NULL;
}
} while ($pageToken && count($result)<$max_results);
return $result;
}