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