NOBUG: Fixed file access permissions
[moodle.git] / repository / nextcloud / lib.php
CommitLineData
b4e24a82
NH
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Nextcloud repository plugin library.
19 *
20 * @package repository_nextcloud
21 * @copyright 2017 Project seminar (Learnweb, University of Münster)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or
23 */
24
25use repository_nextcloud\issuer_management;
26use repository_nextcloud\ocs_client;
27
28defined('MOODLE_INTERNAL') || die();
29
30require_once($CFG->dirroot . '/repository/lib.php');
31require_once($CFG->libdir . '/webdavlib.php');
32
33/**
34 * Nextcloud repository class.
35 *
36 * @package repository_nextcloud
37 * @copyright 2017 Project seminar (Learnweb, University of Münster)
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 */
40class repository_nextcloud extends repository {
41 /**
42 * OAuth 2 client
43 * @var \core\oauth2\client
44 */
45 private $client = null;
46
47 /**
48 * OAuth 2 Issuer
49 * @var \core\oauth2\issuer
50 */
51 private $issuer = null;
52
53 /**
54 * Additional scopes needed for the repository. Currently, nextcloud does not actually support/use scopes, so
55 * this is intended as a hint at required functionality and will help declare future scopes.
56 */
57 const SCOPES = 'files ocs';
58
59 /**
60 * Webdav client which is used for webdav operations.
61 *
62 * @var \webdav_client
63 */
64 private $dav = null;
65
66 /**
67 * Basepath for WebDAV operations
68 * @var string
69 */
70 private $davbasepath;
71
72 /**
73 * OCS client that uses the Open Collaboration Services REST API.
74 * @var ocs_client
75 */
76 private $ocsclient;
77
78 /**
79 * @var oauth2_client System account client.
80 */
81 private $systemoauthclient = false;
82
83 /**
84 * OCS systemocsclient that uses the Open Collaboration Services REST API.
85 * @var ocs_client
86 */
87 private $systemocsclient = null;
e8da9f7f 88
b4e24a82
NH
89 /**
90 * Name of the folder for controlled links.
91 * @var string
92 */
93 private $controlledlinkfoldername;
94
95 /**
96 * repository_nextcloud constructor.
e8da9f7f 97 *
b4e24a82
NH
98 * @param int $repositoryid
99 * @param bool|int|stdClass $context
100 * @param array $options
101 */
102 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array()) {
103 parent::__construct($repositoryid, $context, $options);
104 try {
105 // Issuer from repository instance config.
106 $issuerid = $this->get_option('issuerid');
107 $this->issuer = \core\oauth2\api::get_issuer($issuerid);
108 } catch (dml_missing_record_exception $e) {
109 // A repository is marked as disabled when no issuer is present.
110 $this->disabled = true;
111 return;
112 }
113
114 try {
115 // Load the webdav endpoint and parse the basepath.
116 $webdavendpoint = issuer_management::parse_endpoint_url('webdav', $this->issuer);
117 // Get basepath without trailing slash, because future uses will come with a leading slash.
118 $basepath = $webdavendpoint['path'];
119 if (strlen($basepath) > 0 && substr($basepath, -1) === '/') {
120 $basepath = substr($basepath, 0, -1);
121 }
122 $this->davbasepath = $basepath;
123 } catch (\repository_nextcloud\configuration_exception $e) {
124 // A repository is marked as disabled when no webdav_endpoint is present
125 // or it fails to parse, because all operations concerning files
126 // rely on the webdav endpoint.
127 $this->disabled = true;
128 return;
129 }
130 $this->controlledlinkfoldername = $this->get_option('controlledlinkfoldername');
131
132 if (!$this->issuer) {
133 $this->disabled = true;
134 return;
135 } else if (!$this->issuer->get('enabled')) {
136 // In case the Issuer is not enabled, the repository is disabled.
137 $this->disabled = true;
138 return;
139 } else if (!issuer_management::is_valid_issuer($this->issuer)) {
140 // Check if necessary endpoints are present.
141 $this->disabled = true;
142 return;
143 }
144
145 $this->ocsclient = new ocs_client($this->get_user_oauth_client());
146 }
147
148 /**
149 * Get or initialise an oauth client for the system account.
e8da9f7f 150 *
b4e24a82
NH
151 * @return false|oauth2_client False if initialisation was unsuccessful, otherwise an initialised client.
152 */
153 private function get_system_oauth_client() {
154 if ($this->systemoauthclient === false) {
155 try {
156 $this->systemoauthclient = \core\oauth2\api::get_system_oauth_client($this->issuer);
157 } catch (\moodle_exception $e) {
158 $this->systemoauthclient = false;
159 }
160 }
161 return $this->systemoauthclient;
162 }
163
164 /**
165 * Get or initialise an ocs client for the system account.
e8da9f7f 166 *
b4e24a82
NH
167 * @return null|ocs_client Null if initialisation was unsuccessful, otherwise an initialised client.
168 */
169 private function get_system_ocs_client() {
170 if ($this->systemocsclient === null) {
171 try {
172 $systemoauth = $this->get_system_oauth_client();
173 if (!$systemoauth) {
174 return null;
175 }
176 $this->systemocsclient = new ocs_client($systemoauth);
177 } catch (\moodle_exception $e) {
178 $this->systemocsclient = null;
179 }
180 }
181 return $this->systemocsclient;
182 }
183
184 /**
185 * Initiates the webdav client.
e8da9f7f 186 *
b4e24a82
NH
187 * @throws \repository_nextcloud\configuration_exception If configuration is missing (endpoints).
188 */
189 private function initiate_webdavclient() {
190 if ($this->dav !== null) {
191 return $this->dav;
192 }
193
194 $webdavendpoint = issuer_management::parse_endpoint_url('webdav', $this->issuer);
195
196 // Selects the necessary information (port, type, server) from the path to build the webdavclient.
197 $server = $webdavendpoint['host'];
198 if ($webdavendpoint['scheme'] === 'https') {
199 $webdavtype = 'ssl://';
200 $webdavport = 443;
201 } else if ($webdavendpoint['scheme'] === 'http') {
202 $webdavtype = '';
203 $webdavport = 80;
204 }
205
206 // Override default port, if a specific one is set.
207 if (isset($webdavendpoint['port'])) {
208 $webdavport = $webdavendpoint['port'];
209 }
210
211 // Authentication method is `bearer` for OAuth 2. Pass token of authenticated client, too.
212 $this->dav = new \webdav_client($server, '', '', 'bearer', $webdavtype,
213 $this->get_user_oauth_client()->get_accesstoken()->token);
214
215 $this->dav->port = $webdavport;
216 $this->dav->debug = false;
217 return $this->dav;
218 }
219
220 /**
221 * This function does exactly the same as in the WebDAV repository. The only difference is, that
222 * the nextcloud OAuth2 client uses OAuth2 instead of Basic Authentication.
223 *
224 * @param string $reference relative path to the file.
225 * @param string $title title of the file.
226 * @return array|bool returns either the moodle path to the file or false.
227 */
228 public function get_file($reference, $title = '') {
229 // Normal file.
230 $reference = urldecode($reference);
231
232 // Prepare a file with an arbitrary name - cannot be $title because of special chars (cf. MDL-57002).
233 $path = $this->prepare_file(uniqid());
234 $this->initiate_webdavclient();
235 if (!$this->dav->open()) {
236 return false;
237 }
238 $this->dav->get_file($this->davbasepath . $reference, $path);
239 $this->dav->close();
240
241 return array('path' => $path);
242 }
243
244 /**
245 * This function does exactly the same as in the WebDAV repository. The only difference is, that
246 * the nextcloud OAuth2 client uses OAuth2 instead of Basic Authentication.
247 *
248 * @param string $path relative path to the directory or file.
249 * @param string $page page number (given multiple pages of elements).
250 * @return array directory properties.
251 */
252 public function get_listing($path='', $page = '') {
253 if (empty($path)) {
254 $path = '/';
255 }
256
257 $ret = $this->get_listing_prepare_response($path);
258
259 // Before any WebDAV method can be executed, a WebDAV client socket needs to be opened
260 // which connects to the server.
261 $this->initiate_webdavclient();
262 if (!$this->dav->open()) {
263 return $ret;
264 }
265
266 // Since the paths which are received from the PROPFIND WebDAV method are url encoded
267 // (because they depict actual web-paths), the received paths need to be decoded back
268 // for the plugin to be able to work with them.
269 $ls = $this->dav->ls($this->davbasepath . urldecode($path));
270 $this->dav->close();
271
272 // The method get_listing return all information about all child files/folders of the
273 // current directory. If no information was received, the directory must be empty.
274 if (!is_array($ls)) {
275 return $ret;
276 }
277
278 // Process WebDAV output and convert it into Moodle format.
279 $ret['list'] = $this->get_listing_convert_response($path, $ls);
280 return $ret;
281
282 }
283
284 /**
285 * Use OCS to generate a public share to the requested file.
286 * This method derives a download link from the public share URL.
287 *
288 * @param string $url relative path to the chosen file
289 * @return string the generated download link.
290 * @throws \repository_nextcloud\request_exception If nextcloud responded badly
291 *
292 */
293 public function get_link($url) {
294 $ocsparams = [
295 'path' => $url,
296 'shareType' => ocs_client::SHARE_TYPE_PUBLIC,
297 'publicUpload' => false,
298 'permissions' => ocs_client::SHARE_PERMISSION_READ
299 ];
300
301 $response = $this->ocsclient->call('create_share', $ocsparams);
302 $xml = simplexml_load_string($response);
b4e24a82
NH
303
304 if ($xml === false ) {
4354a428
JD
305 throw new \repository_nextcloud\request_exception(array('instance' => $this->get_name(),
306 'errormessage' => get_string('invalidresponse', 'repository_nextcloud')));
b4e24a82
NH
307 }
308
309 if ((string)$xml->meta->status !== 'ok') {
4354a428 310 throw new \repository_nextcloud\request_exception(array('instance' => $this->get_name(), 'errormessage' => sprintf(
b4e24a82
NH
311 '(%s) %s', $xml->meta->statuscode, $xml->meta->message)));
312 }
313
314 // Take the share link and convert it into a download link.
315 return ((string)$xml->data[0]->url) . '/download';
316 }
317
318 /**
e8da9f7f 319 * This method does not do any translation of the file source.
b4e24a82
NH
320 *
321 * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
322 * @return string file reference, ready to be stored
323 */
324 public function get_file_reference($source) {
e8da9f7f 325 // The simple relative path to the file is enough.
b4e24a82
NH
326 return $source;
327 }
328
e8da9f7f
DW
329 /**
330 * Called when a file is selected as a "access control link".
b4e24a82
NH
331 * Invoked at MOODLE/repository/repository_ajax.php
332 *
333 * This is called at the point the reference files are being copied from the draft area to the real area.
334 * What is done here is transfer ownership to the system user (by copying) then delete the intermediate share
335 * used for that. Finally update the reference to point to new file name.
336 *
337 * @param string $reference this reference is generated by repository::get_file_reference()
338 * @param context $context the target context for this new file.
339 * @param string $component the target component for this new file.
340 * @param string $filearea the target filearea for this new file.
341 * @param string $itemid the target itemid for this new file.
342 * @return string updated reference (final one before it's saved to db).
343 * @throws \repository_nextcloud\configuration_exception
344 * @throws \repository_nextcloud\request_exception
345 * @throws coding_exception
346 * @throws moodle_exception
347 * @throws repository_exception
348 */
349 public function reference_file_selected($reference, $context, $component, $filearea, $itemid) {
350 $source = json_decode($reference);
351
352 if (is_object($source)) {
353 if ($source->type != 'FILE_CONTROLLED_LINK') {
354 // Only access controlled links need special handling; we are done.
355 return $reference;
356 }
357 if (!empty($source->usesystem)) {
358 // If we already copied this file to the system account - we are done.
359 return $reference;
360 }
361 }
362
363 // Check this issuer is enabled.
364 if ($this->disabled || $this->get_system_oauth_client() === false || $this->get_system_ocs_client() === null) {
365 throw new repository_exception('cannotdownload', 'repository');
366 }
367
368 $linkmanager = new \repository_nextcloud\access_controlled_link_manager($this->ocsclient, $this->get_system_oauth_client(),
369 $this->get_system_ocs_client(), $this->issuer, $this->get_name());
370
371 // Get the current user.
372 $userauth = $this->get_user_oauth_client();
373 if ($userauth === false) {
374 $details = get_string('cannotconnect', 'repository_nextcloud');
375 throw new \repository_nextcloud\request_exception(array('instance' => $this->get_name(), 'errormessage' => $details));
376 }
377 // 1. Share the File with the system account.
378 $responsecreateshare = $linkmanager->create_share_user_sysaccount($reference);
379 if ($responsecreateshare['statuscode'] == 403) {
380 // File has already been shared previously => find file in system account and use that.
381 $responsecreateshare = $linkmanager->find_share_in_sysaccount($reference);
382 }
383
384 // 2. Create a unique path in the system account.
385 $createdfolder = $linkmanager->create_folder_path_access_controlled_links($context, $component, $filearea,
386 $itemid);
387
388 // 3. Copy File to the new folder path.
389 $linkmanager->transfer_file_to_path($responsecreateshare['filetarget'], $createdfolder, 'copy');
390
391 // 4. Delete the share.
392 $linkmanager->delete_share_dataowner_sysaccount($responsecreateshare['shareid']);
393
394 // Update the returned reference so that the stored_file in moodle points to the newly copied file.
395 $filereturn = new stdClass();
396 $filereturn->type = 'FILE_CONTROLLED_LINK';
397 $filereturn->link = $createdfolder . $responsecreateshare['filetarget'];
398 $filereturn->name = $reference;
399 $filereturn->usesystem = true;
400 $filereturn = json_encode($filereturn);
401
402 return $filereturn;
403 }
404
405 /**
406 * Repository method that serves the referenced file (created e.g. via get_link).
407 * All parameters are there for compatibility with superclass, but they are ignored.
408 *
409 * @param stored_file $storedfile
410 * @param int $lifetime (ignored)
411 * @param int $filter (ignored)
412 * @param bool $forcedownload (ignored)
413 * @param array $options (ignored)
414 * @throws \repository_nextcloud\configuration_exception
415 * @throws \repository_nextcloud\request_exception
416 * @throws coding_exception
417 * @throws moodle_exception
418 */
419 public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
420 $repositoryname = $this->get_name();
421 $reference = json_decode($storedfile->get_reference());
422
b4e24a82
NH
423 // 1. assure the client and user is logged in.
424 if (empty($this->client) || $this->get_system_oauth_client() === false || $this->get_system_ocs_client() === null) {
425 $details = get_string('contactadminwith', 'repository_nextcloud',
4354a428 426 get_string('noclientconnection', 'repository_nextcloud'));
b4e24a82
NH
427 throw new \repository_nextcloud\request_exception(array('instance' => $repositoryname, 'errormessage' => $details));
428 }
429
430 if (!$this->client->is_logged_in()) {
431 $this->print_login_popup(['style' => 'margin-top: 250px']);
432 return;
433 }
434
435 // Determining writeability of file from the using context.
436 // Variable $info is null|\file_info. file_info::is_writable is only true if user may write for any reason.
437 $fb = get_file_browser();
438 $context = context::instance_by_id($storedfile->get_contextid(), MUST_EXIST);
439 $info = $fb->get_file_info($context,
440 $storedfile->get_component(),
441 $storedfile->get_filearea(),
442 $storedfile->get_itemid(),
443 $storedfile->get_filepath(),
444 $storedfile->get_filename());
445 $maywrite = !empty($info) && $info->is_writable();
446
447 $this->initiate_webdavclient();
448
449 // Create the a manager to handle steps.
450 $linkmanager = new \repository_nextcloud\access_controlled_link_manager($this->ocsclient, $this->get_system_oauth_client(),
451 $this->get_system_ocs_client(), $this->issuer, $repositoryname);
452
453 // 2. Check whether user has folder for files otherwise create it.
454 $linkmanager->create_storage_folder($this->controlledlinkfoldername, $this->dav);
455
456 $userinfo = $this->client->get_userinfo();
457 $username = $userinfo['username'];
458
459 // Creates a share between the systemaccount and the user.
460 $responsecreateshare = $linkmanager->create_share_user_sysaccount($reference->link, $username, $maywrite);
461
462 $statuscode = $responsecreateshare['statuscode'];
463
464 if ($statuscode == 403) {
465 $shareid = $linkmanager->get_shares_from_path($reference->link, $username);
466 } else if ($statuscode == 100) {
467 $filetarget = $linkmanager->get_share_information_from_shareid($responsecreateshare['shareid'], $username);
468 $copyresult = $linkmanager->transfer_file_to_path($filetarget, $this->controlledlinkfoldername,
469 'move', $this->dav);
470 if (!($copyresult == 201 || $copyresult == 412)) {
4354a428 471 throw new \repository_nextcloud\request_exception(array('instance' => $repositoryname,
b4e24a82
NH
472 'errormessage' => get_string('couldnotmove', 'repository_nextcloud', $this->controlledlinkfoldername)));
473 }
474 $shareid = $responsecreateshare['shareid'];
475 } else if ($statuscode == 997) {
476 throw new \repository_nextcloud\request_exception(array('instance' => $repositoryname,
477 'errormessage' => get_string('notauthorized', 'repository_nextcloud')));
478 } else {
479 $details = get_string('filenotaccessed', 'repository_nextcloud');
480 throw new \repository_nextcloud\request_exception(array('instance' => $repositoryname, 'errormessage' => $details));
481 }
482 $filetarget = $linkmanager->get_share_information_from_shareid((int)$shareid, $username);
483
484 // Obtain the file from Nextcloud using a Bearer token authenticated connection because we cannot perform a redirect here.
485 // The reason is that Nextcloud uses samesite cookie validation, i.e. a redirected request would not be authenticated.
486 // (Also the browser might use the session of a Nextcloud user that is different from the one that is known to Moodle.)
487 $filename = basename($filetarget);
488 $tmppath = make_request_directory() . '/' . $filename;
489 $this->dav->open();
490
491 // Concat webdav path with file path.
492 $webdavendpoint = issuer_management::parse_endpoint_url('webdav', $this->issuer);
493 $filetarget = ltrim($filetarget, '/');
494 $filetarget = $webdavendpoint['path'] . $filetarget;
495
496 // Write file into temp location.
497 if (!$this->dav->get_file($filetarget, $tmppath)) {
498 $this->dav->close();
499 throw new repository_exception('cannotdownload', 'repository');
500 }
501 $this->dav->close();
502
503 // Output the obtained file to the user and remove it from disk.
504 send_temp_file($tmppath, $filename);
505 }
506
507 /**
508 * Which return type should be selected by default.
509 *
510 * @return int
511 */
512 public function default_returntype() {
513 $setting = $this->get_option('defaultreturntype');
514 $supported = $this->get_option('supportedreturntypes');
515 if (($setting == FILE_INTERNAL && $supported !== 'external') || $supported === 'internal') {
516 return FILE_INTERNAL;
517 }
518 return FILE_CONTROLLED_LINK;
519 }
520
521 /**
522 * Return names of the general options.
523 * By default: no general option name.
524 *
525 * @return array
526 */
527 public static function get_type_option_names() {
528 return array();
529 }
530
531 /**
532 * Function which checks whether the user is logged in on the Nextcloud instance.
533 *
534 * @return bool false, if no Access Token is set or can be requested.
535 */
536 public function check_login() {
537 $client = $this->get_user_oauth_client();
538 return $client->is_logged_in();
539 }
540
541 /**
542 * Get a cached user authenticated oauth client.
e8da9f7f 543 *
b4e24a82
NH
544 * @param bool|moodle_url $overrideurl Use this url instead of the repo callback.
545 * @return \core\oauth2\client
546 */
547 protected function get_user_oauth_client($overrideurl = false) {
548 if ($this->client) {
549 return $this->client;
550 }
551 if ($overrideurl) {
552 $returnurl = $overrideurl;
553 } else {
554 $returnurl = new moodle_url('/repository/repository_callback.php');
555 $returnurl->param('callback', 'yes');
556 $returnurl->param('repo_id', $this->id);
557 $returnurl->param('sesskey', sesskey());
558 }
559 $this->client = \core\oauth2\api::get_user_oauth_client($this->issuer, $returnurl, self::SCOPES);
560 return $this->client;
561 }
562
b4e24a82
NH
563 /**
564 * Prints a simple Login Button which redirects to an authorization window from Nextcloud.
565 *
566 * @return mixed login window properties.
567 * @throws coding_exception
568 */
569 public function print_login() {
570 $client = $this->get_user_oauth_client();
571 $loginurl = $client->get_login_url();
572 if ($this->options['ajax']) {
573 $ret = array();
574 $btn = new \stdClass();
575 $btn->type = 'popup';
576 $btn->url = $loginurl->out(false);
577 $ret['login'] = array($btn);
578 return $ret;
579 } else {
580 echo html_writer::link($loginurl, get_string('login', 'repository'),
581 array('target' => '_blank', 'rel' => 'noopener noreferrer'));
582 }
583 }
584
585 /**
586 * Deletes the held Access Token and prints the Login window.
587 *
588 * @return array login window properties.
589 */
590 public function logout() {
591 $client = $this->get_user_oauth_client();
592 $client->log_out();
593 return parent::logout();
594 }
595
596 /**
597 * Sets up access token after the redirection from Nextcloud.
598 */
599 public function callback() {
600 $client = $this->get_user_oauth_client();
601 // If an Access Token is stored within the client, it has to be deleted to prevent the addition
602 // of an Bearer authorization header in the request method.
603 $client->log_out();
604
605 // This will upgrade to an access token if we have an authorization code and save the access token in the session.
606 $client->is_logged_in();
607 }
608
b4e24a82
NH
609 /**
610 * Create an instance for this plug-in
611 *
612 * @param string $type the type of the repository
613 * @param int $userid the user id
614 * @param stdClass $context the context
615 * @param array $params the options for this instance
616 * @param int $readonly whether to create it readonly or not (defaults to not)
617 * @return mixed
618 * @throws dml_exception
619 * @throws required_capability_exception
620 */
621 public static function create($type, $userid, $context, $params, $readonly=0) {
622 require_capability('moodle/site:config', context_system::instance());
623 return parent::create($type, $userid, $context, $params, $readonly);
624 }
625
b4e24a82
NH
626 /**
627 * This method adds a select form and additional information to the settings form..
628 *
629 * @param \moodleform $mform Moodle form (passed by reference)
630 * @return bool|void
631 * @throws coding_exception
632 * @throws dml_exception
633 */
634 public static function instance_config_form($mform) {
635 if (!has_capability('moodle/site:config', context_system::instance())) {
636 $mform->addElement('static', null, '', get_string('nopermissions', 'error', get_string('configplugin',
637 'repository_nextcloud')));
638 return false;
639 }
640
641 // Load configured issuers.
642 $issuers = core\oauth2\api::get_all_issuers();
643 $types = array();
644
645 // Validates which issuers implement the right endpoints. WebDav is necessary for Nextcloud.
646 $validissuers = [];
647 foreach ($issuers as $issuer) {
648 $types[$issuer->get('id')] = $issuer->get('name');
649 if (\repository_nextcloud\issuer_management::is_valid_issuer($issuer)) {
650 $validissuers[] = $issuer->get('name');
651 }
652 }
653
654 // Render the form.
655 $url = new \moodle_url('/admin/tool/oauth2/issuers.php');
656 $mform->addElement('static', null, '', get_string('oauth2serviceslink', 'repository_nextcloud', $url->out()));
657
658 $mform->addElement('select', 'issuerid', get_string('chooseissuer', 'repository_nextcloud'), $types);
659 $mform->addRule('issuerid', get_string('required'), 'required', null, 'issuer');
660 $mform->addHelpButton('issuerid', 'chooseissuer', 'repository_nextcloud');
661 $mform->setType('issuerid', PARAM_INT);
662
663 // All issuers that are valid are displayed seperately (if any).
664 if (count($validissuers) === 0) {
665 $mform->addElement('static', null, '', get_string('no_right_issuers', 'repository_nextcloud'));
666 } else {
667 $mform->addElement('static', null, '', get_string('right_issuers', 'repository_nextcloud',
668 implode(', ', $validissuers)));
669 }
670
671 $mform->addElement('text', 'controlledlinkfoldername', get_string('foldername', 'repository_nextcloud'));
672 $mform->addHelpButton('controlledlinkfoldername', 'foldername', 'repository_nextcloud');
673 $mform->setType('controlledlinkfoldername', PARAM_TEXT);
674 $mform->setDefault('controlledlinkfoldername', 'Moodlefiles');
675
676 $mform->addElement('static', null, '', get_string('fileoptions', 'repository_nextcloud'));
677 $choices = [
678 'both' => get_string('both', 'repository_nextcloud'),
679 'internal' => get_string('internal', 'repository_nextcloud'),
680 'external' => get_string('external', 'repository_nextcloud'),
681 ];
682 $mform->addElement('select', 'supportedreturntypes', get_string('supportedreturntypes', 'repository_nextcloud'), $choices);
683
684 $choices = [
685 FILE_INTERNAL => get_string('internal', 'repository_nextcloud'),
686 FILE_CONTROLLED_LINK => get_string('external', 'repository_nextcloud'),
687 ];
688 $mform->addElement('select', 'defaultreturntype', get_string('defaultreturntype', 'repository_nextcloud'), $choices);
689 }
690
691 /**
692 * Save settings for repository instance
693 *
694 * @param array $options settings
695 * @return bool
696 */
697 public function set_option($options = array()) {
698 $options['issuerid'] = clean_param($options['issuerid'], PARAM_INT);
699 $options['controlledlinkfoldername'] = clean_param($options['controlledlinkfoldername'], PARAM_TEXT);
700
701 $ret = parent::set_option($options);
702 return $ret;
703 }
704
705 /**
706 * Names of the plugin settings
707 *
708 * @return array
709 */
710 public static function get_instance_option_names() {
711 return ['issuerid', 'controlledlinkfoldername',
712 'defaultreturntype', 'supportedreturntypes'];
713 }
714
715 /**
716 * Method to define which file-types are supported (hardcoded can not be changed in Admin Menu)
e8da9f7f 717 *
b4e24a82
NH
718 * By default FILE_INTERNAL is supported. In case a system account is connected and an issuer exist,
719 * FILE_CONTROLLED_LINK is supported.
e8da9f7f 720 *
b4e24a82
NH
721 * FILE_INTERNAL - the file is uploaded/downloaded and stored directly within the Moodle file system.
722 * FILE_CONTROLLED_LINK - creates a copy of the file in Nextcloud from which private shares to permitted users will be
723 * created. The file itself can not be changed any longer by the owner.
e8da9f7f 724 *
b4e24a82
NH
725 * @return int return type bitmask supported
726 */
727 public function supported_returntypes() {
e8da9f7f
DW
728 // We can only support references if the system account is connected.
729 if (!empty($this->issuer) && $this->issuer->is_system_account_connected()) {
730 $setting = $this->get_option('supportedreturntypes');
731 if ($setting === 'internal') {
732 return FILE_INTERNAL;
733 } else if ($setting === 'external') {
734 return FILE_CONTROLLED_LINK;
735 } else {
736 return FILE_CONTROLLED_LINK | FILE_INTERNAL;
b4e24a82 737 }
e8da9f7f
DW
738 } else {
739 return FILE_INTERNAL;
b4e24a82 740 }
b4e24a82
NH
741 }
742
e8da9f7f 743
b4e24a82
NH
744 /**
745 * Take the WebDAV `ls()' output and convert it into a format that Moodle's filepicker understands.
746 *
747 * @param string $dirpath Relative (urlencoded) path of the folder of interest.
748 * @param array $ls Output by WebDAV
749 * @return array Moodle-formatted list of directory contents; ready for use as $ret['list'] in get_listings
750 */
751 private function get_listing_convert_response($dirpath, $ls) {
752 global $OUTPUT;
753 $folders = array();
754 $files = array();
755 $parsedurl = issuer_management::parse_endpoint_url('webdav', $this->issuer);
756 $basepath = rtrim('/' . ltrim($parsedurl['path'], '/ '), '/ ');
757
758 foreach ($ls as $item) {
759 if (!empty($item['lastmodified'])) {
760 $item['lastmodified'] = strtotime($item['lastmodified']);
761 } else {
762 $item['lastmodified'] = null;
763 }
764
765 // Extracting object title from absolute path: First remove Nextcloud basepath.
766 $item['href'] = substr(urldecode($item['href']), strlen($basepath));
767 // Then remove relative path to current folder.
768 $title = substr($item['href'], strlen($dirpath));
769
770 if (!empty($item['resourcetype']) && $item['resourcetype'] == 'collection') {
771 // A folder.
772 if ($dirpath == $item['href']) {
773 // Skip "." listing.
774 continue;
775 }
776
777 $folders[strtoupper($title)] = array(
778 'title' => rtrim($title, '/'),
779 'thumbnail' => $OUTPUT->image_url(file_folder_icon(90))->out(false),
780 'children' => array(),
781 'datemodified' => $item['lastmodified'],
782 'path' => $item['href']
783 );
784 } else {
785 // A file.
786 $size = !empty($item['getcontentlength']) ? $item['getcontentlength'] : '';
787 $files[strtoupper($title)] = array(
788 'title' => $title,
789 'thumbnail' => $OUTPUT->image_url(file_extension_icon($title, 90))->out(false),
790 'size' => $size,
791 'datemodified' => $item['lastmodified'],
792 'source' => $item['href']
793 );
794 }
795 }
796 ksort($files);
797 ksort($folders);
798 return array_merge($folders, $files);
799 }
e8da9f7f 800
b4e24a82
NH
801 /**
802 * Print the login in a popup.
803 *
804 * @param array|null $attr Custom attributes to be applied to popup div.
805 */
806 private function print_login_popup($attr = null) {
807 global $OUTPUT;
808
809 $this->client = $this->get_user_oauth_client();
810 $url = new moodle_url($this->client->get_login_url());
811 $state = $url->get_param('state') . '&reloadparent=true';
812 $url->param('state', $state);
813
814 echo $OUTPUT->header();
815
4354a428 816 $button = new single_button($url, get_string('logintoaccount', 'repository', $this->get_name()),
b4e24a82
NH
817 'post', true);
818 $button->add_action(new popup_action('click', $url, 'Login'));
819 $button->class = 'mdl-align';
820 $button = $OUTPUT->render($button);
821 echo html_writer::div($button, '', $attr);
822
823 echo $OUTPUT->footer();
824 }
e8da9f7f 825
b4e24a82
NH
826 /**
827 * Prepare response of get_listing; namely
828 * - defining setting elements,
829 * - filling in the parent path of the currently-viewed directory.
e8da9f7f 830 *
b4e24a82
NH
831 * @param string $path Relative path
832 * @return array ret array for use as get_listing's $ret
833 */
834 private function get_listing_prepare_response($path) {
835 $ret = [
836 // Fetch the list dynamically. An AJAX request is sent to the server as soon as the user opens a folder.
837 'dynload' => true,
838 'nosearch' => true, // Disable search.
839 'nologin' => false, // Provide a login link because a user logs into his/her private Nextcloud storage.
840 'path' => array([ // Contains all parent paths to the current path.
841 'name' => $this->get_meta()->name,
842 'path' => '',
843 ]),
844 'defaultreturntype' => $this->default_returntype(),
845 'manage' => $this->issuer->get('baseurl'), // Provide button to go into file management interface quickly.
846 'list' => array(), // Contains all file/folder information and is required to build the file/folder tree.
847 ];
848
849 // If relative path is a non-top-level path, calculate all its parents' paths.
850 // This is used for navigation in the file picker.
851 if ($path != '/') {
852 $chunks = explode('/', trim($path, '/'));
853 $parent = '/';
854 // Every sub-path to the last part of the current path is a parent path.
855 foreach ($chunks as $chunk) {
856 $subpath = $parent . $chunk . '/';
857 $ret['path'][] = [
858 'name' => urldecode($chunk),
859 'path' => $subpath
860 ];
861 // Prepare next iteration.
862 $parent = $subpath;
863 }
864 }
865 return $ret;
866 }
e8da9f7f
DW
867
868 /**
869 * When a controlled link is clicked in the file picker get the human readable info about this file.
870 *
871 * @param string $reference
872 * @param int $filestatus
873 * @return string
874 */
875 public function get_reference_details($reference, $filestatus = 0) {
876 if ($this->disabled) {
877 throw new repository_exception('cannotdownload', 'repository');
878 }
879 if (empty($reference)) {
880 return get_string('unknownsource', 'repository');
881 }
882 $source = json_decode($reference);
883 $path = '';
884 if (!empty($source->usesystem) && !empty($source->name)) {
885 $path = $source->name;
886 }
887
888 return $path;
889 }
890}