-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.php
549 lines (490 loc) · 22.7 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
<?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/>.
/**
* Panopto repository plugin.
*
* @package repository_panopto
* @copyright 2017 Lancaster University (http://www.lancaster.ac.uk/)
* @author Ruslan Kabalin (https://github.com/kabalin)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . "/repository/panopto/lib/panopto/lib/Client.php");
require_once($CFG->dirroot . '/repository/lib.php');
/**
* Repository plugin for accessing Panopto files.
*
* @package repository_panopto
* @copyright 2017 Lancaster University (http://www.lancaster.ac.uk/)
* @author Ruslan Kabalin (https://github.com/kabalin)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class repository_panopto extends repository {
/** Current client version in use. */
const ROOT_FOLDER_ID = '00000000-0000-0000-0000-000000000000';
/** @var stdClass Session Management client */
private $smclient;
/** @var stdClass User Management client */
private $umclient;
/** @var stdClass AuthenticationInfo object */
private $auth;
/** @var stdClass AuthenticationInfo object for admin */
private $adminauth;
/**
* Constructor
*
* @param int $repositoryid repository instance id.
* @param int|stdClass $context a context id or context object.
* @param array $options repository options.
*/
public function __construct($repositoryid, $context = SYSCONTEXTID, $options = []) {
global $USER;
parent::__construct($repositoryid, $context, $options);
// Disable this repo, we only can use it in Panopto course module at the moment,
// which will initialise it explicitly and bypass this flag. It is pointless to use it outside
// Panopto module, as it returns Panopto sessionid string only for the choosen video.
$this->disabled = true;
// Instantiate Panopto client.
$panoptoclient = new \Panopto\Client(get_config('panopto', 'serverhostname'));
$panoptoclient->setAuthenticationInfo(get_config('panopto', 'userkey'), get_config('panopto', 'password'));
$this->adminauth = $panoptoclient->getAuthenticationInfo();
$panoptoclient->setAuthenticationInfo(
get_config('panopto', 'instancename') . '\\' . $USER->username, '', get_config('panopto', 'applicationkey'));
$this->auth = $panoptoclient->getAuthenticationInfo();
try {
$this->smclient = $panoptoclient->SessionManagement();
$this->umclient = $panoptoclient->UserManagement();
} catch (Exception $e) {
debugging("Caught exception initialising Panopto API client: " . $e->getMessage());
}
}
/**
* Given a path, and perhaps a search, get a list of files.
*
* @param string $path identifier for current path.
* @param string $page the page number of file list.
* @return array list of files including meta information as specified by parent.
*/
public function get_listing($path = '', $page = '') {
// Data preparation.
if (empty($path)) {
$path = self::ROOT_FOLDER_ID;
}
$navpath = [];
$listfolders = [];
// Split the path requested.
$patharray = explode('/', $path);
// Build navigation path.
$navpathitem = '';
foreach ($patharray as $pathitem) {
if ($pathitem === self::ROOT_FOLDER_ID) {
// Root dir.
$navpathitem = $pathitem;
$navpath[] = ['name' => get_string('pluginname', 'repository_panopto'), 'path' => $navpathitem];
} else {
// Getting deeper in subdirs...
// Add navigation path item.
$param = new \Panopto\SessionManagement\GetFoldersById($this->auth, [$pathitem]);
$folders = $this->smclient->GetFoldersById($param)->getGetFoldersByIdResult();
// Add navigation path item.
$navpathitem = $navpathitem . '/' . $pathitem;
$navpath[] = ['name' => $folders[0]->getName(), 'path' => $navpathitem];
}
}
if (count($patharray) === 1) {
// Root folder view has been requested.
// Cache setup.
$cache = cache::make('repository_panopto', 'folderstree');
$cachettl = get_config('panopto', 'folderstreecachettl');
if ($cache->get('lastupdated') && (time() - (int) $cache->get('lastupdated') > (int) $cachettl)) {
// Invalidate cache after timeout.
$cache->purge();
}
// Retrieve folders tree from cache, if it does not exist, build one.
$listrootfolders = $cache->get('listrootfolders');
if ($listrootfolders === false) {
// Process folders and replace missing parent folders with root.
$listfolders = $this->get_folders_list($path);
$listrootfolders = [];
foreach ($listfolders as $folder) {
if ($folder['parentfolderid'] == self::ROOT_FOLDER_ID || !isset($listfolders[$folder['parentfolderid']])) {
// Missing parent folder, set to root.
$listrootfolders[] = $folder;
}
}
// Process sessions and move those with missing parent folder to root.
$listsessions = $this->get_sessions_list($path);
$listrootsessions = [];
foreach ($listsessions as $parentfolderid => $sessionsarray) {
if ($parentfolderid == self::ROOT_FOLDER_ID || !isset($listfolders[$parentfolderid])) {
// Missing parent folder.
$listrootsessions = array_merge($listrootsessions, $sessionsarray);
}
}
// Mix root level folders and sessions.
$listrootfolders = array_merge($listrootfolders, $listrootsessions);
// Store result in cache.
if (count($listrootfolders)) {
$cache->set_many(['listrootfolders' => $listrootfolders, 'lastupdated' => time()]);
}
}
$listfolders = $listrootfolders;
} else {
// When we are not in root folder, we request the actual folder content.
$listfolders = $this->get_folders_list($path);
$listsessions = $this->get_sessions_list($path);
$currentfolderid = end($patharray);
$listfolders = array_merge($listfolders, $listsessions[$currentfolderid]);
}
// Output result.
$listing = $this->get_base_listing();
$listing['list'] = $listfolders;
$listing['path'] = $navpath;
return $listing;
}
/**
* Search for results
* @param string $key The search string
* @param int $page The search page
* @return array A set of results with the same layout as the 'list' element in 'get_listing'.
*/
public function search($key, $page = 0) {
// Data preparation.
// Get the folders and sessions list for the current path.
$listfolders = $this->get_folders_list(self::ROOT_FOLDER_ID, $key);
$listsessions = $this->get_sessions_list(self::ROOT_FOLDER_ID, $key);
$list = array_merge($listfolders, $listsessions[self::ROOT_FOLDER_ID]);
// Output result.
$listing = $this->get_base_listing();
$listing['issearchresult'] = true;
$listing['list'] = $list;
return $listing;
}
/**
* Given a path, get a list of Panopto directories.
*
* If root path is requested, we get all possible folders instead, to build
* a root directory (see get_listing). There is a use case, when user was
* given access rights to some non-root folder in Panopto, if parent is set
* to root folder in the API request below on initial listing, there will
* be no way to retrieve this folder and display it to the user.
*
* @param string $path identifier for current path.
* @param string $search the search query.
* @return array list of folders with the same layout as the 'list' element in 'get_listing'.
*/
private function get_folders_list($path, $search = '') {
global $OUTPUT;
$list = [];
// Build the GetFoldersList request and perform the call.
$pagination = new \Panopto\RemoteRecorderManagement\Pagination();
$pagination->setPageNumber(0);
$pagination->setMaxNumberResults(1000);
$request = new \Panopto\SessionManagement\ListFoldersRequest();
$request->setPagination($pagination);
$request->setSortBy('Name');
$request->setSortIncreasing(true);
// If we are searching, there is no need to set parent folder,
// also a good idea to search by relevance.
if (!empty($search)) {
$request->setWildcardSearchNameOnly(true);
} else if ($path !== self::ROOT_FOLDER_ID) {
// Set parent folder if it is not root.
$patharray = explode('/', $path);
$currentfolderid = end($patharray);
$request->setParentFolderId($currentfolderid);
}
$param = new \Panopto\SessionManagement\GetCreatorFoldersList($this->auth, $request, $search);
$folders = $this->smclient->GetCreatorFoldersList($param)->getGetCreatorFoldersListResult();
$totalfolders = $folders->getTotalNumberResults();
// Processing GetCreatorFoldersList result.
if ($totalfolders) {
foreach ($folders->getResults() as $folder) {
// Determine parent folder.
$parentfolderid = $folder->getParentFolder();
if (empty($parentfolderid)) {
$parentfolderid = self::ROOT_FOLDER_ID;
}
$list[$folder->getId()] = [
'title' => $folder->getName(),
'shorttitle' => $folder->getName(),
'path' => $path . '/' . $folder->getId(),
'thumbnail' => $OUTPUT->image_url('f/folder-32')->out(false),
'children' => [],
// Techical data we need to build directory tree.
'parentfolderid' => $parentfolderid,
];
}
}
return $list;
}
/**
* Get a list of Panopto sessions available for viewing in each directory.
*
* List of files with the same layout as the 'list' element in 'get_listing',
* but with parent directory data. Basically array of arrays with key set to parent directory.
*
* @param string $path identifier for current path.
* @param string $search the search query.
* @return array list of files with the same layout as the 'list' element in 'get_listing'.
*/
private function get_sessions_list($path, $search = '') {
$list = [];
// Build the GetFoldersList request and perform the call.
$pagination = new \Panopto\RemoteRecorderManagement\Pagination();
$pagination->setPageNumber(0);
$pagination->setMaxNumberResults(1000);
$request = new \Panopto\SessionManagement\ListSessionsRequest();
$request->setPagination($pagination);
$request->setSortBy('Name');
$request->setSortIncreasing(true);
$request->setStates(['Complete']);
// If we are not searching, set parent folder if required.
$orphanedlistingcheck = get_config('panopto', 'showorphanedsessions') ? ($path !== self::ROOT_FOLDER_ID) : true;
if (empty($search) && $orphanedlistingcheck) {
$patharray = explode('/', $path);
$currentfolderid = end($patharray);
$request->setFolderId($currentfolderid);
// Pre-define array for the current parent folder.
$list[$currentfolderid] = [];
}
$param = new \Panopto\SessionManagement\GetSessionsList($this->auth, $request, $search);
$sessions = $this->smclient->GetSessionsList($param)->getGetSessionsListResult();
$totalsessions = $sessions->getTotalNumberResults();
// Processing GetFoldersList result.
if ($totalsessions) {
foreach ($sessions->getResults() as $session) {
// Define parent folder array.
$parentfolderid = $session->getFolderId();
if (empty($parentfolderid) || !empty($search)) {
$parentfolderid = self::ROOT_FOLDER_ID;
}
if (!isset($list[$parentfolderid])) {
$list[$parentfolderid] = [];
}
// Add session data.
$title = $session->getName();
$url = new moodle_url($session->getViewerUrl());
$thumbnail = $session->getThumbUrl();
if (is_string($thumbnail) && strpos($thumbnail, '//') === 0) {
$thumburl = new moodle_url('https:' . $thumbnail);
$thumbnail = $thumburl->out(false);
}
$list[$parentfolderid][] = [
'shorttitle' => $title,
'title' => $title,
'source' => $session->getId(),
'url' => $url->out(false),
'thumbnail' => $thumbnail,
'thumbnail_title' => $session->getDescription(),
'date' => $session->getStartTime()->format('U'),
];
}
}
return $list;
}
/**
* Return array of default listing properties.
*
* @return array of listing properties.
*/
private function get_base_listing() {
return [
'dynload' => true,
'nologin' => true,
'path' => [
[
'name' => get_string('pluginname', 'repository_panopto'),
'path' => self::ROOT_FOLDER_ID,
],
],
'list' => [],
];
}
/**
* Return names of the options to display in the repository plugin config form.
*
* @return array of option names.
*/
public static function get_type_option_names() {
return [
'serverhostname',
'userkey',
'password',
'instancename',
'applicationkey',
'pluginname',
'folderstreecachettl',
'showorphanedsessions',
];
}
/**
* Setup repistory form.
*
* @param moodleform $mform Moodle form (passed by reference).
* @param string $classname repository class name.
*/
public static function type_config_form($mform, $classname = 'repository') {
global $DB;
// Notice about repo availability.
$mform->addElement('static', 'pluginnotice', '',
html_writer::tag('div', get_string('pluginnotice', 'repository_panopto'), ['class' => 'warning']));
$strrequired = get_string('required');
parent::type_config_form($mform);
// Folder tree cache ttl.
$mform->addElement('text', 'folderstreecachettl', get_string('folderstreecachettl', 'repository_panopto'));
$mform->setType('folderstreecachettl', PARAM_INT);
$mform->setDefault('folderstreecachettl', 300);
$mform->addElement('static', 'folderstreecachettldesc', '', get_string('folderstreecachettldesc', 'repository_panopto'));
// Show orphaned sessions.
$mform->addElement('checkbox', 'showorphanedsessions', get_string('showorphanedsessions', 'repository_panopto'));
$mform->setType('showorphanedsessions', PARAM_BOOL);
$mform->setDefault('showorphanedsessions', false);
$mform->addElement('static', 'showorphanedsessionsdesc', '', get_string('showorphanedsessionsdesc', 'repository_panopto'));
// Header.
$mform->addElement('header', 'connectionsettings', get_string('connectionsettings', 'repository_panopto'));
// Server hostname.
$mform->addElement('text', 'serverhostname', get_string('serverhostname', 'repository_panopto'));
$mform->addRule('serverhostname', $strrequired, 'required', null, 'client');
$mform->setType('serverhostname', PARAM_HOST);
$mform->addElement('static', 'serverhostnamedesc', '', get_string('serverhostnamedesc', 'repository_panopto'));
// User key.
$mform->addElement('text', 'userkey', get_string('userkey', 'repository_panopto'));
$mform->addRule('userkey', $strrequired, 'required', null, 'client');
$mform->setType('userkey', PARAM_RAW_TRIMMED);
$mform->addElement('static', 'userkeydesc', '', get_string('userkeydesc', 'repository_panopto'));
// Password.
$mform->addElement('text', 'password', get_string('password', 'repository_panopto'));
$mform->addRule('password', $strrequired, 'required', null, 'client');
$mform->setType('password', PARAM_RAW_TRIMMED);
$mform->addElement('static', 'passworddesc', '', get_string('passworddesc', 'repository_panopto'));
// Instance name.
$mform->addElement('text', 'instancename', get_string('instancename', 'repository_panopto'));
$mform->addRule('instancename', $strrequired, 'required', null, 'client');
$mform->setType('instancename', PARAM_ALPHANUMEXT);
$mform->addElement('static', 'instancenamedesc', '', get_string('instancenamedesc', 'repository_panopto'));
// Application key.
$mform->addElement('text', 'applicationkey', get_string('applicationkey', 'repository_panopto'));
$mform->addRule('applicationkey', $strrequired, 'required', null, 'client');
$mform->setType('applicationkey', PARAM_ALPHANUMEXT);
$mform->addElement('static', 'applicationkeydesc', '', get_string('applicationkeydesc', 'repository_panopto'));
// Display Bounce Page URL for Identity Privder setup.
$sql = 'SELECT i.id FROM {repository} r, {repository_instances} i WHERE r.type=? AND i.typeid=r.id';
$repoid = $DB->get_field_sql($sql, ['panopto']);
if ($repoid) {
$url = new \moodle_url('/repository/repository_callback.php', ['repo_id' => $repoid]);
$mform->addElement('static', 'bouncepageurl', get_string('bouncepageurl', 'repository_panopto'),
get_string('bouncepageurldesc', 'repository_panopto', $url->out(true)));
} else {
$mform->addElement('static', 'bouncepageurl', get_string('bouncepageurl', 'repository_panopto'),
get_string('bouncepageurlnotreadydesc', 'repository_panopto'));
}
}
/**
* This repository doesn't support global search.
*
* @return bool if supports global search
*/
public function global_search() {
return false;
}
/**
* This repository only supports external files
*
* @return int return type bitmask supported
*/
public function supported_returntypes() {
return FILE_EXTERNAL;
}
/**
* We do not treat Panopto site data as private.
*
* @return bool
*/
public function contains_private_data() {
return false;
}
/**
* Use check login for syncling user data with Panopto.
*
* @return true.
*/
public function check_login() {
$this->sync_user();
return true;
}
/**
* Sync user data with Panopto.
*
* This will create user on Panopto side if needed and populate user data.
*
* @return void.
*/
private function sync_user() {
global $USER;
// Check that external user exists, if not, sync user data.
$params = new \Panopto\UserManagement\GetUserByKey($this->auth, get_config('panopto', 'instancename') . '\\' .
$USER->username);
$user = $this->umclient->GetUserByKey($params)->getGetUserByKeyResult();
if ($user === null) {
// User does not exist, sync one.
$params = new \Panopto\UserManagement\SyncExternalUser($this->auth, $USER->firstname,
$USER->lastname, $USER->email, false, []);
$this->umclient->SyncExternalUser($params);
} else if (!$user->getFirstName() || !$user->getLastName() || !$user->getEmail()) {
// User exists, but some data is missing, update contact info.
$params = new \Panopto\UserManagement\UpdateContactInfo($this->auth, $user->getUserId(), $USER->firstname,
$USER->lastname, $USER->email, false);
$this->umclient->UpdateContactInfo($params);
}
}
/**
* Callback for SSO processing.
*
* @return true.
*/
public function callback() {
global $USER;
$authcode = required_param("authCode", PARAM_ALPHANUM);
$servername = required_param("serverName", PARAM_HOST);
$callbackurl = required_param("callbackURL", PARAM_URL);
$expiration = required_param("expiration", PARAM_RAW);
$action = optional_param("action", "", PARAM_ALPHA);
// Verify provided authcode.
$authpayload = "serverName=" . $servername . "&expiration=" . $expiration;
$authpayload = $authpayload . "|" . get_config('panopto', 'applicationkey');
$encodedpayload = strtoupper(sha1($authpayload));
if ($encodedpayload !== $authcode) {
throw new \invalid_parameter_exception('Invalid auth code provided.');
}
// Sync user data.
$this->sync_user();
// Craft the response to Panopto.
$userkey = get_config('panopto', 'instancename') . '\\' . $USER->username;
$responseparams = "serverName=" . $servername . "&externalUserKey=" . $userkey . "&expiration=" . $expiration;
$responseparams = $responseparams . "|" . get_config('panopto', 'applicationkey');
$responseauthcode = strtoupper(sha1($responseparams));
$urlparams = [
'serverName' => $servername,
'externalUserKey' => $userkey,
'expiration' => $expiration,
'authCode' => $responseauthcode,
];
$redirecturl = new \moodle_url($callbackurl, $urlparams);
// Redirect to Panopto.
redirect($redirecturl->out(true));
}
}