Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]

   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  
  25  use repository_nextcloud\issuer_management;
  26  use repository_nextcloud\ocs_client;
  27  
  28  defined('MOODLE_INTERNAL') || die();
  29  
  30  require_once($CFG->dirroot . '/repository/lib.php');
  31  require_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   */
  40  class 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       * repository_nextcloud constructor.
  97       *
  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.
 150       *
 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.
 166       *
 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.
 186       *
 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);
 303  
 304          if ($xml === false ) {
 305              throw new \repository_nextcloud\request_exception(array('instance' => $this->get_name(),
 306                  'errormessage' => get_string('invalidresponse', 'repository_nextcloud')));
 307          }
 308  
 309          if ((string)$xml->meta->status !== 'ok') {
 310              throw new \repository_nextcloud\request_exception(array('instance' => $this->get_name(), 'errormessage' => sprintf(
 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      /**
 319       * This method does not do any translation of the file source.
 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) {
 325          // The simple relative path to the file is enough.
 326          return $source;
 327      }
 328  
 329      /**
 330       * Called when a file is selected as a "access control link".
 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 additional options affecting the file serving
 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  
 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',
 426                  get_string('noclientconnection', 'repository_nextcloud'));
 427              throw new \repository_nextcloud\request_exception(array('instance' => $repositoryname, 'errormessage' => $details));
 428          }
 429  
 430          // Download for offline usage. This is strictly read-only, so the file need not be shared.
 431          if (!empty($options['offline'])) {
 432              // Download from system account and provide the file to the user.
 433              $linkmanager = new \repository_nextcloud\access_controlled_link_manager($this->ocsclient,
 434                  $this->get_system_oauth_client(), $this->get_system_ocs_client(), $this->issuer, $repositoryname);
 435  
 436              // Create temp path, then download into it.
 437              $filename = basename($reference->link);
 438              $tmppath = make_request_directory() . '/' . $filename;
 439              $linkmanager->download_for_offline_usage($reference->link, $tmppath);
 440  
 441              // Output the obtained file to the user and remove it from disk.
 442              send_temp_file($tmppath, $filename);
 443  
 444              // That's all.
 445              return;
 446          }
 447  
 448          if (!$this->client->is_logged_in()) {
 449              $this->print_login_popup(['style' => 'margin-top: 250px'], $options['embed']);
 450              return;
 451          }
 452  
 453          // Determining writeability of file from the using context.
 454          // Variable $info is null|\file_info. file_info::is_writable is only true if user may write for any reason.
 455          $fb = get_file_browser();
 456          $context = context::instance_by_id($storedfile->get_contextid(), MUST_EXIST);
 457          $info = $fb->get_file_info($context,
 458              $storedfile->get_component(),
 459              $storedfile->get_filearea(),
 460              $storedfile->get_itemid(),
 461              $storedfile->get_filepath(),
 462              $storedfile->get_filename());
 463          $maywrite = !empty($info) && $info->is_writable();
 464  
 465          $this->initiate_webdavclient();
 466  
 467          // Create the a manager to handle steps.
 468          $linkmanager = new \repository_nextcloud\access_controlled_link_manager($this->ocsclient, $this->get_system_oauth_client(),
 469              $this->get_system_ocs_client(), $this->issuer, $repositoryname);
 470  
 471          // 2. Check whether user has folder for files otherwise create it.
 472          $linkmanager->create_storage_folder($this->controlledlinkfoldername, $this->dav);
 473  
 474          $userinfo = $this->client->get_userinfo();
 475          $username = $userinfo['username'];
 476  
 477          // Creates a share between the systemaccount and the user.
 478          $responsecreateshare = $linkmanager->create_share_user_sysaccount($reference->link, $username, $maywrite);
 479  
 480          $statuscode = $responsecreateshare['statuscode'];
 481  
 482          if ($statuscode == 403) {
 483              $shareid = $linkmanager->get_shares_from_path($reference->link, $username);
 484          } else if ($statuscode == 100) {
 485              $filetarget = $linkmanager->get_share_information_from_shareid($responsecreateshare['shareid'], $username);
 486              $copyresult = $linkmanager->transfer_file_to_path($filetarget, $this->controlledlinkfoldername,
 487                  'move', $this->dav);
 488              if (!($copyresult == 201 || $copyresult == 412)) {
 489                  throw new \repository_nextcloud\request_exception(array('instance' => $repositoryname,
 490                      'errormessage' => get_string('couldnotmove', 'repository_nextcloud', $this->controlledlinkfoldername)));
 491              }
 492              $shareid = $responsecreateshare['shareid'];
 493          } else if ($statuscode == 997) {
 494              throw new \repository_nextcloud\request_exception(array('instance' => $repositoryname,
 495                  'errormessage' => get_string('notauthorized', 'repository_nextcloud')));
 496          } else {
 497              $details = get_string('filenotaccessed', 'repository_nextcloud');
 498              throw new \repository_nextcloud\request_exception(array('instance' => $repositoryname, 'errormessage' => $details));
 499          }
 500          $filetarget = $linkmanager->get_share_information_from_shareid((int)$shareid, $username);
 501  
 502          // Obtain the file from Nextcloud using a Bearer token authenticated connection because we cannot perform a redirect here.
 503          // The reason is that Nextcloud uses samesite cookie validation, i.e. a redirected request would not be authenticated.
 504          // (Also the browser might use the session of a Nextcloud user that is different from the one that is known to Moodle.)
 505          $filename = basename($filetarget);
 506          $tmppath = make_request_directory() . '/' . $filename;
 507          $this->dav->open();
 508  
 509          // Concat webdav path with file path.
 510          $webdavendpoint = issuer_management::parse_endpoint_url('webdav', $this->issuer);
 511          $filetarget = ltrim($filetarget, '/');
 512          $filetarget = $webdavendpoint['path'] . $filetarget;
 513  
 514          // Write file into temp location.
 515          if (!$this->dav->get_file($filetarget, $tmppath)) {
 516              $this->dav->close();
 517              throw new repository_exception('cannotdownload', 'repository');
 518          }
 519          $this->dav->close();
 520  
 521          // Output the obtained file to the user and remove it from disk.
 522          send_temp_file($tmppath, $filename);
 523      }
 524  
 525      /**
 526       * Which return type should be selected by default.
 527       *
 528       * @return int
 529       */
 530      public function default_returntype() {
 531          $setting = $this->get_option('defaultreturntype');
 532          $supported = $this->get_option('supportedreturntypes');
 533          if (($setting == FILE_INTERNAL && $supported !== 'external') || $supported === 'internal') {
 534              return FILE_INTERNAL;
 535          }
 536          return FILE_CONTROLLED_LINK;
 537      }
 538  
 539      /**
 540       * Return names of the general options.
 541       * By default: no general option name.
 542       *
 543       * @return array
 544       */
 545      public static function get_type_option_names() {
 546          return array();
 547      }
 548  
 549      /**
 550       * Function which checks whether the user is logged in on the Nextcloud instance.
 551       *
 552       * @return bool false, if no Access Token is set or can be requested.
 553       */
 554      public function check_login() {
 555          $client = $this->get_user_oauth_client();
 556          return $client->is_logged_in();
 557      }
 558  
 559      /**
 560       * Get a cached user authenticated oauth client.
 561       *
 562       * @param bool|moodle_url $overrideurl Use this url instead of the repo callback.
 563       * @return \core\oauth2\client
 564       */
 565      protected function get_user_oauth_client($overrideurl = false) {
 566          if ($this->client) {
 567              return $this->client;
 568          }
 569          if ($overrideurl) {
 570              $returnurl = $overrideurl;
 571          } else {
 572              $returnurl = new moodle_url('/repository/repository_callback.php');
 573              $returnurl->param('callback', 'yes');
 574              $returnurl->param('repo_id', $this->id);
 575              $returnurl->param('sesskey', sesskey());
 576          }
 577          $this->client = \core\oauth2\api::get_user_oauth_client($this->issuer, $returnurl, self::SCOPES);
 578          return $this->client;
 579      }
 580  
 581      /**
 582       * Prints a simple Login Button which redirects to an authorization window from Nextcloud.
 583       *
 584       * @return mixed login window properties.
 585       * @throws coding_exception
 586       */
 587      public function print_login() {
 588          $client = $this->get_user_oauth_client();
 589          $loginurl = $client->get_login_url();
 590          if ($this->options['ajax']) {
 591              $ret = array();
 592              $btn = new \stdClass();
 593              $btn->type = 'popup';
 594              $btn->url = $loginurl->out(false);
 595              $ret['login'] = array($btn);
 596              return $ret;
 597          } else {
 598              echo html_writer::link($loginurl, get_string('login', 'repository'),
 599                      array('target' => '_blank',  'rel' => 'noopener noreferrer'));
 600          }
 601      }
 602  
 603      /**
 604       * Deletes the held Access Token and prints the Login window.
 605       *
 606       * @return array login window properties.
 607       */
 608      public function logout() {
 609          $client = $this->get_user_oauth_client();
 610          $client->log_out();
 611          return parent::logout();
 612      }
 613  
 614      /**
 615       * Sets up access token after the redirection from Nextcloud.
 616       */
 617      public function callback() {
 618          $client = $this->get_user_oauth_client();
 619          // If an Access Token is stored within the client, it has to be deleted to prevent the addition
 620          // of an Bearer authorization header in the request method.
 621          $client->log_out();
 622  
 623          // This will upgrade to an access token if we have an authorization code and save the access token in the session.
 624          $client->is_logged_in();
 625      }
 626  
 627      /**
 628       * Create an instance for this plug-in
 629       *
 630       * @param string $type the type of the repository
 631       * @param int $userid the user id
 632       * @param stdClass $context the context
 633       * @param array $params the options for this instance
 634       * @param int $readonly whether to create it readonly or not (defaults to not)
 635       * @return mixed
 636       * @throws dml_exception
 637       * @throws required_capability_exception
 638       */
 639      public static function create($type, $userid, $context, $params, $readonly=0) {
 640          require_capability('moodle/site:config', context_system::instance());
 641          return parent::create($type, $userid, $context, $params, $readonly);
 642      }
 643  
 644      /**
 645       * This method adds a select form and additional information to the settings form..
 646       *
 647       * @param \moodleform $mform Moodle form (passed by reference)
 648       * @return bool|void
 649       * @throws coding_exception
 650       * @throws dml_exception
 651       */
 652      public static function instance_config_form($mform) {
 653          if (!has_capability('moodle/site:config', context_system::instance())) {
 654              $mform->addElement('static', null, '',  get_string('nopermissions', 'error', get_string('configplugin',
 655                  'repository_nextcloud')));
 656              return false;
 657          }
 658  
 659          // Load configured issuers.
 660          $issuers = core\oauth2\api::get_all_issuers();
 661          $types = array();
 662  
 663          // Validates which issuers implement the right endpoints. WebDav is necessary for Nextcloud.
 664          $validissuers = [];
 665          foreach ($issuers as $issuer) {
 666              $types[$issuer->get('id')] = $issuer->get('name');
 667              if (\repository_nextcloud\issuer_management::is_valid_issuer($issuer)) {
 668                  $validissuers[] = $issuer->get('name');
 669              }
 670          }
 671  
 672          // Render the form.
 673          $url = new \moodle_url('/admin/tool/oauth2/issuers.php');
 674          $mform->addElement('static', null, '', get_string('oauth2serviceslink', 'repository_nextcloud', $url->out()));
 675  
 676          $mform->addElement('select', 'issuerid', get_string('chooseissuer', 'repository_nextcloud'), $types);
 677          $mform->addRule('issuerid', get_string('required'), 'required', null, 'issuer');
 678          $mform->addHelpButton('issuerid', 'chooseissuer', 'repository_nextcloud');
 679          $mform->setType('issuerid', PARAM_INT);
 680  
 681          // All issuers that are valid are displayed seperately (if any).
 682          if (count($validissuers) === 0) {
 683              $mform->addElement('static', null, '', get_string('no_right_issuers', 'repository_nextcloud'));
 684          } else {
 685              $mform->addElement('static', null, '', get_string('right_issuers', 'repository_nextcloud',
 686                  implode(', ', $validissuers)));
 687          }
 688  
 689          $mform->addElement('text', 'controlledlinkfoldername', get_string('foldername', 'repository_nextcloud'));
 690          $mform->addHelpButton('controlledlinkfoldername', 'foldername', 'repository_nextcloud');
 691          $mform->setType('controlledlinkfoldername', PARAM_TEXT);
 692          $mform->setDefault('controlledlinkfoldername', 'Moodlefiles');
 693  
 694          $mform->addElement('static', null, '', get_string('fileoptions', 'repository_nextcloud'));
 695          $choices = [
 696              'both' => get_string('both', 'repository_nextcloud'),
 697              'internal' => get_string('internal', 'repository_nextcloud'),
 698              'external' => get_string('external', 'repository_nextcloud'),
 699          ];
 700          $mform->addElement('select', 'supportedreturntypes', get_string('supportedreturntypes', 'repository_nextcloud'), $choices);
 701  
 702          $choices = [
 703              FILE_INTERNAL => get_string('internal', 'repository_nextcloud'),
 704              FILE_CONTROLLED_LINK => get_string('external', 'repository_nextcloud'),
 705          ];
 706          $mform->addElement('select', 'defaultreturntype', get_string('defaultreturntype', 'repository_nextcloud'), $choices);
 707      }
 708  
 709      /**
 710       * Save settings for repository instance
 711       *
 712       * @param array $options settings
 713       * @return bool
 714       */
 715      public function set_option($options = array()) {
 716          $options['issuerid'] = clean_param($options['issuerid'], PARAM_INT);
 717          $options['controlledlinkfoldername'] = clean_param($options['controlledlinkfoldername'], PARAM_TEXT);
 718  
 719          $ret = parent::set_option($options);
 720          return $ret;
 721      }
 722  
 723      /**
 724       * Names of the plugin settings
 725       *
 726       * @return array
 727       */
 728      public static function get_instance_option_names() {
 729          return ['issuerid', 'controlledlinkfoldername',
 730              'defaultreturntype', 'supportedreturntypes'];
 731      }
 732  
 733      /**
 734       * Method to define which file-types are supported (hardcoded can not be changed in Admin Menu)
 735       *
 736       * By default FILE_INTERNAL is supported. In case a system account is connected and an issuer exist,
 737       * FILE_CONTROLLED_LINK is supported.
 738       *
 739       * FILE_INTERNAL - the file is uploaded/downloaded and stored directly within the Moodle file system.
 740       * FILE_CONTROLLED_LINK - creates a copy of the file in Nextcloud from which private shares to permitted users will be
 741       * created. The file itself can not be changed any longer by the owner.
 742       *
 743       * @return int return type bitmask supported
 744       */
 745      public function supported_returntypes() {
 746          // We can only support references if the system account is connected.
 747          if (!empty($this->issuer) && $this->issuer->is_system_account_connected()) {
 748              $setting = $this->get_option('supportedreturntypes');
 749              if ($setting === 'internal') {
 750                  return FILE_INTERNAL;
 751              } else if ($setting === 'external') {
 752                  return FILE_CONTROLLED_LINK;
 753              } else {
 754                  return FILE_CONTROLLED_LINK | FILE_INTERNAL;
 755              }
 756          } else {
 757              return FILE_INTERNAL;
 758          }
 759      }
 760  
 761  
 762      /**
 763       * Take the WebDAV `ls()' output and convert it into a format that Moodle's filepicker understands.
 764       *
 765       * @param string $dirpath Relative (urlencoded) path of the folder of interest.
 766       * @param array $ls Output by WebDAV
 767       * @return array Moodle-formatted list of directory contents; ready for use as $ret['list'] in get_listings
 768       */
 769      private function get_listing_convert_response($dirpath, $ls) {
 770          global $OUTPUT;
 771          $folders = array();
 772          $files = array();
 773          $parsedurl = issuer_management::parse_endpoint_url('webdav', $this->issuer);
 774          $basepath = rtrim('/' . ltrim($parsedurl['path'], '/ '), '/ ');
 775  
 776          foreach ($ls as $item) {
 777              if (!empty($item['lastmodified'])) {
 778                  $item['lastmodified'] = strtotime($item['lastmodified']);
 779              } else {
 780                  $item['lastmodified'] = null;
 781              }
 782  
 783              // Extracting object title from absolute path: First remove Nextcloud basepath.
 784              $item['href'] = substr(urldecode($item['href']), strlen($basepath));
 785              // Then remove relative path to current folder.
 786              $title = substr($item['href'], strlen($dirpath));
 787  
 788              if (!empty($item['resourcetype']) && $item['resourcetype'] == 'collection') {
 789                  // A folder.
 790                  if ($dirpath == $item['href']) {
 791                      // Skip "." listing.
 792                      continue;
 793                  }
 794  
 795                  $folders[strtoupper($title)] = array(
 796                      'title' => rtrim($title, '/'),
 797                      'thumbnail' => $OUTPUT->image_url(file_folder_icon(90))->out(false),
 798                      'children' => array(),
 799                      'datemodified' => $item['lastmodified'],
 800                      'path' => $item['href']
 801                  );
 802              } else {
 803                  // A file.
 804                  $size = !empty($item['getcontentlength']) ? $item['getcontentlength'] : '';
 805                  $files[strtoupper($title)] = array(
 806                      'title' => $title,
 807                      'thumbnail' => $OUTPUT->image_url(file_extension_icon($title, 90))->out(false),
 808                      'size' => $size,
 809                      'datemodified' => $item['lastmodified'],
 810                      'source' => $item['href']
 811                  );
 812              }
 813          }
 814          ksort($files);
 815          ksort($folders);
 816          return array_merge($folders, $files);
 817      }
 818  
 819      /**
 820       * Print the login in a popup.
 821       *
 822       * @param array|null $attr Custom attributes to be applied to popup div.
 823       */
 824      private function print_login_popup($attr = null, $embed = false) {
 825          global $OUTPUT, $PAGE;
 826  
 827          if ($embed) {
 828              $PAGE->set_pagelayout('embedded');
 829          }
 830  
 831          $this->client = $this->get_user_oauth_client();
 832          $url = new moodle_url($this->client->get_login_url());
 833          $state = $url->get_param('state') . '&reloadparent=true';
 834          $url->param('state', $state);
 835  
 836          echo $OUTPUT->header();
 837  
 838          $button = new single_button($url, get_string('logintoaccount', 'repository', $this->get_name()),
 839              'post', true);
 840          $button->add_action(new popup_action('click', $url, 'Login'));
 841          $button->class = 'mdl-align';
 842          $button = $OUTPUT->render($button);
 843          echo html_writer::div($button, '', $attr);
 844  
 845          echo $OUTPUT->footer();
 846      }
 847  
 848      /**
 849       * Prepare response of get_listing; namely
 850       * - defining setting elements,
 851       * - filling in the parent path of the currently-viewed directory.
 852       *
 853       * @param string $path Relative path
 854       * @return array ret array for use as get_listing's $ret
 855       */
 856      private function get_listing_prepare_response($path) {
 857          $ret = [
 858              // Fetch the list dynamically. An AJAX request is sent to the server as soon as the user opens a folder.
 859              'dynload' => true,
 860              'nosearch' => true, // Disable search.
 861              'nologin' => false, // Provide a login link because a user logs into his/her private Nextcloud storage.
 862              'path' => array([ // Contains all parent paths to the current path.
 863                  'name' => $this->get_meta()->name,
 864                  'path' => '',
 865              ]),
 866              'defaultreturntype' => $this->default_returntype(),
 867              'manage' => $this->issuer->get('baseurl'), // Provide button to go into file management interface quickly.
 868              'list' => array(), // Contains all file/folder information and is required to build the file/folder tree.
 869          ];
 870  
 871          // If relative path is a non-top-level path, calculate all its parents' paths.
 872          // This is used for navigation in the file picker.
 873          if ($path != '/') {
 874              $chunks = explode('/', trim($path, '/'));
 875              $parent = '/';
 876              // Every sub-path to the last part of the current path is a parent path.
 877              foreach ($chunks as $chunk) {
 878                  $subpath = $parent . $chunk . '/';
 879                  $ret['path'][] = [
 880                      'name' => urldecode($chunk),
 881                      'path' => $subpath
 882                  ];
 883                  // Prepare next iteration.
 884                  $parent = $subpath;
 885              }
 886          }
 887          return $ret;
 888      }
 889  
 890      /**
 891       * When a controlled link is clicked in the file picker get the human readable info about this file.
 892       *
 893       * @param string $reference
 894       * @param int $filestatus
 895       * @return string
 896       */
 897      public function get_reference_details($reference, $filestatus = 0) {
 898          if ($this->disabled) {
 899              throw new repository_exception('cannotdownload', 'repository');
 900          }
 901          if (empty($reference)) {
 902              return get_string('unknownsource', 'repository');
 903          }
 904          $source = json_decode($reference);
 905          $path = '';
 906          if (!empty($source->usesystem) && !empty($source->name)) {
 907              $path = $source->name;
 908          }
 909  
 910          return $path;
 911      }
 912  }