/
lib.php
executable file
·1706 lines (1563 loc) · 75.8 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/>.
/**
* Morsle Plugin
*
* @since 2.2
* @package repository
* @subpackage googledocs
* @copyright since 2011 Bob Puffer puffro01@luther.edu
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once($CFG->libdir.'/googleapi.php');
require_once("$CFG->dirroot/repository/morsle/locallib.php");
require_once("$CFG->dirroot/repository/lib.php");
require_once("$CFG->dirroot/google/gauth.php");
require_once("$CFG->dirroot/google/lib.php");
require_once "$CFG->dirroot/google/google-api-php-client/src/Google/Service.php";
require_once "$CFG->dirroot/google/google-api-php-client/src/Google/Service/Resource.php";
require_once($CFG->dirroot.'/google/google-api-php-client/src/Google/Http/Batch.php');
require_once "$CFG->dirroot/google/google-api-php-client/src/Google/Service/Calendar.php";
require_once "$CFG->dirroot/google/google-api-php-client/src/Google/Service/Directory.php";
require_once "$CFG->dirroot/google/google-api-php-client/src/Google/Service/Drive.php";
require_once "$CFG->dirroot/google/google-api-php-client/src/Google/Client.php";
class repository_morsle extends repository {
private $subauthtoken = '';
public function __construct($repositoryid=9,$context = SYSCONTEXTID, $options = array(), $readonly=0) {
global $USER, $COURSE, $DB;
$this->repositoryid = $repositoryid;
$this->context = $context;
$this->options = $options;
$this->readonly = $readonly;
$this->useremail = $COURSE->shortname.'@luther.edu';
if ( !$this->domain = get_config('morsle','consumer_key')) {
throw new moodle_exception('Consumer key not set up');
}
parent::__construct($this->repositoryid, $this->context, $this->options, $this->readonly);
// days past last enrollment day that morsle resources are retained
$this->expires = get_config('morsle','morsle_expiration') == 0 ? 600 * 24 * 60 * 60: get_config('blocks/morsle','morsle_expiration') * 24 * 60 * 60;
$this->curtime = time();
// set basefeeds
$this->user_auth = "https://www.googleapis.com/auth/admin.directory.user";
$this->site_feed = "https://sites.google.com/feeds/site/$this->domain";
$this->drive_auth = 'https://www.googleapis.com/auth/drive ';
$this->file_auth = 'https://www.googleapis.com/auth/drive.file ';
$this->alias_feed = "https://apps-apis.google.com/a/feeds/alias/2.0/$this->domain/?start=aaaarnold@luther.edu";
$this->group_auth = 'https://www.googleapis.com/auth/admin.directory.group';
$this->id_feed = 'https://docs.google.com/feeds/id/';
$this->cal_auth = 'https://www.googleapis.com/auth/calendar';
$this->owncalendars_feed = 'https://www.google.com/calendar/feeds/default/owncalendars/full';
// skip marked for delete, unapproved and past term
$this->disregard = "'Past Term','DELETED'";
$this->setup_client();
}
function setup_client() {
$this->client = new Google_Client();
$this->client->addscope($this->cal_auth);
$this->client->addscope($this->drive_auth);
$this->client->addscope($this->file_auth);
$this->client->addscope($this->user_auth);
$this->client->addscope($this->group_auth);
}
function get_token($service_name) {
$this->setup_client();
$auth='';
switch($service_name) {
case 'calendar':
$auth = $this->cal_auth;
$this->service = new Google_Service_Calendar($this->client);
$this->auth = service_account($this->client, $this->useremail, $auth);
$this->revoke_token();
$this->auth = service_account($this->client, $this->useremail, $auth);
$this->update_timezone();
break;
case 'drive':
$auth = $this->drive_auth;
$this->service = new Google_Service_Drive($this->client);
$this->auth = service_account($this->client, $this->useremail, $auth);
$this->revoke_token();
$this->auth = service_account($this->client, $this->useremail, $auth);
break;
case 'file':
$auth = $this->drive_auth;
$this->service = new Google_Service_Drive_DriveFile($this->client);
$this->auth = service_account($this->client, $this->useremail, $auth);
$this->revoke_token();
$this->auth = service_account($this->client, $this->useremail, $auth);
break;
case 'user':
$auth = $this->user_auth;
$this->service = new Google_Service_Directory($this->client);
$this->user = new Google_Service_Directory_User();
$this->name = new Google_Service_Directory_UserName();
$this->auth = service_account($this->client, $this->useremail, $auth);
$this->revoke_token();
$this->auth = service_account($this->client, $this->useremail, $auth);
break;
case 'group':
$auth = $this->group_auth;
$this->service = new Google_Service_Directory($this->client);
$this->group = new Google_Service_Directory_Group();
$this->revoke_token();
$this->auth = service_account($this->client, $this->useremail, $auth);
break;
}
}
function revoke_token() {
$this->client->revokeToken($this->auth->access_token);
unset($this->client->auth);
unset($_SESSION['service_token']);
}
function update_timezone(){
$calendar = $this->service->calendars->get($this->useremail);
$calendar->setTimeZone('America/Chicago');
return $this->service->calendars->update($this->useremail,$calendar);
}
/*
* here's where the fun is going to start getting google docs for
* the course
* the user
* the department, if exists
*/
public function get_listing($path='', $page = '', $query = null) {
global $CFG, $USER, $OUTPUT, $COURSE, $DB;
require_once("$CFG->dirroot/google/constants.php");
require_once('course_constants.php');
require_once("$CFG->dirroot/blocks/morsle/morsle.php");
$ret = array();
$ret['dynload'] = true;
$user = build_user();
$course = $COURSE;
// $user = $USER->email; // TODO: uncomment
$useraccount = $USER->email;
$user = $useraccount;
$morsle = new morsle($user);
$deptstr = get_string('departmentaccountstring', 'repository_morsle');
// get departmental folder if exists
$shortname = is_number(substr($course->shortname,0,5)) ? substr($course->shortname, 6) : $course->shortname;
$morsleaccount = strtolower($course->shortname . '@' . $this->domain);
// SPLIT INTO DEPARTMENTAL CODES
$dept = explode("-",$shortname);
if (defined($dept[0])) {
$deptstr = CONSTANT($dept[0]) . $deptstr;
$deptshortstr = strtolower(substr($deptstr,0,6));
$deptaccount = strtolower($deptstr . '@' . $this->domain);
} else {
$deptstr = 'nodept';
$deptshortstr = 'nodept';
$deptaccount = 'nodept';
}
// get course level folders or documents
$maxfiles = get_config('morsle','maxfilesreturned');
// get a docid if available
$path = base64_decode($path);
if ($path == '') {
$root_path = null;
$pathleftover = null;
$search_path = null;
} elseif ($path == $deptstr) {
$root_path = $deptstr;
$pathleftover = null;
$search_path = null;
} elseif (strpos($path, '|')) {
list($docid,$pathleftover) = explode('|', $path);
$search_path = 'folder%3A' . $docid;
$root_path = strtolower(substr($pathleftover, 0, 6));
} else {
$root_path = strtolower(substr($path,0,6));
$pathleftover = $path;
$search_path = null;
}
// handle a search instance
if ($query !== null) {
$root_path = 'queryi';
}
switch ($root_path) {
case null: // empty: get only the readonly and writeable folders plus any files and user folder and (if available) department folder
$user = $morsleaccount;
$search = array(
'xoauth_requestor_id' => $user,
// 'foldersonly' => 'true', // identifies that we're just looking for the special morsle folders
'showfolders' => 'true',
'folder' => 'folder%3Aroot',
'max-results'=>$maxfiles
);
if ($search_path !== null) { // looking for another folder's contents
$search['folder'] = $search_path;
}
// $mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored
unset($search['repo_id']);
// $mdocs = new morsle_docs($mauth);
// get user level folders or documents
$user = $useraccount;
$title = get_string('useraccountstring', 'repository_morsle') . $user;
// $collectionid = get_collection($morsle, 'root');
$files = $this->get_doc_feed($morsle, 'root');
$ret['list'] = $this->get_file_list($files);
$url = DOCUMENTFEED_URL;
$ret['list'][] = array(
'title' => $title,
'url' => $url,
'source' => $url,
'children' => array(),
'path' => base64_encode('User Files'),
'thumbnail' => (string) $OUTPUT->pix_url('f/folder-64')
);
// 'date' => usertime(strtotime(time())),
// check to see if we even have a departmental account for this department but don't show the departmental collection if we're already in it indicated by $wdir
// TODO: this needs to change if we eliminate morsle table, but if the read-only or writeable folders get renamed then we need the table
// department account if exists
$conditions = " shortname = '$deptstr' ";
$user = $deptaccount;
$title = get_string('deptaccountstring', 'repository_morsle') . $user;
if (strpos($path,$deptstr) === false && $is_morsle_dept = $DB->get_record_select('morsle_active', $conditions)) {
$ret['list'][] = array(
'title' => $deptstr,
'url' => $url,
'source' => $url,
'date' => usertime(strtotime(time())),
'children' => array(),
'path' => base64_encode($deptstr),
'thumbnail' => (string) $OUTPUT->pix_url('f/folder-64')
);
}
$ret['path'][]['name'] = 'Morsle Files';
break;
case 'queryi':
case 'user f': // user account google files
$search = array(
'xoauth_requestor_id' => $user,
'path' => $pathleftover,
'showfolders' => 'true',
'repo_id'=>5,
'max-results'=>$maxfiles
);
if ($search_path !== null) { // looking for another folder's contents
$search['folder'] = $search_path;
}
if ($query !== null) {
$search['q'] = $query;
}
$mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored
unset($search['repo_id']);
$mdocs = new morsle_docs($mauth);
$ret['list'] = $mdocs->get_file_list($search, $this);
$ret['path'][]['name'] = $pathleftover;
break;
case '/': // TODO: what does this get
$search = array(
'xoauth_requestor_id' => $user,
'folder' => $search_path,
'repo_id'=>5,
'max-results'=>$maxfiles
);
$mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored
unset($search['repo_id']);
$mdocs = new morsle_docs($mauth);
$ret['list'] = $mdocs->get_file_list($search, $this);
break;
case $deptstr: // department account google files, if we got here it means department files exist
$user = $deptaccount;
$search = array(
'xoauth_requestor_id' => $user,
'path' => $pathleftover,
'showfolders' => 'true',
// 'foldersonly' => 'true', // identifies that we're just looking for the special morsle folders
'repo_id'=>5,
'max-results'=>$maxfiles
);
if ($search_path !== null) { // looking for another folder's contents
$search['folder'] = $search_path;
}
$mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored
unset($search['repo_id']);
$mdocs = new morsle_docs($mauth);
$ret['list'] = $mdocs->get_file_list($search, $this);
$ret['path'][]['name'] = $pathleftover;
break;
case 'morsle': // only way we'd get here is if the read-only or writeable folder got clicked
$user = $morsleaccount;
$search = array(
'xoauth_requestor_id' => $user,
'path' => 'Morsle Files',
'max-results'=>$maxfiles
);
if ($search_path !== null) { // looking for another folder's contents
$search['folder'] = $search_path;
}
$mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored
unset($search['repo_id']);
$mdocs = new morsle_docs($mauth);
$ret['list'] = $mdocs->get_file_list($search);
$ret['path'][]['name'] = $pathleftover;
break;
default: // empty: get only the readonly and writeable folders user folder and (if available) department folder
$user = $morsleaccount;
// list($title, $domain) = explode('@',$user);
$search = array(
'xoauth_requestor_id' => $user,
'showfolders' => 'true',
'max-results'=>$maxfiles
);
if ($search_path !== null) { // looking for another folder's contents
$search['folder'] = $search_path;
}
$mauth = new morsle_oauth_request(null, null, $search); // subauthtoken ignored
// unset($search['repo_id']);
$mdocs = new morsle_docs($mauth);
$ret['list'] = $mdocs->get_file_list($search, $this);
// check to see if we even have a departmental account for this department but don't show the departmental collection if we're already in it indicated by $wdir
// TODO: this needs to change if we eliminate morsle table
$conditions = " shortname = '$deptstr' ";
$user = $deptaccount;
$title = get_string('deptaccountstring', 'repository_morsle') . $user;
if (strpos($path,$deptstr) === false && $is_morsle_dept = $DB->get_record_select('morsle_active', $conditions)) {
$ret['list'][] = array(
'title' => $deptstr,
'url' => $url,
'source' => $url,
'date' => usertime(strtotime(time())),
'children' => array(),
'path' => base64_encode($deptstr),
'icon' => (string) $OUTPUT->pix_url('f/folder-64')
);
}
$ret['path'][]['name'] = 'Morsle Files';
}
return $ret;
}
public function get_file_list($getfiles){
// require_once('constants.php');
global $CFG, $OUTPUT;
/*
$url = get_morsle_url($search);
if (array_key_exists('path', $search)) {
$path = $search['path'] . '/';
unset($search['path']);
} else {
$path = null;
}
foreach ($search as $key=>$param) {
if ($key === 'q') {
$param = urlencode($param);
}
$params[$key] = trim($param);
}
*/
// $url .= '?' . implode_assoc('=', '&', $params);
// $content = twolegged($url, $params, 'GET');
// $content = $this->get($url, $params, null);
// $xml = new SimpleXMLElement($content->response);
// $files = array();
// $repolink = "$CFG->wwwroot/repository/repository_ajax.php?action=list&p=";
foreach($getfiles['modelData']['items'] as $gdoc){
// $docid = (string) $gdoc->children('http://schemas.google.com/g/2005')->resourceId;
// list($type, $docid) = explode(':', $docid);
// FIXME: We're making hard-coded choices about format here.
// If the repo api can support it, we could let the user
// chose.
/*
switch($gdoc->type){
case 'folder':
break;
case 'document':
$temptitle = 'temp.doc';
break;
case 'presentation':
$temptitle = 'temp.ppt';
break;
case 'spreadsheet':
$temptitle = 'temp.xls';
break;
case 'pdf':
$temptitle = 'temp.pdf';
break;
default:
$temptitle = $gdoc->title;
}
*/
// $source = (string) get_href_noentry($gdoc, GDOC_ALT_REL);
// TODO: get this thumbnail working with the display
// $iconlink = '<img src="' . (string) get_href_noentry($gdoc, GDOC_THUMB_REL) . '" />';
// if(!empty($source)){
if ($type == 'folder') {
echo null;
$files[] = array(
'title' => $gdoc['title'],
'url' => $gdoc['alternateLink'],
'source' => $gdoc['alternateLink'],
'date' => usertime(strtotime($gdoc['modifiedDate'])),
'thumbnail' => (string) $OUTPUT->pix_url($gdoc['iconLink'])
);
// 'children' => array(),
// 'path' => base64_encode($docid . '|' . $path . $title),
// 'page' => base64_encode($docid),
} else {
$files[] = array(
'title' => $gdoc['title'],
'url' => $gdoc['alternateLink'],
'source' => $$gdoc['alternateLink'],
// 'url' => "{$gdoc->link[0]->attributes()->href}",
// 'source' => "{$gdoc->link[0]->attributes()->href}",
'date' => usertime(strtotime($gdoc['modifiedDate'])),
'icon' => $gdoc['iconLink']
);
// 'thumbnail' => (string) $OUTPUT->pix_url($gdoc['thumbnailLink'])
}
// }
}
return $files;
}
function get_doc_feed($morsle, $collectionid, $max = 1000) {
$drive = new Google_Service_Drive($morsle->client);
$resource = $drive->files;
$searchtime = time() - (60*60*24*365*2);
$date = new DateTime(date('y-m-d', $searchtime));
$formatdate = $date->format("Y-m-d\TH:i:sP");
$files = $resource->listFiles(array("q" => "'$collectionid' in parents and trashed = false and modifiedDate > '$formatdate'", 'maxResults' => $max));
return $files;
}
// TODO: where's this getting called from? there's not much we need here, could also add in the parameters from get_listing instead of calling it
public function search($search_text, $page = 0) {
$list = $this->get_listing(null, $page, $search_text);
return $list;
}
public function get_file($url, $filename = '') {
global $CFG;
$path = $this->prepare_file($filename);
$fp = fopen($path, 'w');
$c = new curl;
$c->download(array(array('url'=>$url, 'file'=>$fp)));
// Close file handler.
fclose($fp);
return array('path'=>$path, 'url'=>$url);
}
public function get_link($encoded) {
return $encoded;
}
/**
* Defines operations that happen occasionally on cron
* @return boolean
*/
public function cron() {
global $CFG;
/// We are going to measure execution times
// set this up so it runs at your desired interval
srand ((double) microtime() * 10000000);
$random100 = rand(0,100);
if ($random100 < 10) { // Approximately every hour.
mtrace(date(DATE_ATOM) . " - Running m_cook...");
$status = $this->m_cook();
mtrace(date(DATE_ATOM) . " - Done m_cook: $status");
}
if ($random100 > 45 && $random100 < 55) { // Approximately every hour
mtrace(date(DATE_ATOM) . " - Running m_maintain...");
// $status = $this->m_maintain();
mtrace(date(DATE_ATOM) . " - Done m_maintain: $status");
}
if ($random100 > 90) { // Approximately every hour.
mtrace(date(DATE_ATOM) . " -Running m_digest...");
$status = $this->m_digest();
mtrace(date(DATE_ATOM) . " -Done m_digest: $status");
}
}
public function supported_returntypes() {
// return FILE_REFERENCE;
// return (FILE_INTERNAL | FILE_EXTERNAL);
return FILE_EXTERNAL;
}
/*
* Processes all current morsle_active records, creating or deleting components as necessary
* Any course that is current (mdl_course.startdate > now and is visible gets resources created (if not already done)
* Any course whose mdl_course.startdate + config.morsle_expiration (converted to seconds) < now gets its resources deleted
* Any course falling inbetween is ignored (we don't update courses beyond their startdate)
*/
function m_cook() {
// get all the morsle records that should be deleted
global $CFG, $DB;
$deletion_clause = " m.status NOT IN($this->disregard)
AND c.startdate + $this->expires < $this->curtime";
$sql = "SELECT m.*, c.startdate + $this->expires AS expire, c.id AS coursepresent from " . $CFG->prefix . "morsle_active m
LEFT JOIN " . $CFG->prefix . "course c on m.courseid = c.id
WHERE $deletion_clause
AND (m.readfolderid IS NOT NULL
OR m.writefolderid IS NOT NULL
OR m.groupname IS NOT NULL
OR m.password IS NOT NULL
OR m.siteid IS NOT NULL) "; // don't care to consider any records who've already been deleted
$this->deleterecs = $DB->get_records_sql($sql);
foreach ($this->deleterecs as $record) {
$this->user= $record->shortname . '@' . $this->domain;
$this->params = array('xoauth_requestor_id' => $this->user, 'delete' => 'true');
if ($status = $this->m_barf($record)) {
$record->status = 'DELETED';
$deleted = $DB->update_record(morsle_active, $record);
if (!$deleted) {
$this->log('RECORD NOT DELETED - FAILURE', $record->courseid);
} else {
$this->log('RECORD DELETED - SUCCESS', $record->courseid);
}
}
}
// CREATE OR COMPLETE CREATION OF CURRENT COURSES
/* sql criteria:
// course visible OR INVISIBLE
// c.enrolenddate > $curtime (for creation)
// one of the fields - password, readfolderid, writefolderid, groupname, siteid must be NULL (creation)
*/
$creation_clause = " m.status NOT IN($this->disregard)
AND ((c.startdate > $this->curtime - $this->expires) OR c.startdate = 0)
AND (m.readfolderid IS NULL OR m.writefolderid IS NULL OR m.groupname IS NULL OR m.siteid IS NULL)";
$sql = 'SELECT m.* from ' . $CFG->prefix . 'morsle_active m
JOIN ' . $CFG->prefix . 'course c on m.courseid = c.id
WHERE ' . $creation_clause;
$todigest = $DB->get_records_sql($sql);
// process each record
foreach ($todigest as $record) {
$this->user= $record->shortname . '@' . $this->domain;
$this->params = array('xoauth_requestor_id' => $this->user);
$status = $this->morsle_digest($record);
}
}
/*
* Add components to google for morsle_active record
* Checks condition of each item field in record and creates if not present
*/
public function morsle_digest($record) {
global $success, $CFG, $DB;
$this->shortname = strtolower($record->shortname);
$this->courseid = $record->courseid;
$groupname = $this->shortname . '-group';
$groupfullname = $groupname . '@' . $this->domain;
$this->sitename = urlencode('Course Site for ' . strtoupper($this->shortname));
$stats = array(
'password' => $record->password,
'groupname' => $record->groupname,
'readfolderid' => $record->readfolderid,
'writefolderid' => $record->writefolderid,
'siteid' => $record->siteid
);
foreach ($stats as $key=>$stat) {
if (is_null($stat)) {
switch ($key) {
case 'password': // create user account
$this->useremail = 'admin-moogle@luther.edu';
// $this->get_token('user');
$this->revoke_token();
$this->get_token('user');
$returnval = $this->useradd(); // either password coming back or $response->response
break;
case 'groupname': // add group
$this->useremail = 'admin-moogle@luther.edu';
$this->get_token('group');
$this->revoke_token();
$this->get_token('group');
$returnval = $this->groupadd($groupname);
break;
case 'readfolderid': // create readonly folder
$this->useremail = $this->shortname . '@luther.edu';
$this->get_token('drive');
$this->revoke_token();
$this->get_token('drive');
$returnval = createcollection($this, $this->shortname . '-read');
break;
case 'writefolderid': // create writeable folder
$this->useremail = $this->shortname . '@luther.edu';
$this->get_token('drive');
$this->revoke_token();
$this->get_token('drive');
$returnval = createcollection($this, $this->shortname . '-write');
break;
case 'siteid': // create site
// $returnval = $this->createsite();
break;
}
if ($returnval !== null) {
$this->log('added ' . $key . " SUCCESS", $record->courseid, null, s($returnval));
$record->$key = s($returnval);
$updaterec = $DB->update_record('morsle_active', $record);
} else {
$this->log('added ' . $key . " FAILURE", $record->courseid, null, s($returnval));
if ($key == 'password') {
// break;
}
}
}
}
return $returnval;
}
// checks condition of each item field in record (stats) and deletes if present
public function m_barf($record) {
global $success, $DB;
// we're deleting because the course has expired
$stats = array(
'user' => $record->password,
'group' => $record->groupname,
'readonly folder' => $record->readfolderid,
'writeable folder' => $record->writefolderid
);
$stats = array_reverse($stats, true);
foreach ($stats as $key=>$stat) {
if (!is_null($stat)) {
$status = $key;
switch ($key) {
// sites not deleteable through API yet
case 'site': // create site
// $siteid = sitedelete($shortname, $record, $user, $this->domain);
// $record->siteid = null;
// $writeassigned = sitepermissions($shortname, $record, $groupfullname, $courseid, $this->domain);
break;
case 'writeable folder': // delete writeable folder
$this->get_token('drive');
$this->revoke_token();
$this->get_token('drive');
$return = $this->service->files->delete($stat);
$record->writefolderid = null;
break;
case 'readonly folder': // delete readonly folder
$this->get_token('drive');
$this->revoke_token();
$this->get_token('drive');
$return = $this->service->files->delete($stat);
$record->readfolderid = null;
break;
case 'group': // delete group
$this->get_token('drive');
$this->revoke_token();
$this->get_token('group');
$return = $this->service->groups->delete($stat);
$record->groupname = null;
break;
case 'user': // delete user account
$this->get_token('user');
$this->revoke_token();
$this->get_token('user');
$primaryEmail = $this->shortname . '@luther.edu';
$return = $this->service->users->delete($primaryEmail);
$record->password = null;
break;
}
if ($success) {
$updaterec = $DB->update_record('morsle_active', $record);
$this->log($key . ' DELETED', $record->courseid, null, s($response->response));
} else {
$this->log($key . ' DELETE FAILED', $record->courseid, null, null);
return false;
}
}
}
return true;
}
/********** PROVISIONING - ACCOUNTS - GROUPS - ****************/
/*
* creates a new user on google domain for the course
* important to note that if the account is never accessed by anything other than the API it will
* never initiate the first challenge typical of a new account. This additionally allows people who've
* editor rights to the calendar to add and delete events
* NOTE: ALL OF THESE FUNCTIONS LOG FROM THEIR CALLING PROGRAM
* TODO: uses clientlogin
*/
function useradd() {
global $CFG, $success;
$password = genrandom_password(12);
$familyName = $this->shortname;
$givenName = 'm';
$primaryEmail = $this->shortname . '@luther.edu';
$this->name->setFamilyName($familyName);
$this->name->setGivenName($givenName);
$this->user->setName($this->name);
$this->user->setPrimaryEmail($primaryEmail);
$this->user->setPassword($password);
$return = $this->service->users->insert($this->user);
if (isset($return->id)) {
return $password;
}
}
/*
* creates a new group on google domain for the course
* @param $this->headers - precreated clientlogin headers for authentication
* @param $groupname - name of group to be created
* @param $morslerec entire morsle record for this course NOT NEEDED
* @param $this->domain - constant representing domain name
* TODO: uses Clientlogin
*/
function groupadd($groupname) {
$this->group->setName($groupname);
$this->group->setEmail($groupname . '@luther.edu');
$return = $this->service->groups->insert($this->group);
return $groupname;
}
/********** SITE FUNCTIONS ***********************/
// TODO: should be able to combine these two functions
/*
* creates base site for course name
*/
function createsite() {
// form the xml for the post
$sitecreate =
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:sites="http://schemas.google.com/sites/2008">
<title>' . $this->sitename . '</title>
<summary>Morsle course site for collaboration</summary>
<sites:theme>microblueprint</sites:theme>
</entry>';
// Make the request
$response = twolegged($this->site_feed, $this->params, 'POST', $sitecreate, '1.4');
if ($success ) {
$feed = simplexml_load_string($response->response);
return get_href_noentry($feed, 'alternate');
} else {
return $response->response;
}
}
/*
* creates a portfolio site for a student based on the HPE portfolio template
* NOT GOING TO BE USED ANYMORE
*/
function createportfoliosite($title) {
global $success;
// form the xml for the post
$sitecreate =
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:sites="http://schemas.google.com/sites/2008">
<title>' . $title . '</title>
<link rel="http://schemas.google.com/sites/2008#source" type="application/atom+xml"
href="https://sites.google.com/feeds/site/luther.edu/puffer-s-temp-hpe2"/>
<summary>HPE ePortfolio Site For Assessment</summary>
</entry>';
// Make the request
$response = twolegged($this->site_feed, $this->params, 'POST', $sitecreate, '1.4');
if ($success ) {
$feed = simplexml_load_string($response->response);
return get_href_noentry($feed, 'alternate');
} else {
return $response->response;
}
}
/*
* gets a list of portfolios sites to which a particular user (usually a teacher) has access -- not used all that much
* NOT GOING TO BE USED ANYMORE
* mostly for troubleshooting
*/
function getportfoliosites() {
global $success;
$portfolio = array();
// Make the request
$response = twolegged($this->site_feed, $this->params, 'GET', null, '1.4');
if ($success ) {
$feed = simplexml_load_string($response->response);
foreach ($feed->entry as $entry) {
if(strpos($entry->title,$this->portfoliobase) === 0) {
$portfolio[] = trim(substr($entry->title, strlen($portfolioname),70));
}
}
return $portfolio;
} else {
return false;
}
}
/************** PERMISSION FUNCTIONS ******************/
/*
* adds or deletes members and owners to a group on google domain for the course
* this maintains "membership" and thereby deletes owners if they're no longer in the course
* as well as plain members
*/
function m_maintain($course = null) {
global $CFG, $DB,$COURSE;
require_once('../../config.php');
// $this->get_aliases();
$courseclause = $course != null ? " AND m.shortname = '" . strtolower($course) . "'": null;
$sql = 'SELECT m.*, c.visible as visible, c.category as category from ' . $CFG->prefix . 'morsle_active m
JOIN ' . $CFG->prefix . 'course c on m.courseid = c.id
WHERE m.status NOT IN(' . $this->disregard . ')
AND ((c.startdate + ' . $this->expires . ' > ' . $this->curtime . ') OR c.startdate = 0)
AND c.id > 6412'
. $courseclause;
$chewon = $DB->get_records_sql($sql);
$random = rand(0,9);
foreach ($chewon as $record) {
$this->shortname = $record->shortname;
$this->courseid = $record->courseid;
$this->user = strtolower($this->shortname . '@' . $this->domain);
$this->urluser = urlencode($this->user);
// $this->params = array('xoauth_requestor_id' => $this->user);
$this->groupname = $this->shortname . '-group';
$this->groupfullname= $this->groupname . '@' . $this->domain;
$this->visible = $record->visible;
$this->sitename = str_replace(' ', '-',strtolower('Course Site for ' . $this->shortname));
$this->site_acl_feed = "https://sites.google.com/feeds/acl/site/$this->domain/$this->sitename";
$this->cal_acl_feed = "https://www.googleapis.com/calendar/v3/calendars/";
$this->term= $DB->get_field('course_categories','name',array('id' => $record->category));
// determine rosters for everything else based on visibility of course,
// removing students if not visible
// if course is invisible we don't give students permission
// or they could get at resources from the google side
$rosters = $this->get_roster();
// maintain members and owners for group
if (!is_null($this->groupname)) {
//replaced 'admin-moogle@luther.edu' with $this->shortname as useremail
$this->useremail = $this->shortname.'@luther.edu';
$this->get_token('group');
$this->revoke_token();
$this->get_token('group');
$garray = array('editingteacher' => 'owner','teacher' => 'owner','student' => 'member');
// if full resources have been switched off, this will remove all permissions but the calendar
$allusers = $rosters;
array_walk($allusers,'set_googlerole', $garray);
// $this->membersmaintain($allusers);
}
// now we need to substitute real email for alias because folders use real (groups use alias)
foreach ($rosters as $key=>$value) {
if (isset($this->aliases[$key])) {
$rosters[$this->aliases[$key]] = $value;
unset($rosters[$key]);
}
}
$this->useremail = $this->user;
// Calendar permissions
if (!is_null($record->password)) {
$this->get_token('calendar');
$garray = array('editingteacher' => 'writer','teacher' => 'writer','student' => 'reader','guest' => 'reader');
$allusers = $rosters;
array_walk($allusers,'set_googlerole', $garray);
$this->gmembers = $this->set_calendarpermissions($allusers, $record);
}
// read-only folder permissions
if (!is_null($record->readfolderid)) {
$this->get_token('drive');
$garray = array('editingteacher' => 'writer','teacher' => 'writer','student' => 'reader');
// if full resources have been switched off, this will remove all permissions but the calendar
$allusers = $rosters;
// $allusers = array();
array_walk($allusers,'set_googlerole', $garray);
$readassigned = $this->set_folderpermissions('reader', $allusers, $record->readfolderid);
}
// writeable folder permissions (everyone writes)
if (!is_null($record->writefolderid)) {
$this->get_token('drive');
$garray = array('editingteacher' => 'writer','teacher' => 'writer','student' => 'writer');
// if full resources have been switched off, this will remove all permissions but the calendar
$allusers = $rosters;
array_walk($allusers,'set_googlerole', $garray);
$writeassigned = $this->set_folderpermissions('writer', $allusers, $record->writefolderid);
}
$this->revoke_token();
// Site permissions
if (!is_null($record->siteid)) {/* Site authentication not yet done, needs to be done
$this->get_token('site');
$this->revoke_token();
$this->get_token('site');
$garray = array('editingteacher' => 'owner','teacher' => 'owner','student' => 'writer');
// if full resources have been switched off, this will remove all permissions but the calendar
$allusers = $rosters;
array_walk($allusers,'set_googlerole', $garray);
$writeassigned = $this->set_sitepermissions($allusers);*/
}
}
}
function membersmaintain($members) {
global $success;
$return = $this->service->members->listMembers($this->groupfullname);
// $gmembers = get_group_permissions($this->groupname, $this->domain, $this->authstring);
$gmembers = array();
foreach($return as $key => $value) {
$gmembers[$value->email] = strtolower($value->role);
}
// check differences
$deleted = array_diff_assoc($gmembers, $members);
$added = sizeof($members) > 200 ? array() : array_diff_assoc($members, $gmembers);
/************************************************
To actually make the batch call we need to
enable batching on the client - this will apply
globally until we set it to false. This causes
call to the service methods to return the query
rather than immediately executing.
************************************************/
$this->client->setUseBatch(true);
$batch = new Google_Http_Batch($this->client);
// delete first due to aliases
foreach($deleted as $email=>$role) {
$return = $this->service->members->delete($this->groupfullname, $email);
$batch->add($return, $emailAddress);
if ($success == null) {
$this->log("$member delete SUCCESS", $this->courseid, null, $permission . ':' . s($response->response));
} else {
$this->log("$member delete FAILED", $this->courseid, null, $permission . ':');
}
}
// then add
foreach($added as $email => $role) {
$enrollee = new Google_Service_Directory_Member();
$enrollee->setEmail($email);
$enrollee->setRole(strtoupper($role));
$return = $this->service->members->insert($this->groupfullname, $enrollee);
$batch->add($return, $emailAddress);
if ($success == null) {
$this->log("$member add SUCCESS", $this->courseid, null, $permission . ':' . s($response->response));
} else {
$this->log("$member ADD FAILED ", $this->courseid, null, $permission . ':');
}
}
/************************************************
Executing the batch will send all requests off
at once.
************************************************/
$results = $batch->execute();
$this->client->setUseBatch(false);
}
function set_folderpermissions($readwrite, $members, $folderid) {
// what does google say we have for permissions on this folder
$return = $this->service->permissions->listPermissions($folderid);
$gmembers = array();