-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlib.php
2861 lines (2677 loc) · 132 KB
/
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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/repository/lib.php');
require_once($CFG->libdir . '/google/lib.php');
/**
* Google Drive Plugin
*
* @since Moodle 2.0
* @package repository_googledrive
* @copyright 2009 Dan Poltawski <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class repository_googledrive extends repository {
/**
* Google Client.
* @var Google_Client
*/
private $client = null;
/**
* Google Drive Service.
* @var Google_Drive_Service
*/
private $service = null;
/**
* Session key to store the accesstoken.
* @var string
*/
const SESSIONKEY = 'googledrive_accesstoken';
/**
* URI to the callback file for OAuth.
* @var string
*/
const CALLBACKURL = '/admin/oauth2callback.php';
/**
* Return file types for repository.
*
* @var array
*/
private static $googlelivedrivetypes = array('document', 'presentation', 'spreadsheet');
/**
* Constructor.
*
* @param int $repositoryid repository instance id.
* @param int|stdClass $context a context id or context object.
* @param array $options repository options.
* @param int $readonly indicate this repo is readonly or not.
* @return void
*/
public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
parent::__construct($repositoryid, $context, $options, $readonly = 0);
$callbackurl = new moodle_url(self::CALLBACKURL);
$this->client = get_google_client();
$this->client->setAccessType("offline");
$this->client->setClientId(get_config('googledrive', 'clientid'));
$this->client->setClientSecret(get_config('googledrive', 'secret'));
$this->client->setScopes(array(Google_Service_Drive::DRIVE_FILE, Google_Service_Drive::DRIVE, 'email'));
$this->client->setRedirectUri($callbackurl->out(false));
$this->service = new Google_Service_Drive($this->client);
$this->check_login();
}
/**
* Returns the access token if any.
*
* @return string|null access token.
*/
protected function get_access_token() {
global $SESSION;
if (isset($SESSION->{self::SESSIONKEY})) {
return $SESSION->{self::SESSIONKEY};
}
return null;
}
/**
* Store the access token in the session.
*
* @param string $token token to store.
* @return void
*/
protected function store_access_token($token) {
global $SESSION;
$SESSION->{self::SESSIONKEY} = $token;
}
/**
* Callback method during authentication.
*
* @return void
*/
public function callback() {
if ($code = optional_param('oauth2code', null, PARAM_RAW)) {
$this->client->authenticate($code);
$this->store_access_token($this->client->getAccessToken());
$this->save_refresh_token();
} else if ($revoke = optional_param('revoke', null, PARAM_RAW)) {
$this->revoke_token();
}
if (optional_param('reloadparentpage', null, PARAM_RAW)) {
$url = new moodle_url('/repository/googledrive/callback.php');
redirect($url);
}
}
/**
* Checks whether the user is authenticated or not.
*
* @return bool true when logged in.
*/
public function check_login() {
global $USER, $DB;
$googlerefreshtokens = $DB->get_record('repository_gdrive_tokens', array ('userid' => $USER->id));
if ($googlerefreshtokens && !is_null($googlerefreshtokens->refreshtokenid)) {
try {
$this->client->refreshToken($googlerefreshtokens->refreshtokenid);
} catch (Exception $e) {
$this->revoke_token();
}
$token = $this->client->getAccessToken();
$this->store_access_token($token);
return true;
}
return false;
}
/**
* Return the revoke form.
*
*/
public function get_revoke_url() {
$url = new moodle_url('/repository/repository_callback.php');
$url->param('callback', 'yes');
$url->param('repo_id', $this->id);
$url->param('revoke', 'yes');
$url->param('reloadparentpage', true);
$url->param('sesskey', sesskey());
return '<a target="_blank" href="'.$url->out(false).'">'.get_string('revokeyourgoogleaccount', 'repository_googledrive').'</a>';
}
/**
* Return the login form.
*
* @return void|array for ajax.
*/
public function get_login_url() {
$returnurl = new moodle_url('/repository/repository_callback.php');
$returnurl->param('callback', 'yes');
$returnurl->param('repo_id', $this->id);
$returnurl->param('sesskey', sesskey());
$returnurl->param('reloadparentpage', true);
$url = new moodle_url($this->client->createAuthUrl());
$url->param('state', $returnurl->out_as_local_url(false));
return '<a target="repo_auth" href="'.$url->out(false).'">'.get_string('connectyourgoogleaccount', 'repository_googledrive').'</a>';
}
/**
* Print or return the login form.
*
* @return void|array for ajax.
*/
public function print_login() {
$returnurl = new moodle_url('/repository/repository_callback.php');
$returnurl->param('callback', 'yes');
$returnurl->param('repo_id', $this->id);
$returnurl->param('sesskey', sesskey());
$url = new moodle_url($this->client->createAuthUrl());
$url->param('state', $returnurl->out_as_local_url(false));
if ($this->options['ajax']) {
$popup = new stdClass();
$popup->type = 'popup';
$popup->url = $url->out(false);
return array('login' => array($popup));
} else {
echo '<a target="_blank" href="'.$url->out(false).'">'.get_string('login', 'repository').'</a>';
}
}
/**
* Build the breadcrumb from a path.
*
* @param string $path to create a breadcrumb from.
* @return array containing name and path of each crumb.
*/
protected function build_breadcrumb($path) {
$bread = explode('/', $path);
$crumbtrail = '';
foreach ($bread as $crumb) {
list($id, $name) = $this->explode_node_path($crumb);
$name = empty($name) ? $id : $name;
$breadcrumb[] = array(
'name' => $name,
'path' => $this->build_node_path($id, $name, $crumbtrail)
);
$tmp = end($breadcrumb);
$crumbtrail = $tmp['path'];
}
return $breadcrumb;
}
/**
* Generates a safe path to a node.
*
* Typically, a node will be id|Name of the node.
*
* @param string $id of the node.
* @param string $name of the node, will be URL encoded.
* @param string $root to append the node on, must be a result of this function.
* @return string path to the node.
*/
protected function build_node_path($id, $name = '', $root = '') {
$path = $id;
if (!empty($name)) {
$path .= '|' . urlencode($name);
}
if (!empty($root)) {
$path = trim($root, '/') . '/' . $path;
}
return $path;
}
/**
* Returns information about a node in a path.
*
* @see self::build_node_path()
* @param string $node to extrat information from.
* @return array about the node.
*/
protected function explode_node_path($node) {
if (strpos($node, '|') !== false) {
list($id, $name) = explode('|', $node, 2);
$name = urldecode($name);
} else {
$id = $node;
$name = '';
}
$id = urldecode($id);
return array(
0 => $id,
1 => $name,
'id' => $id,
'name' => $name
);
}
/**
* List the files and folders.
*
* @param string $path path to browse.
* @param string $page page to browse.
* @return array of result.
*/
public function get_listing($path='', $page = '') {
if (empty($path)) {
$path = $this->build_node_path('root', get_string('pluginname', 'repository_googledrive'));
}
// We analyse the path to extract what to browse.
$trail = explode('/', $path);
$uri = array_pop($trail);
list($id, $name) = $this->explode_node_path($uri);
// Handle the special keyword 'search', which we defined in self::search() so that
// we could set up a breadcrumb in the search results. In any other case ID would be
// 'root' which is a special keyword set up by Google, or a parent (folder) ID.
if ($id === 'search') {
return $this->search($name);
}
// Query the Drive.
$q = "'" . str_replace("'", "\'", $id) . "' in parents";
$q .= ' AND trashed = false';
$results = $this->query($q, $path);
$ret = array();
$ret['dynload'] = true;
$ret['path'] = $this->build_breadcrumb($path);
$ret['list'] = $results;
return $ret;
}
/**
* Search throughout the Google Drive.
*
* @param string $searchtext text to search for.
* @param int $page search page.
* @return array of results.
*/
public function search($searchtext, $page = 0) {
$path = $this->build_node_path('root', get_string('pluginname', 'repository_googledrive'));
$path = $this->build_node_path('search', $searchtext, $path);
// Query the Drive.
$q = "fullText contains '" . str_replace("'", "\'", $searchtext) . "'";
$q .= ' AND trashed = false';
$results = $this->query($q, $path);
$ret = array();
$ret['dynload'] = true;
$ret['path'] = $this->build_breadcrumb($path);
$ret['list'] = $results;
return $ret;
}
/**
* Query Google Drive for files and folders using a search query.
*
* Documentation about the query format can be found here:
* https://developers.google.com/drive/search-parameters
*
* This returns a list of files and folders with their details as they should be
* formatted and returned by functions such as get_listing() or search().
*
* @param string $q search query as expected by the Google API.
* @param string $path parent path of the current files, will not be used for the query.
* @param int $page page.
* @return array of files and folders.
*/
protected function query($q, $path = null, $page = 0) {
global $OUTPUT;
$files = array();
$folders = array();
$fields = "items(id,title,mimeType,downloadurl,fileExtension,exportLinks,modifiedDate,fileSize,thumbnailLink,alternateLink)";
$params = array('q' => $q, 'fields' => $fields);
try {
// Retrieving files and folders.
$response = $this->service->files->listFiles($params);
} catch (Google_Service_Exception $e) {
if ($e->getCode() == 403 && strpos($e->getMessage(), 'Access Not Configured') !== false) {
// This is raised when the service Drive API has not been enabled on Google APIs control panel.
throw new repository_exception('servicenotenabled', 'repository_googledrive');
} else {
throw $e;
}
}
$items = isset($response['items']) ? $response['items'] : array();
foreach ($items as $item) {
if ($item['mimeType'] == 'application/vnd.google-apps.folder') {
// This is a folder.
$folders[$item['title'] . $item['id']] = array(
'title' => $item['title'],
'path' => $this->build_node_path($item['id'], $item['title'], $path),
'date' => strtotime($item['modifiedDate']),
'thumbnail' => $OUTPUT->pix_url(file_folder_icon(64))->out(false),
'thumbnail_height' => 64,
'thumbnail_width' => 64,
'children' => array()
);
} else {
// This is a file.
if (isset($item['fileExtension'])) {
// The file has an extension, therefore there is a download link.
$title = $item['title'];
$source = $item['downloadurl'];
} else {
// The file is probably a Google Doc file, we get the corresponding export link.
// This should be improved by allowing the user to select the type of export they'd like.
$type = str_replace('application/vnd.google-apps.', '', $item['mimeType']);
$title = '';
$exporttype = '';
switch ($type){
case 'document':
$title = $item['title'] . '.rtf';
$exporttype = 'application/rtf';
break;
case 'presentation':
$title = $item['title'] . '.pptx';
$exporttype = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
break;
case 'spreadsheet':
$title = $item['title'] . '.csv';
$exporttype = 'text/csv';
break;
}
// Skips invalid/unknown types.
if (empty($title) || !isset($item['exportLinks'][$exporttype])) {
continue;
}
$source = $item['exportLinks'][$exporttype];
}
// Adds the file to the file list. Using the itemId along with the title as key
// of the array because Google Drive allows files with identical names.
$files[$title . $item['id']] = array(
'title' => $title,
'source' => $item['id'],
'date' => strtotime($item['modifiedDate']),
'size' => isset($item['fileSize']) ? $item['fileSize'] : null,
'thumbnail' => $OUTPUT->pix_url(file_extension_icon($title, 64))->out(false),
'thumbnail_height' => 64,
'thumbnail_width' => 64,
// Do not use real thumbnails as they wouldn't work if the user disabled 3rd party
// plugins in his browser, or if they're not logged in their Google account.
);
// Sometimes the real thumbnails can't be displayed, for example if 3rd party cookies are disabled
// or if the user is not logged in Google anymore. But this restriction does not seem to be applied
// to a small subset of files.
$extension = strtolower(pathinfo($title, PATHINFO_EXTENSION));
if (isset($item['thumbnailLink']) && in_array($extension, array('jpg', 'png', 'txt', 'pdf'))) {
$files[$title . $item['id']]['realthumbnail'] = $item['thumbnailLink'];
}
}
}
// Filter and order the results.
$files = array_filter($files, array($this, 'filter'));
core_collator::ksort($files, core_collator::SORT_NATURAL);
core_collator::ksort($folders, core_collator::SORT_NATURAL);
return array_merge(array_values($folders), array_values($files));
}
/**
* Logout.
*
* @return string
*/
public function logout() {
$this->store_access_token(null);
return parent::logout();
}
/**
* Get a file.
*
* @param string $reference reference of the file.
* @param string $file name to save the file to.
* @return string JSON encoded array of information about the file.
*/
public function get_file($source, $filename = '') {
global $USER, $CFG;
$url = $this->get_doc_url_by_doc_id($source, $downloadurl = true);
$auth = $this->client->getAuth();
$request = $auth->authenticatedRequest(new Google_Http_Request($url));
if ($request->getResponseHttpCode() == 200) {
$path = $this->prepare_file($filename);
$content = $request->getResponseBody();
if (file_put_contents($path, $content) !== false) {
@chmod($path, $CFG->filepermissions);
return array(
'path' => $path,
'url' => $url
);
}
}
throw new repository_exception('cannotdownload', 'repository');
}
/**
* Return external link.
*
* @param string $ref of the file.
* @return string document url.
*/
public function get_link($ref) {
return $this->service->files->get($ref)->alternateLink;
}
/**
* What kind of files will be in this repository?
*
* @return array return '*' means this repository support any files, otherwise
* return mimetypes of files, it can be an array
*/
public function supported_filetypes() {
return '*';
}
/**
* Tells how the file can be picked from this repository.
*
* Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE.
*
* @return int
*/
public function supported_returntypes() {
global $PAGE;
if ($PAGE->bodyid == 'page-mod-resource-mod') {
return FILE_INTERNAL | FILE_REFERENCE;
} else {
return FILE_INTERNAL;
}
}
/**
* Repository method to serve the referenced file.
*
* @param stored_file $storedfile the file that contains the reference
* @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
* @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
* @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
* @param array $options additional options affecting the file serving
*/
public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
$id = $storedfile->get_reference();
$token = json_decode($this->get_access_token());
header('Authorization: Bearer ' . $token->access_token);
if ($forcedownload) {
$downloadurl = true;
$url = $this->get_doc_url_by_doc_id($id, $downloadurl);
header('Location: ' . $url);
die;
} else {
$file = $this->service->files->get($id);
$type = str_replace('application/vnd.google-apps.', '', $file['mimeType']);
if (in_array($type, self::$googlelivedrivetypes)) {
redirect($file->alternateLink);
} else {
header("Location: " . $file->downloadurl . '&access_token='. $token->access_token);
die;
}
}
}
/**
* Repository method to get the document url.
*
* @param unknown $id
* @param string $downloadurl
* @throws repository_exception
* @return string|unknown
*/
private function get_doc_url_by_doc_id($id, $downloadurl=false) {
$file = $this->service->files->get($id);
if (isset($file['fileExtension'])) {
if ($downloadurl) {
$token = json_decode($this->get_access_token());
return $file['downloadurl']. '&access_token='. $token->access_token;
} else {
return $file['webContentLink'];
}
} else {
// The file is probably a Google Doc file, we get the corresponding export link.
// This should be improved by allowing the user to select the type of export they'd like.
$type = str_replace('application/vnd.google-apps.', '', $file['mimeType']);
$exporttype = '';
switch ($type){
case 'document':
$exporttype = 'application/rtf';
break;
case 'presentation':
$exporttype = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
break;
case 'spreadsheet':
$exporttype = 'text/csv';
break;
}
// Skips invalid/unknown types.
if (!isset($file['exportLinks'][$exporttype])) {
throw new repository_exception('repositoryerror', 'repository', '', 'Uknown file type');
}
return $file['exportLinks'][$exporttype];
}
}
/**
* Return names of the general options.
* By default: no general option name.
*
* @return array
*/
public static function get_type_option_names() {
return array('clientid', 'secret', 'pluginname');
}
/**
* Edit/Create Admin Settings Moodle form.
*
* @param moodleform $mform Moodle form (passed by reference).
* @param string $classname repository class name.
*/
public static function type_config_form($mform, $classname = 'repository') {
$callbackurl = new moodle_url(self::CALLBACKURL);
$a = new stdClass;
$a->driveurl = get_docs_url('Google_OAuth_2.0_setup');
$a->callbackurl = $callbackurl->out(false);
$mform->addElement('static', null, '', get_string('oauthinfo', 'repository_googledrive', $a));
parent::type_config_form($mform);
$mform->addElement('text', 'clientid', get_string('clientid', 'repository_googledrive'));
$mform->setType('clientid', PARAM_RAW_TRIMMED);
$mform->addElement('text', 'secret', get_string('secret', 'repository_googledrive'));
$mform->setType('secret', PARAM_RAW_TRIMMED);
$strrequired = get_string('required');
$mform->addRule('clientid', $strrequired, 'required', null, 'client');
$mform->addRule('secret', $strrequired, 'required', null, 'client');
}
/**
* Accessor to native revokeToken method
*
*/
private function revoke_token() {
$this->delete_refresh_token();
$this->client->revokeToken();
$this->store_access_token(null);
}
/**
*
* @return stdclass user info.
*/
public function get_user_info() {
$serviceoauth2 = new Google_Service_Oauth2($this->client);
return $serviceoauth2->userinfo_v2_me->get();
}
/**
* Removes the refresh token from database.
*
*/
private function delete_refresh_token() {
global $DB, $USER;
$grt = $DB->get_record('repository_gdrive_tokens', array('userid' => $USER->id));
$event = \repository_googledrive\event\repository_gdrive_tokens_deleted::create_from_userid($USER->id);
$event->add_record_snapshot('repository_gdrive_tokens', $grt);
$event->trigger();
$DB->delete_records('repository_gdrive_tokens', array ('userid' => $USER->id));
}
/**
* Saves the refresh token to database.
*
*/
private function save_refresh_token() {
global $DB, $USER;
$newdata = new stdClass();
$newdata->refreshtokenid = $this->client->getRefreshToken();
$newdata->gmail = $this->get_user_info()->email;
if (!is_null($newdata->refreshtokenid) && !is_null($newdata->gmail)) {
$rectoken = $DB->get_record('repository_gdrive_tokens', array ('userid' => $USER->id));
if ($rectoken) {
$newdata->id = $rectoken->id;
if ($newdata->gmail === $rectoken->gmail) {
unset($newdata->gmail);
}
$DB->update_record('repository_gdrive_tokens', $newdata);
} else {
$newdata->userid = $USER->id;
$newdata->gmail_active = 1;
$DB->insert_record('repository_gdrive_tokens', $newdata);
}
}
$event = \repository_googledrive\event\repository_gdrive_tokens_created::create_from_userid($USER->id);
$event->trigger();
}
/**
* Sync google resource permissions based on various events.
*
* @param \core\event\* $event The event fired.
*/
public function manage_resources($event) {
global $DB;
switch($event->eventname) {
case '\core\event\course_category_updated':
$this->course_category_updated($event);
break;
case '\core\event\course_updated':
$this->course_updated($event);
break;
case '\core\event\course_content_deleted':
$this->course_content_deleted($event);
break;
case '\core\event\course_restored':
$this->course_restored($event);
break;
case '\core\event\course_section_updated':
$this->course_section_updated($event);
break;
case '\core\event\course_module_created':
$this->course_module_created($event);
break;
case '\core\event\course_module_updated':
$this->course_module_updated($event);
break;
case '\core\event\course_module_deleted':
$this->course_module_deleted($event);
break;
case '\tool_recyclebin\event\course_bin_item_restored':
$this->course_bin_item_restored($event);
break;
case '\core\event\role_assigned':
$this->role_assigned($event);
break;
case '\core\event\role_unassigned':
$this->role_unassigned($event);
break;
case '\core\event\role_capabilities_updated':
$this->role_capabilities_updated($event);
break;
case '\core\event\group_member_added':
case '\core\event\group_member_removed':
$this->group_member_added($event);
break;
case '\core\event\grouping_group_assigned':
case '\core\event\grouping_group_unassigned':
$this->grouping_group_assigned($event);
break;
case '\core\event\user_enrolment_created':
$this->user_enrolment_created($event);
break;
case '\core\event\user_enrolment_updated':
$this->user_enrolment_updated($event);
break;
case '\core\event\user_enrolment_deleted':
$this->user_enrolment_deleted($event);
break;
case '\core\event\user_deleted':
$this->user_deleted($event);
break;
case '\repository_googledrive\event\repository_gdrive_tokens_created':
break;
case '\repository_googledrive\event\repository_gdrive_tokens_deleted':
break;
default:
return false;
}
return true;
}
/**
* Update Google Drive reader permissions if category (and therefore course) visibility changed.
*
* @param string $event
*/
private function course_category_updated($event) {
global $DB;
$categoryid = $event->objectid;
$courses = $DB->get_records('course', array('category' => $categoryid), '', 'id, visible');
$insertcalls = array();
$deletecalls = array();
foreach ($courses as $course) {
$courseid = $course->id;
$coursecontext = context_course::instance($courseid);
$users = $this->get_google_authenticated_users($courseid);
$coursemodinfo = get_fast_modinfo($courseid, -1);
$cms = $coursemodinfo->get_cms();
foreach ($cms as $cm) {
$cmid = $cm->id;
$cmcontext = context_module::instance($cmid);
$fileids = $this->get_fileids($cmid);
if ($fileids) {
foreach ($fileids as $fileid) {
foreach ($users as $user) {
if (has_capability('moodle/course:view', $coursecontext, $user->userid)) {
// Manager; do nothing.
} elseif (is_enrolled($coursecontext, $user->userid, null, true) && has_capability('moodle/course:manageactivities', $cmcontext, $user->userid)) {
// Teacher (enrolled) (active); do nothing.
} elseif (is_enrolled($coursecontext, $user->userid, null, true)) {
// Student (enrolled) (active); continue checks.
if ($course->visible == 1) {
// Course is visible, continue checks.
rebuild_course_cache($courseid, true);
$modinfo = get_fast_modinfo($courseid, $user->userid);
$cminfo = $modinfo->get_cm($cmid);
$sectionnumber = $this->get_cm_sectionnum($cmid);
$secinfo = $modinfo->get_section_info($sectionnumber);
if ($cminfo->uservisible && $secinfo->available) {
// User can view and access course module and can access section; insert reader permission.
$call = new stdClass();
$call->fileid = $fileid;
$call->gmail = $user->gmail;
$call->role = 'reader';
$insertcalls[] = $call;
if (count($insertcalls) == 1000) {
$this->batch_insert_permissions($insertcalls);
$insertcalls = array();
}
}
// User cannot access course module, do nothing (course module availability won't change here).
} else {
// Course not visible, delete permission.
try {
$permissionid = $this->service->permissions->getIdForEmail($user->gmail);
$permission = $this->service->permissions->get($fileid, $permissionid->id);
if ($permission->role != 'owner') {
$call = new stdClass();
$call->fileid = $fileid;
$call->permissionid = $permissionid->id;
$deletecalls[] = $call;
if (count($deletecalls) == 1000) {
$this->batch_delete_permissions($deletecalls);
$deletecalls = array();
}
}
} catch (Exception $e) {
debugging($e);
}
}
} else {
// Unenrolled user; do nothing (user enrolment would not have changed during this event).
}
}
}
}
}
}
// Call any remaining batch requests.
if (count($insertcalls) > 0) {
$this->batch_insert_permissions($insertcalls);
}
if (count($deletecalls) > 0) {
$this->batch_delete_permissions($deletecalls);
}
}
/**
* Update Google Drive reader permissions if course visibility changed.
*
* @param string $event
*/
private function course_updated($event) {
global $DB;
$courseid = $event->courseid;
$course = $DB->get_record('course', array('id' => $courseid), 'visible');
$coursecontext = context_course::instance($courseid);
$coursemodinfo = get_fast_modinfo($courseid, -1);
$cms = $coursemodinfo->get_cms();
$users = $this->get_google_authenticated_users($courseid);
$insertcalls = array();
$deletecalls = array();
foreach ($cms as $cm) {
$cmid = $cm->id;
$cmcontext = context_module::instance($cmid);
$fileids = $this->get_fileids($cmid);
if ($fileids) {
foreach ($fileids as $fileid) {
foreach ($users as $user) {
if (has_capability('moodle/course:view', $coursecontext, $user->userid)) {
// Manager; do nothing.
} elseif (is_enrolled($coursecontext, $user->userid, null, true) && has_capability('moodle/course:manageactivities', $cmcontext, $user->userid)) {
// Teacher (enrolled) (active); do nothing.
} elseif (is_enrolled($coursecontext, $user->userid, null, true)) {
// Student (enrolled); continue checks for reader permissions.
if ($course->visible == 1) {
// Course is visible, continue checks.
rebuild_course_cache($courseid, true);
$modinfo = get_fast_modinfo($courseid, $user->userid);
$cminfo = $modinfo->get_cm($cmid);
$sectionnumber = $this->get_cm_sectionnum($cmid);
$secinfo = $modinfo->get_section_info($sectionnumber);
if ($cminfo->uservisible && $secinfo->available) {
// User can view and access course module and can access section; insert reader permission.
$call = new stdClass();
$call->fileid = $fileid;
$call->gmail = $user->gmail;
$call->role = 'reader';
$insertcalls[] = $call;
if (count($insertcalls) == 1000) {
$this->batch_insert_permissions($insertcalls);
$insertcalls = array();
}
}
// User cannot access course module, do nothing (course module availability won't change here).
} else {
// Course not visible, delete permission.
try {
$permissionid = $this->service->permissions->getIdForEmail($user->gmail);
$permission = $this->service->permissions->get($fileid, $permissionid->id);
if ($permission->role != 'owner') {
$call = new stdClass();
$call->fileid = $fileid;
$call->permissionid = $permissionid->id;
$deletecalls[] = $call;
if (count($deletecalls) == 1000) {
$this->batch_delete_permissions($deletecalls);
$deletecalls = array();
}
}
} catch (Exception $e) {
debugging($e);
}
}
}
// Unenrolled user; do nothing (user enrolment would not have changed during this event).
}
}
}
}
// Call any remaining batch requests.
if (count($insertcalls) > 0) {
$this->batch_insert_permissions($insertcalls);
}
if (count($deletecalls) > 0) {
$this->batch_delete_permissions($deletecalls);
}
}
/**
* Delete repository database table records when course is deleted.
* Permission deletes handled by user_enrolment_deleted.
*
* @param string $event
*/
private function course_content_deleted($event) {
global $DB;
$courseid = $event->courseid;
$DB->delete_records('repository_gdrive_references', array('courseid' => $courseid));
}
/**
* Insert Google Drive permissions when course is restored.
*
* @param string $event
*/
private function course_restored($event) {
global $DB;
$courseid = $event->courseid;
$course = $DB->get_record('course', array('id' => $courseid), 'visible');
$coursecontext = context_course::instance($courseid);
$siteadmins = $this->get_siteadmins();
$users = $this->get_google_authenticated_users($courseid);
$coursemodinfo = get_fast_modinfo($courseid, -1);
$cms = $coursemodinfo->get_cms();
$insertcalls = array();
$deletecalls = array();
foreach ($cms as $cm) {
$cmid = $cm->id;
$cmcontext = context_module::instance($cmid);
$fileids = $this->get_fileids($cmid);
if ($fileids) {
foreach ($fileids as $fileid) {
foreach ($users as $user) {
if (has_capability('moodle/course:view', $coursecontext, $user->userid)) {
// Manager; insert writer permission.
$call = new stdClass();
$call->fileid = $fileid;
$call->gmail = $user->gmail;
$call->role = 'writer';
$insertcalls[] = $call;
if (count($insertcalls) == 1000) {
$this->batch_insert_permissions($insertcalls);
$insertcalls = array();
}
} elseif (is_enrolled($coursecontext, $user->userid, null, true) && has_capability('moodle/course:manageactivities', $cmcontext, $user->userid)) {
// Enrolled teacher; insert writer permission.
$call = new stdClass();
$call->fileid = $fileid;
$call->gmail = $user->gmail;
$call->role = 'writer';
$insertcalls[] = $call;
if (count($insertcalls) == 1000) {
$this->batch_insert_permissions($insertcalls);
$insertcalls = array();
}
} elseif (is_enrolled($coursecontext, $user->userid, null, true)) {
// Enrolled student; continue checks for reader permission.
if ($course->visible == 1) {
// Course is visible, continue checks.
if ($cm->visible == 1) {
// Course module is visible, continue checks.
rebuild_course_cache($courseid, true);