-
Notifications
You must be signed in to change notification settings - Fork 7
/
GoogleDriveApi.php
359 lines (332 loc) · 9.84 KB
/
GoogleDriveApi.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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<?php
require __DIR__.'/vendor/autoload.php';
require __DIR__.'/Token.php';
/**
* Class that operates with google drive api
* At first create and download your creadentials here: https://console.developers.google.com/apis/credentials
* Set "Authorized redirect URIs" as the redirect URI
*
* @author ondrej-maxa
* @version 1.0.0
*/
class GoogleDriveApi
{
/**
* Email of logged user.
*
* @var string
*/
private $email;
/**
* Your google drive client.
*
* @var Google_Client
*/
private $client;
/**
* Client's token.
*
* @var Token
*/
private $token;
/**
* Service that operates with google drive.
*
* @var Google_Service_Drive
*/
private $service;
/**
* Owner permission.
*
* @var Google_Service_Drive_Permission
*/
private $ownerPermission;
/**
* Path to your credentials.
*
* @var string
*/
private $pathToCredentials;
/**
* Email that will be set as an owner of all files
*
* @final string
*/
const OWNER_EMAIL = "";
/**
* Emails, that are allowed as owner
*
* @final array
*/
const VERIFIED_EMAILS = array();
/**
* Id of root directory.
*/
const ROOT_DIR = "root";
/**
* Constructor of this class
*
* @param string $pathToCredentials This is the path to downloaded credentials
*/
public function __construct($pathToCredentials)
{
$this->pathToCredentials = $pathToCredentials;
$this->initClient();
$this->token = new Token($this->client);
$this->service = new Google_Service_Drive($this->client);
$this->email = $this->getUsersEmail();
$this->ownerPermission = new Google_Service_Drive_Permission(array(
'type' => 'user',
'role' => 'owner',
'emailAddress' => self::OWNER_EMAIL
));
}
/**
* Getter of $email
*
* @return string Email of logged user.
*/
public function getEmail()
{
return $this->email;
}
/**
* Method that logs you out from google drive
*/
public function logOut()
{
$this->token->reset();
}
/**
* List all files that are associated with your account.
*
* @param string $fields Fields of files.
* @return array Array of all files.
*/
public function listFiles($fields = "files(id, name, owners)")
{
$result = array();
$pageToken = null;
do {
$parameters = array(
"fields" => "nextPageToken, $fields"
);
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $this->service->files->listFiles($parameters);
$result = array_merge($result, $files->getFiles());
try {
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: ".$e->getMessage();
$pageToken = null;
}
} while ($pageToken);
return $result;
}
/**
* Creates new folder
*
* @param string $name
* @param string $parentId
* @return string Id of created folder
*/
public function createFolder($name, $parentId = ROOT_DIR)
{
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $name,
'mimeType' => 'application/vnd.google-apps.folder',
'parents' => array($parentId)
));
$file = $this->service->files->create($fileMetadata,
array(
'fields' => 'id'));
return $file['id'];
}
/**
* Creates new file
*
* @param string $fullName Full name of file ex. document1.docx
* @param string $mimeType Mime type ex. image/png
* @param string $fullPath Path to file
* @param string $parentId Id of parent to be uploaded
* @return string
*/
public function uploadFile($fullName, $mimeType, $fullPath,
$parentId = ROOT_DIR)
{
$content = file_get_contents($fullPath);
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $fullName,
'parents' => array($parentId)
));
$file = $this->service->files->create($fileMetadata,
array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'
));
return $file['id'];
}
/**
* Creates new file
*
* @param string $name Name of file ex. document1
* @param string $type Type of file ex. image
* @param string $extension Extension of file ex. docx
* @param string $pathToFileDir Path to directory where the file is located ex. /path/to/directory
* @param string $parentId Id of parent to be uploaded
* @return string Id of created file
*/
public function uploadFileBasic($name, $type, $extension, $pathToFileDir,
$parentId = ROOT_DIR)
{
return $this->uploadFile("$name.$extension", "$type/$extension",
$pathToFileDir."/$name.$extension", $parentId);
}
/**
* Creates new empty file
*
* @param string $name Name of file ex. document1
* @param string $type Type of file ex. image
* @param string $extension Extension of file ex. docx
* @param string $parentId Id of parent to be uploaded
* @return string Id of created file
*/
public function createFile($fullName, $mimeType, $parentId = ROOT_DIR)
{
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $fullName,
'parents' => array($parentId)
));
$file = $this->service->files->create($fileMetadata,
array(
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'
));
return $file['id'];
}
/**
* Creates new file
*
* @param string $name Name of file ex. document1
* @param string $type Type of file ex. image
* @param string $extension Extension of file ex. docx
* @param string $parentId Id of parent to be uploaded
* @return string Id of created file
*/
public function createFileBasic($name, $type, $extension,
$parentId = ROOT_DIR)
{
return $this->createFile("$name.$extension", "$type/$extension",
$parentId);
}
/**
* Moves file to another folder
*
* @param string $fileId File to be move
* @param string $folderId Final folder
*/
public function moveFile($fileId, $folderId)
{
$emptyFileMetadata = new Google_Service_Drive_DriveFile();
$file = $this->service->files->get($fileId,
array('fields' => 'parents'));
$previousParents = join(',', $file->parents);
$this->service->files->update($fileId, $emptyFileMetadata,
array(
'addParents' => $folderId,
'removeParents' => $previousParents,
'fields' => 'id, parents'));
}
/**
* Downloads file content
*
* @param string $fileId
* @return file_content
*/
public function downloadFile($fileId)
{
$response = $this->service->files->get($fileId,
array(
'alt' => 'media'));
$content = $response->getBody()->getContents();
return $content;
}
/**
* List all files that aren't owned by allowed users.
*
* @return array $filesInDanger Array of files in danger.
*/
public function testFilesOwners()
{
$files = $this->listFiles();
$filesInDanger = array();
foreach ($files as $file) {
foreach ($file['owners'] as $owner) {
if (in_array($owner['emailAddress'], self::VERIFIED_EMAILS)) {
continue;
}
array_push($filesInDanger, $file);
}
}
return $filesInDanger;
}
/**
* Set owner of files with $ids to allowed owner.
*
* @param array $ids Ids of files to be changed.
*/
public function setVerifiedOwner($ids)
{
$files = $this->getFilesByIds($ids);
foreach ($files as $file) {
$this->service->permissions->create(
$file['id'], $this->ownerPermission,
array('transferOwnership' => 'true')
);
}
}
/**
* Lists all files with $ids.
*
* @param array $ids Ids of files to be listed.
* @return array $filesToBeReturned Files with id same as in $ids.
*/
private function getFilesByIds($ids)
{
$files = $this->listFiles("files(id, name, permissions)");
$filesToBeReturned = array();
foreach ($files as $file) {
if (in_array($file['id'], $ids)) {
array_push($filesToBeReturned, $file);
}
}
return $filesToBeReturned;
}
/**
* Gets email of logged user.
*
* @return string $email Email of logged user.
*/
private function getUsersEmail()
{
$about = $this->service->about->get(array("fields" => "user"));
return $about->getUser()['emailAddress'];
}
/**
* Inits Google Client
*/
private function initClient()
{
$this->client = new Google_Client();
$this->client->setApplicationName('Google Drive API');
$this->client->setScopes(Google_Service_Drive::DRIVE);
$this->client->setAuthConfig($this->pathToCredentials);
$this->client->setAccessType('offline');
$this->client->setPrompt('select_account consent');
}
}