As part of the registration process, you will need to enter the following URL as \'Authorized Redirect URIs\':
{$a->callbackurl}
Once registered, you will be provided with a client ID and secret which can be used to configure all Google Drive and Picasa plugins.
Please also note that you will have to enable the service \'Drive API\'.
';
$string['pluginname'] = 'Google Drive';
$string['presentationformat'] = 'Default presentation import format';
-$string['secret'] = 'Secret';
-$string['servicenotenabled'] = 'Access not configured. Make sure the service \'Drive API\' is enabled.';
$string['spreadsheetformat'] = 'Default spreadsheet import format';
+$string['issuer'] = 'OAuth 2 service';
+$string['issuer_help'] = 'Select the OAuth 2 service that is configured to talk to the Google Drive API. If the services does not exist yet, you might need to create it.';
+$string['servicenotenabled'] = 'Access not configured. Make sure the service \'Drive API\' is enabled.';
+$string['oauth2serviceslink'] = 'OAuth 2 Services Configuration';
+$string['searchfor'] = 'Search for {$a}';
+
+// Deprecated since Moodle 3.3.
+$string['oauthinfo'] = '
To use this plugin, you must register your site with Google, as described in the documentation Google OAuth 2.0 setup.
As part of the registration process, you will need to enter the following URL as \'Authorized Redirect URIs\':
{$a->callbackurl}
Once registered, you will be provided with a client ID and secret which can be used to configure all Google Drive and Picasa plugins.
Please also note that you will have to enable the service \'Drive API\'.
';
+$string['secret'] = 'Secret';
+$string['clientid'] = 'Client ID';
diff --git a/repository/googledocs/lib.php b/repository/googledocs/lib.php
index 82fdfe45e4f..852ee5d1bae 100644
--- a/repository/googledocs/lib.php
+++ b/repository/googledocs/lib.php
@@ -39,28 +39,21 @@ require_once($CFG->libdir . '/google/lib.php');
class repository_googledocs extends repository {
/**
- * Google Client.
- * @var Google_Client
+ * OAuth 2 client
+ * @var \core\oauth2\client
*/
private $client = null;
/**
- * Google Drive Service.
- * @var Google_Drive_Service
+ * OAuth 2 Issuer
+ * @var \core\oauth2\issuer
*/
- private $service = null;
+ private $issuer = null;
/**
- * Session key to store the accesstoken.
- * @var string
+ * Additional scopes required for drive.
*/
- const SESSIONKEY = 'googledrive_accesstoken';
-
- /**
- * URI to the callback file for OAuth.
- * @var string
- */
- const CALLBACKURL = '/admin/oauth2callback.php';
+ const SCOPES = 'https://www.googleapis.com/auth/drive';
/**
* Constructor.
@@ -74,52 +67,26 @@ class repository_googledocs extends repository {
public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
parent::__construct($repositoryid, $context, $options, $readonly = 0);
- $callbackurl = new moodle_url(self::CALLBACKURL);
-
- $this->client = get_google_client();
- $this->client->setClientId(get_config('googledocs', 'clientid'));
- $this->client->setClientSecret(get_config('googledocs', 'secret'));
- $this->client->setScopes(array(Google_Service_Drive::DRIVE_READONLY));
- $this->client->setRedirectUri($callbackurl->out(false));
- $this->service = new Google_Service_Drive($this->client);
-
- $this->check_login();
+ $this->issuer = \core\oauth2\api::get_issuer(get_config('googledocs', 'issuerid'));
}
/**
- * Returns the access token if any.
+ * Get a cached user authenticated oauth client.
*
- * @return string|null access token.
+ * @return \core\oauth2\client
*/
- protected function get_access_token() {
- global $SESSION;
- if (isset($SESSION->{self::SESSIONKEY})) {
- return $SESSION->{self::SESSIONKEY};
+ protected function get_user_oauth_client() {
+ if ($this->client) {
+ return $this->client;
}
- return null;
- }
+ $returnurl = new moodle_url('/repository/repository_callback.php');
+ $returnurl->param('callback', 'yes');
+ $returnurl->param('repo_id', $this->id);
+ $returnurl->param('sesskey', sesskey());
- /**
- * Store the access token in the session.
- *
- * @param string $token token to store.
- * @return void
- */
- protected function store_access_token($token) {
- global $SESSION;
- $SESSION->{self::SESSIONKEY} = $token;
- }
+ $this->client = \core\oauth2\api::get_user_oauth_client($this->issuer, $returnurl, self::SCOPES);
- /**
- * Callback method during authentication.
- *
- * @return void
- */
- public function callback() {
- if ($code = optional_param('oauth2code', null, PARAM_RAW)) {
- $this->client->authenticate($code);
- $this->store_access_token($this->client->getAccessToken());
- }
+ return $this->client;
}
/**
@@ -128,11 +95,8 @@ class repository_googledocs extends repository {
* @return bool true when logged in.
*/
public function check_login() {
- if ($token = $this->get_access_token()) {
- $this->client->setAccessToken($token);
- return true;
- }
- return false;
+ $client = $this->get_user_oauth_client();
+ return $client->is_logged_in();
}
/**
@@ -141,13 +105,9 @@ class repository_googledocs extends repository {
* @return void|array for ajax.
*/
public function print_login() {
- $returnurl = new moodle_url('/repository/repository_callback.php');
- $returnurl->param('callback', 'yes');
- $returnurl->param('repo_id', $this->id);
- $returnurl->param('sesskey', sesskey());
+ $client = $this->get_user_oauth_client();
+ $url = $client->get_login_url();
- $url = new moodle_url($this->client->createAuthUrl());
- $url->param('state', $returnurl->out_as_local_url(false));
if ($this->options['ajax']) {
$popup = new stdClass();
$popup->type = 'popup';
@@ -159,11 +119,11 @@ class repository_googledocs extends repository {
}
/**
- * Build the breadcrumb from a path.
- *
- * @param string $path to create a breadcrumb from.
- * @return array containing name and path of each crumb.
- */
+ * Build the breadcrumb from a path.
+ *
+ * @param string $path to create a breadcrumb from.
+ * @return array containing name and path of each crumb.
+ */
protected function build_breadcrumb($path) {
$bread = explode('/', $path);
$crumbtrail = '';
@@ -181,15 +141,15 @@ class repository_googledocs extends repository {
}
/**
- * Generates a safe path to a node.
- *
- * Typically, a node will be id|Name of the node.
- *
- * @param string $id of the node.
- * @param string $name of the node, will be URL encoded.
- * @param string $root to append the node on, must be a result of this function.
- * @return string path to the node.
- */
+ * Generates a safe path to a node.
+ *
+ * Typically, a node will be id|Name of the node.
+ *
+ * @param string $id of the node.
+ * @param string $name of the node, will be URL encoded.
+ * @param string $root to append the node on, must be a result of this function.
+ * @return string path to the node.
+ */
protected function build_node_path($id, $name = '', $root = '') {
$path = $id;
if (!empty($name)) {
@@ -202,12 +162,12 @@ class repository_googledocs extends repository {
}
/**
- * Returns information about a node in a path.
- *
- * @see self::build_node_path()
- * @param string $node to extrat information from.
- * @return array about the node.
- */
+ * Returns information about a node in a path.
+ *
+ * @see self::build_node_path()
+ * @param string $node to extrat information from.
+ * @return array about the node.
+ */
protected function explode_node_path($node) {
if (strpos($node, '|') !== false) {
list($id, $name) = explode('|', $node, 2);
@@ -265,16 +225,17 @@ class repository_googledocs extends repository {
/**
* Search throughout the Google Drive.
*
- * @param string $search_text text to search for.
+ * @param string $searchtext text to search for.
* @param int $page search page.
* @return array of results.
*/
- public function search($search_text, $page = 0) {
+ public function search($searchtext, $page = 0) {
$path = $this->build_node_path('root', get_string('pluginname', 'repository_googledocs'));
- $path = $this->build_node_path('search', $search_text, $path);
+ $str = get_string('searchfor', 'repository_googledocs', $searchtext);
+ $path = $this->build_node_path('search', $str, $path);
// Query the Drive.
- $q = "fullText contains '" . str_replace("'", "\'", $search_text) . "'";
+ $q = "fullText contains '" . str_replace("'", "\'", $searchtext) . "'";
$q .= ' AND trashed = false';
$results = $this->query($q, $path);
@@ -304,14 +265,17 @@ class repository_googledocs extends repository {
$files = array();
$folders = array();
- $fields = "items(id,title,mimeType,downloadUrl,fileExtension,exportLinks,modifiedDate,fileSize,thumbnailLink)";
- $params = array('q' => $q, 'fields' => $fields);
$config = get_config('googledocs');
+ $fields = "files(id,name,mimeType,webContentLink,fileExtension,modifiedTime,size,thumbnailLink,iconLink)";
+ $params = array('q' => $q, 'fields' => $fields, 'spaces' => 'drive');
try {
// Retrieving files and folders.
- $response = $this->service->files->listFiles($params);
- } catch (Google_Service_Exception $e) {
+ $client = $this->get_user_oauth_client();
+ $service = new repository_googledocs\rest($client);
+
+ $response = $service->call('list', $params);
+ } catch (Exception $e) {
if ($e->getCode() == 403 && strpos($e->getMessage(), 'Access Not Configured') !== false) {
// This is raised when the service Drive API has not been enabled on Google APIs control panel.
throw new repository_exception('servicenotenabled', 'repository_googledocs');
@@ -320,14 +284,15 @@ class repository_googledocs extends repository {
}
}
- $items = isset($response['items']) ? $response['items'] : array();
- foreach ($items as $item) {
- if ($item['mimeType'] == 'application/vnd.google-apps.folder') {
+ $base = 'https://www.googleapis.com/drive/v3';
+ $gfiles = isset($response->files) ? $response->files : array();
+ foreach ($gfiles as $gfile) {
+ if ($gfile->mimeType == 'application/vnd.google-apps.folder') {
// This is a folder.
- $folders[$item['title'] . $item['id']] = array(
- 'title' => $item['title'],
- 'path' => $this->build_node_path($item['id'], $item['title'], $path),
- 'date' => strtotime($item['modifiedDate']),
+ $folders[$gfile->name . $gfile->id] = array(
+ 'title' => $gfile->name,
+ 'path' => $this->build_node_path($gfile->id, $gfile->name, $path),
+ 'date' => strtotime($gfile->modifiedTime),
'thumbnail' => $OUTPUT->image_url(file_folder_icon(64))->out(false),
'thumbnail_height' => 64,
'thumbnail_width' => 64,
@@ -335,16 +300,18 @@ class repository_googledocs extends repository {
);
} else {
// This is a file.
- if (isset($item['fileExtension'])) {
- // The file has an extension, therefore there is a download link.
- $title = $item['title'];
- $source = $item['downloadUrl'];
+ if (isset($gfile->fileExtension)) {
+ // The file has an extension, therefore we can download it.
+ $title = $gfile->name;
+ $params = ['alt' => 'media'];
+ $sourceurl = new moodle_url($base . '/files/' . $gfile->id, $params);
+ $source = $sourceurl->out(false);
} else {
// The file is probably a Google Doc file, we get the corresponding export link.
// This should be improved by allowing the user to select the type of export they'd like.
- $type = str_replace('application/vnd.google-apps.', '', $item['mimeType']);
+ $type = str_replace('application/vnd.google-apps.', '', $gfile->mimeType);
$title = '';
- $exportType = '';
+ $exporttype = '';
$types = get_mimetypes_array();
switch ($type){
@@ -355,54 +322,52 @@ class repository_googledocs extends repository {
// Moodle user 'text/rtf' as the MIME type for RTF files.
// Google uses 'application/rtf' for the same type of file.
// See https://developers.google.com/drive/v3/web/manage-downloads.
- $exportType = 'application/rtf';
+ $exporttype = 'application/rtf';
} else {
- $exportType = $types[$ext]['type'];
+ $exporttype = $types[$ext]['type'];
}
break;
case 'presentation':
$ext = $config->presentationformat;
$title = $item['title'] . '.'. $ext;
- $exportType = $types[$ext]['type'];
+ $exporttype = $types[$ext]['type'];
break;
case 'spreadsheet':
$ext = $config->spreadsheetformat;
$title = $item['title'] . '.'. $ext;
- $exportType = $types[$ext]['type'];
+ $exporttype = $types[$ext]['type'];
break;
case 'drawing':
$ext = $config->drawingformat;
$title = $item['title'] . '.'. $ext;
- $exportType = $types[$ext]['type'];
+ $exporttype = $types[$ext]['type'];
break;
}
// Skips invalid/unknown types.
- if (empty($title) || !isset($item['exportLinks'][$exportType])) {
+ if (empty($title)) {
continue;
}
- $source = $item['exportLinks'][$exportType];
+ $params = ['mimeType' => $exporttype];
+ $sourceurl = new moodle_url($base . '/files/' . $gfile->id . '/export', $params);
+ $source = $sourceurl->out(false);
}
- // Adds the file to the file list. Using the itemId along with the title as key
+ // Adds the file to the file list. Using the itemId along with the name as key
// of the array because Google Drive allows files with identical names.
- $files[$title . $item['id']] = array(
+ $thumb = '';
+ if (isset($gfile->thumbnailLink)) {
+ $thumb = $gfile->thumbnailLink;
+ } else if (isset($gfile->iconLink)) {
+ $thumb = $gfile->iconLink;
+ }
+ $files[$title . $gfile->id] = array(
'title' => $title,
'source' => $source,
- 'date' => strtotime($item['modifiedDate']),
- 'size' => isset($item['fileSize']) ? $item['fileSize'] : null,
- 'thumbnail' => $OUTPUT->image_url(file_extension_icon($title, 64))->out(false),
+ 'date' => strtotime($gfile->modifiedTime),
+ 'size' => isset($gfile->size) ? $gfile->size : null,
+ 'thumbnail' => $thumb,
'thumbnail_height' => 64,
'thumbnail_width' => 64,
- // Do not use real thumbnails as they wouldn't work if the user disabled 3rd party
- // plugins in his browser, or if they're not logged in their Google account.
);
-
- // Sometimes the real thumbnails can't be displayed, for example if 3rd party cookies are disabled
- // or if the user is not logged in Google anymore. But this restriction does not seem to be applied
- // to a small subset of files.
- $extension = strtolower(pathinfo($title, PATHINFO_EXTENSION));
- if (isset($item['thumbnailLink']) && in_array($extension, array('jpg', 'png', 'txt', 'pdf'))) {
- $files[$title . $item['id']]['realthumbnail'] = $item['thumbnailLink'];
- }
}
}
@@ -419,7 +384,8 @@ class repository_googledocs extends repository {
* @return string
*/
public function logout() {
- $this->store_access_token(null);
+ $client = $this->get_user_oauth_client();
+ $client->log_out();
return parent::logout();
}
@@ -433,18 +399,18 @@ class repository_googledocs extends repository {
public function get_file($reference, $filename = '') {
global $CFG;
- $auth = $this->client->getAuth();
- $request = $auth->authenticatedRequest(new Google_Http_Request($reference));
- if ($request->getResponseHttpCode() == 200) {
- $path = $this->prepare_file($filename);
- $content = $request->getResponseBody();
- if (file_put_contents($path, $content) !== false) {
- @chmod($path, $CFG->filepermissions);
- return array(
- 'path' => $path,
- 'url' => $reference
- );
- }
+ $client = $this->get_user_oauth_client();
+
+ $path = $this->prepare_file($filename);
+ $options = ['filepath' => $path, 'timeout' => 15, 'followlocation' => true, 'maxredirs' => 5];
+ $result = $client->download_one($reference, null, $options);
+
+ if ($result) {
+ @chmod($path, $CFG->filepermissions);
+ return array(
+ 'path' => $path,
+ 'url' => $reference
+ );
}
throw new repository_exception('cannotdownload', 'repository');
}
@@ -490,11 +456,20 @@ class repository_googledocs extends repository {
* @return array
*/
public static function get_type_option_names() {
- return array('clientid', 'secret', 'pluginname',
+ return array('issuerid', 'pluginname',
'documentformat', 'drawingformat',
'presentationformat', 'spreadsheetformat');
}
+ /**
+ * Store the access token.
+ */
+ public function callback() {
+ $client = $this->get_user_oauth_client();
+ // This will upgrade to an access token if we have an authorization code.
+ $client->is_logged_in();
+ }
+
/**
* Edit/Create Admin Settings Moodle form.
*
@@ -502,25 +477,24 @@ class repository_googledocs extends repository {
* @param string $classname repository class name.
*/
public static function type_config_form($mform, $classname = 'repository') {
- $callbackurl = new moodle_url(self::CALLBACKURL);
+ $url = (string)new moodle_url('/admin/tool/oauth2/issuers.php');
- $a = new stdClass;
- $a->docsurl = get_docs_url('Google_OAuth_2.0_setup');
- $a->callbackurl = $callbackurl->out(false);
-
- $mform->addElement('static', null, '', get_string('oauthinfo', 'repository_googledocs', $a));
+ $mform->addElement('static', null, '', get_string('oauth2serviceslink', 'repository_googledocs', $url));
parent::type_config_form($mform);
- $mform->addElement('text', 'clientid', get_string('clientid', 'repository_googledocs'));
- $mform->setType('clientid', PARAM_RAW_TRIMMED);
- $mform->addElement('text', 'secret', get_string('secret', 'repository_googledocs'));
- $mform->setType('secret', PARAM_RAW_TRIMMED);
+ $options = [];
+ $issuers = \core\oauth2\api::get_all_issuers();
+
+ foreach ($issuers as $issuer) {
+ $options[$issuer->get('id')] = s($issuer->get('name'));
+ }
+ $mform->addElement('select', 'issuerid', get_string('issuer', 'repository_googledocs'), $options);
+ $mform->addHelpButton('issuerid', 'issuer', 'repository_googledocs');
+ $mform->addRule('issuerid', $strrequired, 'required', null, 'client');
$strrequired = get_string('required');
- $mform->addRule('clientid', $strrequired, 'required', null, 'client');
- $mform->addRule('secret', $strrequired, 'required', null, 'client');
- $mform->addElement('static', null, '', get_string('importformat', 'repository_googledocs', $a));
+ $mform->addElement('static', null, '', get_string('importformat', 'repository_googledocs'));
// Documents.
$docsformat = array();
diff --git a/repository/googledocs/tests/generator/lib.php b/repository/googledocs/tests/generator/lib.php
index 168c406a795..0fd3e7d3da8 100644
--- a/repository/googledocs/tests/generator/lib.php
+++ b/repository/googledocs/tests/generator/lib.php
@@ -23,6 +23,9 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
+use \core\oauth2\issuer;
+use \core\oauth2\endpoint;
+
/**
* Google Docs repository data generator class
*
@@ -41,11 +44,27 @@ class repository_googledocs_generator extends testing_repository_generator {
*/
protected function prepare_type_record(array $record) {
$record = parent::prepare_type_record($record);
- if (!isset($record['clientid'])) {
- $record['clientid'] = 'clientid';
- }
- if (!isset($record['secret'])) {
- $record['secret'] = 'secret';
+ $issuerrecord = (object) [
+ 'name' => 'Google',
+ 'image' => 'https://accounts.google.com/favicon.ico',
+ 'baseurl' => 'http://accounts.google.com/',
+ 'loginparamsoffline' => 'access_type=offline&prompt=consent',
+ 'showonloginpage' => true
+ ];
+
+ $issuer = new issuer(0, $issuerrecord);
+ $issuer->create();
+
+ $endpointrecord = (object) [
+ 'issuerid' => $issuer->get('id'),
+ 'name' => 'discovery_endpoint',
+ 'url' => 'https://accounts.google.com/.well-known/openid-configuration'
+ ];
+ $endpoint = new endpoint(0, $endpointrecord);
+ $endpoint->create();
+
+ if (!isset($record['issuerid'])) {
+ $record['issuerid'] = $issuer->get('id');
}
if (!isset($record['documentformat'])) {
$record['documentformat'] = 'pdf';
From d247a63dfa49661c00499be26b352009ef3d4ef0 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Sun, 5 Mar 2017 14:28:33 +0800
Subject: [PATCH 14/84] MDL-58128 oauth2: Add a scheduled task for refresh
We need to make sure our refresh tokens do not expire. We run a scheduled
task to update the refresh token once per hour.
Part of MDL-58220
---
lang/en/admin.php | 3 +
.../oauth2/refresh_system_tokens_task.php | 88 +++++++++++++++++++
lib/db/tasks.php | 9 ++
3 files changed, 100 insertions(+)
create mode 100644 lib/classes/oauth2/refresh_system_tokens_task.php
diff --git a/lang/en/admin.php b/lang/en/admin.php
index 3b5f902b6ec..9559b7003d1 100644
--- a/lang/en/admin.php
+++ b/lang/en/admin.php
@@ -795,6 +795,8 @@ $string['notifyloginthreshold'] = 'Threshold for email notifications';
$string['notloggedinroleid'] = 'Role for visitors';
$string['numberofmissingstrings'] = 'Number of missing strings: {$a}';
$string['numberofstrings'] = 'Total number of strings: {$a->strings} Missing: {$a->missing} ({$a->missingpercent} %)';
+$string['oauthrefreshtokenexpired'] = 'The refresh token for one of the OAuth services {$a->issuer} on your site {$a->siteurl} has expired. This will limit the functionality of any plugins that use this service. To fix this issue, visit the OAuth 2 Services configuration page and click on the "Connect system account" icon in the table row for this service. Be sure to login using the same service account for the OAuth system each time.';
+$string['oauthrefreshtokenexpiredshort'] = 'OAuth refresh token expired for {$a->issuer} on your site {$a->siteurl}.';
$string['onlynoreply'] = 'Only when from a no-reply address';
$string['opcacherecommended'] = 'PHP opcode caching improves performance and lowers memory requirements, OPcache extension is recommended and fully supported.';
$string['opensslrecommended'] = 'Installing the optional OpenSSL library is highly recommended -- it enables Moodle Networking functionality.';
@@ -1094,6 +1096,7 @@ $string['taskpasswordresetcleanup'] = 'Cleanup password reset attempts';
$string['taskplagiarismcron'] = 'Background processing for legacy cron in plagiarism plugins';
$string['taskportfoliocron'] = 'Background processing for portfolio plugins';
$string['taskquestioncron'] = 'Background processing for question engine';
+$string['taskrefreshoauthtokens'] = 'Refresh OAuth tokens for service accounts';
$string['taskregistrationcron'] = 'Site registration';
$string['tasksendfailedloginnotifications'] = 'Send failed login notifications';
$string['tasksendnewuserpasswords'] = 'Send new user passwords';
diff --git a/lib/classes/oauth2/refresh_system_tokens_task.php b/lib/classes/oauth2/refresh_system_tokens_task.php
new file mode 100644
index 00000000000..c6e3db8fc08
--- /dev/null
+++ b/lib/classes/oauth2/refresh_system_tokens_task.php
@@ -0,0 +1,88 @@
+.
+
+/**
+ * A scheduled task.
+ *
+ * @package core
+ * @copyright 2017 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+namespace core\oauth2;
+
+use \core\task\scheduled_task;
+
+/**
+ * Simple task to delete old messaging records.
+ */
+class refresh_system_tokens_task extends scheduled_task {
+
+ /**
+ * Get a descriptive name for this task (shown to admins).
+ *
+ * @return string
+ */
+ public function get_name() {
+ return get_string('taskrefreshsystemtokens', 'admin');
+ }
+
+ /**
+ * Notify admins when an OAuth refresh token expires. Should not happen if cron is running regularly.
+ * @param \core\oauth2\issuer $issuer
+ */
+ protected function notify_admins(\core\oauth2\issuer $issuer) {
+ $admins = get_admins();
+
+ if (empty($admins)) {
+ return;
+ }
+ foreach ($admins as $admin) {
+ $strparams = ['siteurl' => $CFG->wwwroot, 'issuer' => $issuer->get('name')];
+ $long = get_string('oauthrefreshtokenexpired', 'core_admin', $strparams);
+ $short = get_string('oauthrefreshtokenexpiredshort', 'core_admin', $strparams);
+ $message = new \core\message\message();
+ $message->courseid = SITEID;
+ $message->component = 'moodle';
+ $message->name = 'oauthrefreshtokenexpired';
+ $message->userfrom = core\user::get_noreply_user();
+ $message->userto = $admin;
+ $message->subject = $short;
+ $message->fullmessage = $long;
+ $message->fullmessageformat = FORMAT_PLAIN;
+ $message->fullmessagehtml = $long;
+ $message->smallmessage = $short;
+ $message->notification = 1;
+ message_send($message);
+ }
+ }
+
+
+ /**
+ * Do the job.
+ * Throw exceptions on errors (the job will be retried).
+ */
+ public function execute() {
+ $issuers = \core\oauth2\api::get_all_issuers();
+ foreach ($issuers as $issuer) {
+ if ($issuer->is_system_account_connected()) {
+ if (!\core\oauth2\api::get_system_oauth_client($issuer)) {
+ $this->notify_admins($issuer);
+ }
+ }
+ }
+ }
+
+}
diff --git a/lib/db/tasks.php b/lib/db/tasks.php
index c820348d6c2..4366f69fb45 100644
--- a/lib/db/tasks.php
+++ b/lib/db/tasks.php
@@ -347,4 +347,13 @@ $tasks = array(
'dayofweek' => '*',
'month' => '*'
),
+ array(
+ 'classname' => 'core\oauth2\refresh_system_tokens_task',
+ 'blocking' => 0,
+ 'minute' => 'R',
+ 'hour' => '*',
+ 'day' => '*',
+ 'dayofweek' => '*',
+ 'month' => '*'
+ ),
);
From 6c9cd495a2279b379173040dac1189f583797456 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Sun, 5 Mar 2017 16:13:53 +0800
Subject: [PATCH 15/84] MDL-58128 googledocs: Upgrade repo config
Part of MDL-58220
---
repository/googledocs/db/upgrade.php | 17 +++++++++++++++++
repository/googledocs/version.php | 2 +-
2 files changed, 18 insertions(+), 1 deletion(-)
diff --git a/repository/googledocs/db/upgrade.php b/repository/googledocs/db/upgrade.php
index da8d731a947..2a5698ef3c1 100644
--- a/repository/googledocs/db/upgrade.php
+++ b/repository/googledocs/db/upgrade.php
@@ -48,6 +48,23 @@ function xmldb_repository_googledocs_upgrade($oldversion) {
// Plugin savepoint reached.
upgrade_plugin_savepoint(true, 2017011100, 'repository', 'googledocs');
}
+ if ($oldversion < 2017030500) {
+ $clientid = get_config('clientid', 'googledocs');
+ $secret = get_config('secret', 'googledocs');
+
+ // Update from repo config to use an OAuth service.
+ if (!empty($clientid) && !empty($secret)) {
+ $issuer = \core\oauth2\api::create_standard_issuer('google');
+
+ $issuer->set('clientid', $clientid);
+ $issuer->set('secret', $secret);
+
+ $issuer->update();
+
+ set_config('issuerid', $issuer->get('id'), 'googledocs');
+ }
+ upgrade_plugin_savepoint(true, 2017030500, 'repository', 'googledocs');
+ }
return true;
}
diff --git a/repository/googledocs/version.php b/repository/googledocs/version.php
index 04eaa0e8fab..ce8f197427a 100644
--- a/repository/googledocs/version.php
+++ b/repository/googledocs/version.php
@@ -25,6 +25,6 @@
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2017011100; // The current plugin version (Date: YYYYMMDDXX).
+$plugin->version = 2017030500; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2016112900; // Requires this Moodle version.
$plugin->component = 'repository_googledocs'; // Full name of the plugin (used for diagnostics).
From 989e14fea094672b401f5dcf3d3071d70573ae32 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Fri, 3 Mar 2017 16:08:28 +0800
Subject: [PATCH 16/84] MDL-58128 googledocs: Support reference files.
Add options so the admin can control the types of files this repository can support (and the default).
Part of MDL-58220
---
lib/classes/oauth2/rest.php | 25 +-
lib/filelib.php | 28 ++
repository/filepicker.js | 8 +
repository/googledocs/classes/rest.php | 71 ++-
repository/googledocs/db/upgrade.php | 3 +
.../lang/en/repository_googledocs.php | 6 +
repository/googledocs/lib.php | 443 +++++++++++++++++-
repository/googledocs/version.php | 2 +-
repository/lib.php | 25 +
repository/repository_ajax.php | 5 +
10 files changed, 591 insertions(+), 25 deletions(-)
diff --git a/lib/classes/oauth2/rest.php b/lib/classes/oauth2/rest.php
index 03afc9fb4f4..708ad35ac5d 100644
--- a/lib/classes/oauth2/rest.php
+++ b/lib/classes/oauth2/rest.php
@@ -64,7 +64,7 @@ abstract class rest {
* @param string $functionname
* @param array $functionargs
*/
- public function call($functionname, $functionargs) {
+ public function call($functionname, $functionargs, $rawpost = false) {
$functions = $this->get_api_functions();
$supportedmethods = [ 'get', 'put', 'post', 'patch', 'head', 'delete' ];
if (empty($functions[$functionname])) {
@@ -86,7 +86,30 @@ abstract class rest {
}
}
+ // Allow params in the URL path like /me/{parent}/children.
+ foreach ($callargs as $argname => $value) {
+ $newendpoint = str_replace('{' . $argname . '}', $value, $endpoint);
+ if ($newendpoint != $endpoint) {
+ $endpoint = $newendpoint;
+ unset($callargs[$argname]);
+ }
+ }
+
+ if ($rawpost !== false) {
+ $queryparams = $this->curl->build_post_data($callargs);
+ if (!empty($queryparams)) {
+ $endpoint .= '?' . $queryparams;
+ }
+ $callargs = $rawpost;
+ }
+
+ error_log('CALL REST');
+ error_log($endpoint);
+ error_log(json_encode($callargs));
+ error_log($method);
+ $this->curl->setHeader('Content-type: application/json');
$response = $this->curl->$method($endpoint, $callargs);
+ error_log($response);
if ($this->curl->errno == 0) {
if ($responsetype == 'json') {
diff --git a/lib/filelib.php b/lib/filelib.php
index 57782bf6782..8d1d3cf818b 100644
--- a/lib/filelib.php
+++ b/lib/filelib.php
@@ -3458,6 +3458,34 @@ class curl {
return $this->request($url, $options);
}
+ /**
+ * HTTP PATCH method
+ *
+ * @param string $url
+ * @param array|string $params
+ * @param array $options
+ * @return bool
+ */
+ public function patch($url, $params = '', $options = array()) {
+ $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
+ if (is_array($params)) {
+ $this->_tmp_file_post_params = array();
+ foreach ($params as $key => $value) {
+ if ($value instanceof stored_file) {
+ $value->add_to_curl_request($this, $key);
+ } else {
+ $this->_tmp_file_post_params[$key] = $value;
+ }
+ }
+ $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
+ unset($this->_tmp_file_post_params);
+ } else {
+ // $params is the raw post data
+ $options['CURLOPT_POSTFIELDS'] = $params;
+ }
+ return $this->request($url, $options);
+ }
+
/**
* HTTP POST method
*
diff --git a/repository/filepicker.js b/repository/filepicker.js
index 386a6abcd17..3a2ff4edd89 100644
--- a/repository/filepicker.js
+++ b/repository/filepicker.js
@@ -29,6 +29,7 @@
* Active repository options
* =====
* this.active_repo.id
+ * this.active_repo.defaultreturntype
* this.active_repo.nosearch
* this.active_repo.norefresh
* this.active_repo.nologin
@@ -1094,6 +1095,12 @@ M.core_filepicker.init = function(Y, options) {
firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
filelinkcount += allowed ? 1 : 0;
}
+ var defaultreturntype = this.options.repositories[this.active_repo.id].defaultreturntype;
+ if (defaultreturntype) {
+ if (filelink[defaultreturntype]) {
+ firstfilelink = defaultreturntype;
+ }
+ }
// make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
// check the first available file-link-type option
for (var linktype in filelink) {
@@ -1415,6 +1422,7 @@ M.core_filepicker.init = function(Y, options) {
this.objecttag = data.object?data.object:null;
this.active_repo = {};
this.active_repo.issearchresult = data.issearchresult ? true : false;
+ this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null;
this.active_repo.dynload = data.dynload?data.dynload:false;
this.active_repo.pages = Number(data.pages?data.pages:null);
this.active_repo.page = Number(data.page?data.page:null);
diff --git a/repository/googledocs/classes/rest.php b/repository/googledocs/classes/rest.php
index f66aa8bd884..38028ba3434 100644
--- a/repository/googledocs/classes/rest.php
+++ b/repository/googledocs/classes/rest.php
@@ -54,7 +54,76 @@ class rest extends \core\oauth2\rest {
'spaces' => PARAM_RAW
],
'response' => 'json'
- ]
+ ],
+ 'get' => [
+ 'endpoint' => 'https://www.googleapis.com/drive/v3/files/{fileid}',
+ 'method' => 'get',
+ 'args' => [
+ 'fields' => PARAM_RAW,
+ 'fileid' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ 'copy' => [
+ 'endpoint' => 'https://www.googleapis.com/drive/v3/files/{fileid}/copy',
+ 'method' => 'post',
+ 'args' => [
+ 'fields' => PARAM_RAW,
+ 'fileid' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ 'create' => [
+ 'endpoint' => 'https://www.googleapis.com/drive/v3/files',
+ 'method' => 'post',
+ 'args' => [
+ 'fields' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ 'update' => [
+ 'endpoint' => 'https://www.googleapis.com/drive/v3/files/{fileid}',
+ 'method' => 'patch',
+ 'args' => [
+ 'fileid' => PARAM_RAW,
+ 'fields' => PARAM_RAW,
+ 'addParents' => PARAM_RAW,
+ 'removeParents' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ 'create_permission' => [
+ 'endpoint' => 'https://www.googleapis.com/drive/v3/files/{fileid}/permissions',
+ 'method' => 'post',
+ 'args' => [
+ 'fileid' => PARAM_RAW,
+ 'emailMessage' => PARAM_RAW,
+ 'sendNotificationEmail' => PARAM_RAW,
+ 'transferOwnership' => PARAM_RAW,
+ ],
+ 'response' => 'json'
+ ],
+ 'update_permission' => [
+ 'endpoint' => 'https://www.googleapis.com/drive/v3/files/{fileid}/permissions/{permissionid}',
+ 'method' => 'patch',
+ 'args' => [
+ 'fileid' => PARAM_RAW,
+ 'permissionid' => PARAM_RAW,
+ 'emailMessage' => PARAM_RAW,
+ 'sendNotificationEmail' => PARAM_RAW,
+ 'transferOwnership' => PARAM_RAW,
+ ],
+ 'response' => 'json'
+ ],
+ 'list_permissions' => [
+ 'endpoint' => 'https://www.googleapis.com/drive/v3/files/{fileid}/permissions',
+ 'method' => 'get',
+ 'args' => [
+ 'fileid' => PARAM_RAW,
+ 'fields' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
];
}
}
diff --git a/repository/googledocs/db/upgrade.php b/repository/googledocs/db/upgrade.php
index 2a5698ef3c1..9d4643230a1 100644
--- a/repository/googledocs/db/upgrade.php
+++ b/repository/googledocs/db/upgrade.php
@@ -63,6 +63,9 @@ function xmldb_repository_googledocs_upgrade($oldversion) {
set_config('issuerid', $issuer->get('id'), 'googledocs');
}
+ if ($oldversion < 2017030600) {
+ set_config('supportedfiles', 'both', 'googledocs');
+ }
upgrade_plugin_savepoint(true, 2017030500, 'repository', 'googledocs');
}
diff --git a/repository/googledocs/lang/en/repository_googledocs.php b/repository/googledocs/lang/en/repository_googledocs.php
index 5654925eb09..e64dabcb73e 100644
--- a/repository/googledocs/lang/en/repository_googledocs.php
+++ b/repository/googledocs/lang/en/repository_googledocs.php
@@ -35,6 +35,12 @@ $string['issuer_help'] = 'Select the OAuth 2 service that is configured to talk
$string['servicenotenabled'] = 'Access not configured. Make sure the service \'Drive API\' is enabled.';
$string['oauth2serviceslink'] = 'OAuth 2 Services Configuration';
$string['searchfor'] = 'Search for {$a}';
+$string['internal'] = 'Internal (files stored in Moodle)';
+$string['external'] = 'External (only links stored in Moodle)';
+$string['both'] = 'Internal and External';
+$string['supportedreturntypes'] = 'Supported files';
+$string['defaultreturntype'] = 'Default return type';
+$string['fileoptions'] = 'The types and defaults for returned files is configurable here. Note that all files linked externally will be updated so that the owner is the Moodle system account.';
// Deprecated since Moodle 3.3.
$string['oauthinfo'] = '
To use this plugin, you must register your site with Google, as described in the documentation Google OAuth 2.0 setup.
As part of the registration process, you will need to enter the following URL as \'Authorized Redirect URIs\':
{$a->callbackurl}
Once registered, you will be provided with a client ID and secret which can be used to configure all Google Drive and Picasa plugins.
Please also note that you will have to enable the service \'Drive API\'.
';
diff --git a/repository/googledocs/lib.php b/repository/googledocs/lib.php
index 852ee5d1bae..bfffc736f92 100644
--- a/repository/googledocs/lib.php
+++ b/repository/googledocs/lib.php
@@ -185,7 +185,6 @@ class repository_googledocs extends repository {
);
}
-
/**
* List the files and folders.
*
@@ -217,6 +216,7 @@ class repository_googledocs extends repository {
$ret = array();
$ret['dynload'] = true;
+ $ret['defaultreturntype'] = $this->default_returntype();
$ret['path'] = $this->build_breadcrumb($path);
$ret['list'] = $results;
return $ret;
@@ -266,7 +266,7 @@ class repository_googledocs extends repository {
$files = array();
$folders = array();
$config = get_config('googledocs');
- $fields = "files(id,name,mimeType,webContentLink,fileExtension,modifiedTime,size,thumbnailLink,iconLink)";
+ $fields = "files(id,name,mimeType,webContentLink,webViewLink,fileExtension,modifiedTime,size,thumbnailLink,iconLink)";
$params = array('q' => $q, 'fields' => $fields, 'spaces' => 'drive');
try {
@@ -284,7 +284,6 @@ class repository_googledocs extends repository {
}
}
- $base = 'https://www.googleapis.com/drive/v3';
$gfiles = isset($response->files) ? $response->files : array();
foreach ($gfiles as $gfile) {
if ($gfile->mimeType == 'application/vnd.google-apps.folder') {
@@ -300,12 +299,11 @@ class repository_googledocs extends repository {
);
} else {
// This is a file.
+ $link = isset($gfile->webContentLink) ? $gfile->webContentLink : '';
if (isset($gfile->fileExtension)) {
// The file has an extension, therefore we can download it.
+ $source = json_encode(['id' => $gfile->id, 'exportformat' => 'download', 'link' => $link]);
$title = $gfile->name;
- $params = ['alt' => 'media'];
- $sourceurl = new moodle_url($base . '/files/' . $gfile->id, $params);
- $source = $sourceurl->out(false);
} else {
// The file is probably a Google Doc file, we get the corresponding export link.
// This should be improved by allowing the user to select the type of export they'd like.
@@ -317,7 +315,7 @@ class repository_googledocs extends repository {
switch ($type){
case 'document':
$ext = $config->documentformat;
- $title = $item['title'] . '.'. $ext;
+ $title = $gfile->name . '.'. $ext;
if ($ext === 'rtf') {
// Moodle user 'text/rtf' as the MIME type for RTF files.
// Google uses 'application/rtf' for the same type of file.
@@ -329,17 +327,17 @@ class repository_googledocs extends repository {
break;
case 'presentation':
$ext = $config->presentationformat;
- $title = $item['title'] . '.'. $ext;
+ $title = $gfile->name . '.'. $ext;
$exporttype = $types[$ext]['type'];
break;
case 'spreadsheet':
$ext = $config->spreadsheetformat;
- $title = $item['title'] . '.'. $ext;
+ $title = $gfile->name . '.'. $ext;
$exporttype = $types[$ext]['type'];
break;
case 'drawing':
$ext = $config->drawingformat;
- $title = $item['title'] . '.'. $ext;
+ $title = $gfile->name . '.'. $ext;
$exporttype = $types[$ext]['type'];
break;
}
@@ -347,9 +345,7 @@ class repository_googledocs extends repository {
if (empty($title)) {
continue;
}
- $params = ['mimeType' => $exporttype];
- $sourceurl = new moodle_url($base . '/files/' . $gfile->id . '/export', $params);
- $source = $sourceurl->out(false);
+ $source = json_encode(['id' => $gfile->id, 'exportformat' => $exporttype, 'link' => $link]);
}
// Adds the file to the file list. Using the itemId along with the name as key
// of the array because Google Drive allows files with identical names.
@@ -400,10 +396,24 @@ class repository_googledocs extends repository {
global $CFG;
$client = $this->get_user_oauth_client();
+ $base = 'https://www.googleapis.com/drive/v3';
+ $source = json_decode($reference);
+
+ if ($source->exportformat == 'download') {
+ $params = ['alt' => 'media'];
+ $sourceurl = new moodle_url($base . '/files/' . $source->id, $params);
+ $source = $sourceurl->out(false);
+ } else {
+ $params = ['mimeType' => $source->exportformat];
+ $sourceurl = new moodle_url($base . '/files/' . $source->id . '/export', $params);
+ $source = $sourceurl->out(false);
+ }
+
+ // We use download_one and not the rest API because it has special timeouts etc.
$path = $this->prepare_file($filename);
$options = ['filepath' => $path, 'timeout' => 15, 'followlocation' => true, 'maxredirs' => 5];
- $result = $client->download_one($reference, null, $options);
+ $result = $client->download_one($source, null, $options);
if ($result) {
@chmod($path, $CFG->filepermissions);
@@ -425,7 +435,8 @@ class repository_googledocs extends repository {
* @return string file reference.
*/
public function get_file_reference($source) {
- return clean_param($source, PARAM_URL);
+ // We could do some magic upgrade code here.
+ return $source;
}
/**
@@ -446,7 +457,34 @@ class repository_googledocs extends repository {
* @return int
*/
public function supported_returntypes() {
- return FILE_INTERNAL;
+ // We can only support references if the system account is connected.
+ if (!empty($this->issuer) && $this->issuer->is_system_account_connected()) {
+ $setting = get_config('googledocs', 'supportedreturntypes');
+ if ($setting == 'internal') {
+ return FILE_INTERNAL;
+ } else if ($setting == 'external') {
+ return FILE_REFERENCE;
+ } else {
+ return FILE_REFERENCE | FILE_INTERNAL;
+ }
+ } else {
+ return FILE_INTERNAL;
+ }
+ }
+
+ /**
+ * Which return type should be selected by default.
+ *
+ * @return int
+ */
+ public function default_returntype() {
+ $setting = get_config('googledocs', 'defaultreturntype');
+ $supported = get_config('googledocs', 'supportedreturntypes');
+ if (($setting == FILE_INTERNAL && $supported != 'external') || $supported == 'internal') {
+ return FILE_INTERNAL;
+ } else {
+ return FILE_REFERENCE;
+ }
}
/**
@@ -458,7 +496,8 @@ class repository_googledocs extends repository {
public static function get_type_option_names() {
return array('issuerid', 'pluginname',
'documentformat', 'drawingformat',
- 'presentationformat', 'spreadsheetformat');
+ 'presentationformat', 'spreadsheetformat',
+ 'defaultreturntype', 'supportedreturntypes');
}
/**
@@ -466,10 +505,348 @@ class repository_googledocs extends repository {
*/
public function callback() {
$client = $this->get_user_oauth_client();
- // This will upgrade to an access token if we have an authorization code.
+ // This will upgrade to an access token if we have an authorization code and save the access token in the session.
$client->is_logged_in();
}
+ /**
+ * Repository method to serve the referenced file
+ *
+ * @see send_stored_file
+ *
+ * @param stored_file $storedfile the file that contains the reference
+ * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
+ * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
+ * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
+ * @param array $options additional options affecting the file serving
+ */
+ public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
+ // TODO.
+ $source = json_decode($storedfile->get_reference());
+
+ if ($source->link) {
+ header('Location: ' . $source->link);
+ } else {
+ $details = 'File is missing source link';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ }
+
+ /**
+ * List the permissions on a file.
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $fileid The id of the file.
+ *
+ * @return array
+ */
+ protected function list_file_permissions(\repository_googledocs\rest $client, $fileid) {
+ $fields = "permissions(id,type,emailAddress,role,allowFileDiscovery,displayName)";
+ return $client->call('list_permissions', ['fileid' => $fileid]);
+ }
+
+ /**
+ * See if a folder exists within a folder
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $foldername The folder we are looking for.
+ * @param string $parentid The parent folder we are looking in.
+ *
+ * @return string|boolean The file id if it exists or false.
+ */
+ protected function folder_exists_in_folder(\repository_googledocs\rest $client, $foldername, $parentid) {
+ $q = '\'' . addslashes($parentid) . '\' in parents and trashed = false and name = \'' . addslashes($foldername). '\'';
+ $fields = 'files(id, name)';
+ $params = [ 'q' => $q, 'fields' => $fields];
+ $response = $client->call('list', $params);
+ $missing = true;
+ foreach ($response->files as $child) {
+ if ($child->name == $foldername) {
+ return $child->id;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Create a folder within a folder
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $foldername The folder we are creating.
+ * @param string $parentid The parent folder we are creating in.
+ *
+ * @return string The file id of the new folder.
+ */
+ protected function create_folder_in_folder(\repository_googledocs\rest $client, $foldername, $parentid) {
+ $fields = 'id';
+ $params = ['fields' => $fields];
+ $folder = ['mimeType' => 'application/vnd.google-apps.folder', 'name' => $foldername, 'parents' => [$parentid]];
+ $created = $client->call('create', $params, json_encode($folder));
+ if (empty($created->id)) {
+ $details = 'Cannot create folder:' . $foldername;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return $created->id;
+ }
+
+ /**
+ * Get capabilities for a file.
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $fileid The file we are checking.
+ *
+ * @return stdClass The file info with capabilities.
+ */
+ protected function get_file_capabilities(\repository_googledocs\rest $client, $fileid) {
+ $fields = "id,capabilities,writersCanShare";
+ $params = [
+ 'fileid' => $fileid,
+ 'fields' => $fields
+ ];
+ return $client->call('get', $params);
+ }
+
+ /**
+ * Update file owner.
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $fileid The file we are updating.
+ *
+ * @return boolean Did it work?
+ */
+ protected function update_file_owner(\repository_googledocs\rest $client, $fileid, $owneremail) {
+ $updateowner = [
+ 'emailAddress' => $owneremail,
+ 'role' => 'owner',
+ 'type' => 'user'
+ ];
+ $params = ['fileid' => $fileid, 'transferOwnership' => 'true'];
+ try {
+ $response = $client->call('create_permission', $params, json_encode($updateowner));
+ } catch (\core\oauth2\rest_exception $re) {
+ return false;
+ }
+ return !empty($response->id);
+ }
+
+ /**
+ * Copy a file and return the new file details. A side effect of the copy
+ * is that the owner will be the account authenticated with this oauth client.
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $fileid The file we are copying.
+ *
+ * @return stdClass file details.
+ */
+ protected function copy_file(\repository_googledocs\rest $client, $fileid) {
+ $fields = "id,name,mimeType,webContentLink,webViewLink,size,thumbnailLink,iconLink";
+ $params = [
+ 'fileid' => $fileid,
+ 'fields' => $fields
+ ];
+ $fileinfo = $client->call('copy', $params, ' ');
+ if (empty($fileinfo->id)) {
+ $details = 'Cannot copy file:' . $fileid;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return $fileinfo;
+ }
+
+ /**
+ * Add a writer to the permissions on the file.
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $fileid The file we are updating.
+ * @param string $email The email of the writer account to add.
+ * @return boolean
+ */
+ protected function add_writer_to_file($client, $fileid, $email) {
+ $updateeditor = [
+ 'emailAddress' => $email,
+ 'role' => 'writer',
+ 'type' => 'user'
+ ];
+ $params = ['fileid' => $fileid];
+ $response = $client->call('create_permission', $params, json_encode($updateeditor));
+ if (empty($response->id)) {
+ $details = 'Cannot add user ' . $email . ' as a writer for document: ' . $fileid;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return true;
+ }
+
+ /**
+ * Move from root to folder
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $fileid The file we are updating.
+ * @param string $folderid The id of the folder we are moving to
+ * @return boolean
+ */
+ protected function move_file_from_root_to_folder($client, $fileid, $folderid) {
+ // Set the parent.
+ $params = [
+ 'fileid' => $fileid, 'addParents' => $folderid, 'removeParents' => 'root'
+ ];
+ $response = $client->call('update', $params, ' ');
+ if (empty($response->id)) {
+ $details = 'Cannot move the file to a folder: ' . $fileid;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return true;
+ }
+
+ /**
+ * Prevent writers from sharing.
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $fileid The file we are updating.
+ * @return boolean
+ */
+ protected function prevent_writers_from_sharing_file($client, $fileid) {
+ // We don't want anyone but Moodle to change the sharing settings.
+ $params = [
+ 'fileid' => $fileid
+ ];
+ $update = [
+ 'writersCanShare' => false
+ ];
+ $response = $client->call('update', $params, json_encode($update));
+ if (empty($response->id)) {
+ $details = 'Cannot prevent writers from sharing document: ' . $fileid;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return true;
+ }
+
+ /**
+ * Allow anyone with the link to read the file.
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $fileid The file we are updating.
+ * @return boolean
+ */
+ protected function set_file_sharing_anyone_with_link_can_read($client, $fileid) {
+ $updateread = [
+ 'type' => 'anyone',
+ 'role' => 'reader',
+ 'allowFileDiscovery' => 'false'
+ ];
+ $params = ['fileid' => $fileid];
+ $response = $client->call('create_permission', $params, json_encode($updateread));
+ if (empty($response->id) || $response->id != 'anyoneWithLink') {
+ $details = 'Cannot update link sharing for the document: ' . $fileid;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return true;
+ }
+
+ /**
+ * Called when a file is selected as a "link".
+ * Invoked at MOODLE/repository/repository_ajax.php
+ *
+ * @param string $reference this reference is generated by
+ * repository::get_file_reference()
+ * @param context $context the target context for this new file.
+ * @return string $modifiedreference (final one before saving to DB)
+ */
+ public function reference_file_selected($reference, $context) {
+ // What we need to do here is transfer ownership to the system user (or copy)
+ // then set the permissions so anyone with the share link can view,
+ // finally update the reference to contain the share link if it was not
+ // already there (and point to new file id if we copied).
+ $systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
+
+ if ($systemauth === false) {
+ $details = 'Cannot connect as system user';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ $systemuserinfo = $systemauth->get_userinfo();
+ $systemuseremail = $systemuserinfo['email'];
+
+ $source = json_decode($reference);
+
+ $userauth = $this->get_user_oauth_client();
+ if ($userauth === false) {
+ $details = 'Cannot connect as current user';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ $userinfo = $userauth->get_userinfo();
+ $useremail = $userinfo['email'];
+
+ $userservice = new repository_googledocs\rest($userauth);
+ $systemservice = new repository_googledocs\rest($systemauth);
+
+ // Get the list of existing permissions so we can see if the owner is already the system account,
+ // and whether we need to update the link sharing options.
+ $permissions = $this->list_file_permissions($userservice, $source->id);
+
+ $readshareupdaterequired = true;
+ $ownerupdaterequired = true;
+ foreach ($permissions->permissions as $permission) {
+ if ($permission->type == 'user' &&
+ $permission->role == 'owner' &&
+ isset($permission->emailAddress) &&
+ $permission->emailAddress == $systemuseremail) {
+ $ownerupdaterequired = false;
+ }
+ if ($permission->id == 'anyoneWithLink' &&
+ $permission->type == 'anyone' &&
+ $permission->role == 'reader' &&
+ $permission->allowFileDiscovery == false) {
+ $readshareupdaterequired = false;
+ }
+ }
+
+ // Now move it to a sensible folder.
+ $contextlist = array_reverse($context->get_parent_contexts(true));
+
+ $parentid = 'root';
+ foreach ($contextlist as $context) {
+ // Make sure a folder exists here.
+ $folderid = $this->folder_exists_in_folder($systemservice, $foldername, $parentid);
+ if ($folderid !== false) {
+ $parentid = $folderid;
+ } else {
+ // Create it.
+ $parentid = $this->create_folder_in_folder($systemservice, $foldername, $parentid);
+ }
+ }
+
+ // See if we have edit capability before the copy.
+ $fileinfo = $this->get_file_capabilities($userservice, $source->id);
+ $canedit = !empty($fileinfo->capabilities->canEdit);
+ $writerscanshare = !empty($fileinfo->writersCanShare);
+
+ // The owner was not the system user so we have to update the file.
+ if ($ownerupdaterequired) {
+
+ $worked = $this->update_file_owner($userservice, $source->id, $systemuseremail);
+ if (!$worked) {
+ // Updating the owner only works for "google files" like documents etc. For binary
+ // files we will get here.
+ $source = $this->copy_file($systemservice, $source->id);
+
+ $readshareupdaterequired = true;
+ $writerscanshare = true;
+
+ if ($canedit) {
+ $this->add_writer_to_file($systemservice, $source->id, $useremail);
+ }
+ }
+
+ $this->move_file_from_root_to_folder($systemservice, $source->id, $parentid);
+ }
+
+ if ($writerscanshare) {
+ // We don't want anyone but Moodle to change the sharing settings.
+ $this->prevent_writers_from_sharing_file($systemservice, $source->id);
+ }
+
+ if ($readshareupdaterequired) {
+ $this->set_file_sharing_anyone_with_link_can_read($systemservice, $source->id);
+ }
+ }
+
/**
* Edit/Create Admin Settings Moodle form.
*
@@ -477,7 +854,8 @@ class repository_googledocs extends repository {
* @param string $classname repository class name.
*/
public static function type_config_form($mform, $classname = 'repository') {
- $url = (string)new moodle_url('/admin/tool/oauth2/issuers.php');
+ $url = new moodle_url('/admin/tool/oauth2/issuers.php');
+ $url = $url->out();
$mform->addElement('static', null, '', get_string('oauth2serviceslink', 'repository_googledocs', $url));
@@ -488,11 +866,26 @@ class repository_googledocs extends repository {
foreach ($issuers as $issuer) {
$options[$issuer->get('id')] = s($issuer->get('name'));
}
+
+ $strrequired = get_string('required');
+
$mform->addElement('select', 'issuerid', get_string('issuer', 'repository_googledocs'), $options);
$mform->addHelpButton('issuerid', 'issuer', 'repository_googledocs');
$mform->addRule('issuerid', $strrequired, 'required', null, 'client');
- $strrequired = get_string('required');
+ $mform->addElement('static', null, '', get_string('fileoptions', 'repository_googledocs'));
+ $choices = [
+ 'internal' => get_string('internal', 'repository_googledocs'),
+ 'external' => get_string('external', 'repository_googledocs'),
+ 'both' => get_string('both', 'repository_googledocs')
+ ];
+ $mform->addElement('select', 'supportedreturntypes', get_string('supportedreturntypes', 'repository_googledocs'), $choices);
+
+ $choices = [
+ FILE_INTERNAL => get_string('internal', 'repository_googledocs'),
+ FILE_REFERENCE => get_string('external', 'repository_googledocs'),
+ ];
+ $mform->addElement('select', 'defaultreturntype', get_string('defaultreturntype', 'repository_googledocs'), $choices);
$mform->addElement('static', null, '', get_string('importformat', 'repository_googledocs'));
@@ -529,7 +922,8 @@ class repository_googledocs extends repository {
$presentationformat['txt'] = 'txt';
core_collator::ksort($presentationformat, core_collator::SORT_NATURAL);
- $mform->addElement('select', 'presentationformat', get_string('presentationformat', 'repository_googledocs'), $presentationformat);
+ $str = get_string('presentationformat', 'repository_googledocs');
+ $mform->addElement('select', 'presentationformat', $str, $presentationformat);
$mform->setDefault('presentationformat', $presentationformat['pptx']);
$mform->setType('presentationformat', PARAM_ALPHANUM);
@@ -541,9 +935,14 @@ class repository_googledocs extends repository {
$spreadsheetformat['xlsx'] = 'xlsx';
core_collator::ksort($spreadsheetformat, core_collator::SORT_NATURAL);
- $mform->addElement('select', 'spreadsheetformat', get_string('spreadsheetformat', 'repository_googledocs'), $spreadsheetformat);
+ $str = get_string('spreadsheetformat', 'repository_googledocs');
+ $mform->addElement('select', 'spreadsheetformat', $str, $spreadsheetformat);
$mform->setDefault('spreadsheetformat', $spreadsheetformat['xlsx']);
$mform->setType('spreadsheetformat', PARAM_ALPHANUM);
}
}
+
// Icon from: http://www.iconspedia.com/icon/google-2706.html.
+function repository_googledocs_oauth2_system_scopes() {
+ return 'https://www.googleapis.com/auth/drive';
+}
diff --git a/repository/googledocs/version.php b/repository/googledocs/version.php
index ce8f197427a..4aa78df7655 100644
--- a/repository/googledocs/version.php
+++ b/repository/googledocs/version.php
@@ -25,6 +25,6 @@
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2017030500; // The current plugin version (Date: YYYYMMDDXX).
+$plugin->version = 2017030600; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2016112900; // Requires this Moodle version.
$plugin->component = 'repository_googledocs'; // Full name of the plugin (used for diagnostics).
diff --git a/repository/lib.php b/repository/lib.php
index c11f4cdc61f..6ed4db745bd 100644
--- a/repository/lib.php
+++ b/repository/lib.php
@@ -1281,6 +1281,19 @@ abstract class repository implements cacheable_object {
public function cache_file_by_reference($reference, $storedfile) {
}
+ /**
+ * reference_file_selected
+ * Invoked at MOODLE/repository/repository_ajax.php
+ *
+ * @param string $reference this reference is generated by
+ * repository::get_file_reference()
+ * @param context $context the target context for this new file.
+ * @return string updated reference (final one before it's saved to db).
+ */
+ public function reference_file_selected($reference, $context) {
+ return $reference;
+ }
+
/**
* Return the source information
*
@@ -1890,6 +1903,17 @@ abstract class repository implements cacheable_object {
return (FILE_INTERNAL | FILE_EXTERNAL);
}
+ /**
+ * Tells how the file can be picked from this repository
+ *
+ * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
+ *
+ * @return int
+ */
+ public function default_returntype() {
+ return FILE_INTERNAL;
+ }
+
/**
* Provide repository instance information for Ajax
*
@@ -1904,6 +1928,7 @@ abstract class repository implements cacheable_object {
$meta->icon = $OUTPUT->image_url('icon', 'repository_'.$meta->type)->out(false);
$meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
$meta->return_types = $this->supported_returntypes();
+ $meta->defaultreturntype = $this->default_returntype();
$meta->sortorder = $this->options['sortorder'];
return $meta;
}
diff --git a/repository/repository_ajax.php b/repository/repository_ajax.php
index 631d4d1a0d0..ba703765f1b 100644
--- a/repository/repository_ajax.php
+++ b/repository/repository_ajax.php
@@ -226,6 +226,11 @@ switch ($action) {
$record->contenthash = $sourcefile->get_contenthash();
$record->filesize = $sourcefile->get_filesize();
}
+
+ // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
+ // to the file store. E.g. transfer ownership of the file to a system account etc.
+ $reference = $repo->reference_file_selected($reference, $context);
+
// Check if file exists.
if (repository::draftfile_exists($itemid, $saveas_path, $saveas_filename)) {
// File name being used, rename it.
From 8ece1d70d89f5c38a233ce0aec3595f282ad27b7 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Mon, 6 Mar 2017 14:16:51 +0800
Subject: [PATCH 17/84] MDL-58128 googledocs: Don't copy files
When linking - add the moodle account to the file and
organise it on the moodle side. Also allow read access with link,
but don't make any other changes to the perm/ownership.
Part of MDL-58220
---
lang/en/repository.php | 1 +
.../lang/en/repository_googledocs.php | 1 +
repository/googledocs/lib.php | 99 ++++++++++++-------
3 files changed, 63 insertions(+), 38 deletions(-)
diff --git a/lang/en/repository.php b/lang/en/repository.php
index d76784a5b7b..16f77ddf476 100644
--- a/lang/en/repository.php
+++ b/lang/en/repository.php
@@ -232,6 +232,7 @@ $string['unknownoriginal'] = 'Unknown';
$string['upload'] = 'Upload this file';
$string['uploading'] = 'Uploading...';
$string['uploadsucc'] = 'The file has been uploaded successfully';
+$string['unknownsource'] = 'Unknown source';
$string['undisclosedsource'] = '(Undisclosed)';
$string['undisclosedreference'] = '(Undisclosed)';
$string['uselatestfile'] = 'Use latest file';
diff --git a/repository/googledocs/lang/en/repository_googledocs.php b/repository/googledocs/lang/en/repository_googledocs.php
index e64dabcb73e..cd4c4af3a59 100644
--- a/repository/googledocs/lang/en/repository_googledocs.php
+++ b/repository/googledocs/lang/en/repository_googledocs.php
@@ -41,6 +41,7 @@ $string['both'] = 'Internal and External';
$string['supportedreturntypes'] = 'Supported files';
$string['defaultreturntype'] = 'Default return type';
$string['fileoptions'] = 'The types and defaults for returned files is configurable here. Note that all files linked externally will be updated so that the owner is the Moodle system account.';
+$string['owner'] = 'Owned by: {$a}';
// Deprecated since Moodle 3.3.
$string['oauthinfo'] = '
To use this plugin, you must register your site with Google, as described in the documentation Google OAuth 2.0 setup.
As part of the registration process, you will need to enter the following URL as \'Authorized Redirect URIs\':
{$a->callbackurl}
Once registered, you will be provided with a client ID and secret which can be used to configure all Google Drive and Picasa plugins.
Please also note that you will have to enable the service \'Drive API\'.
';
diff --git a/repository/googledocs/lib.php b/repository/googledocs/lib.php
index bfffc736f92..14fdef85a9b 100644
--- a/repository/googledocs/lib.php
+++ b/repository/googledocs/lib.php
@@ -299,7 +299,10 @@ class repository_googledocs extends repository {
);
} else {
// This is a file.
- $link = isset($gfile->webContentLink) ? $gfile->webContentLink : '';
+ $link = isset($gfile->webViewLink) ? $gfile->webViewLink : '';
+ if (empty($link)) {
+ $link = isset($gfile->webContentLink) ? $gfile->webContentLink : '';
+ }
if (isset($gfile->fileExtension)) {
// The file has an extension, therefore we can download it.
$source = json_encode(['id' => $gfile->id, 'exportformat' => 'download', 'link' => $link]);
@@ -521,7 +524,6 @@ class repository_googledocs extends repository {
* @param array $options additional options affecting the file serving
*/
public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
- // TODO.
$source = json_decode($storedfile->get_reference());
if ($source->link) {
@@ -605,6 +607,23 @@ class repository_googledocs extends repository {
return $client->call('get', $params);
}
+ /**
+ * Get simple file info for humans.
+ *
+ * @param \core\oauth2\client $client Authenticated client.
+ * @param string $fileid The file we are querying.
+ *
+ * @return stdClass
+ */
+ protected function get_file_summary(\repository_googledocs\rest $client, $fileid) {
+ $fields = "id,name,owners";
+ $params = [
+ 'fileid' => $fileid,
+ 'fields' => $fields
+ ];
+ return $client->call('get', $params);
+ }
+
/**
* Update file owner.
*
@@ -665,7 +684,7 @@ class repository_googledocs extends repository {
'role' => 'writer',
'type' => 'user'
];
- $params = ['fileid' => $fileid];
+ $params = ['fileid' => $fileid, 'sendNotificationEmail' => 'false'];
$response = $client->call('create_permission', $params, json_encode($updateeditor));
if (empty($response->id)) {
$details = 'Cannot add user ' . $email . ' as a writer for document: ' . $fileid;
@@ -783,12 +802,6 @@ class repository_googledocs extends repository {
$readshareupdaterequired = true;
$ownerupdaterequired = true;
foreach ($permissions->permissions as $permission) {
- if ($permission->type == 'user' &&
- $permission->role == 'owner' &&
- isset($permission->emailAddress) &&
- $permission->emailAddress == $systemuseremail) {
- $ownerupdaterequired = false;
- }
if ($permission->id == 'anyoneWithLink' &&
$permission->type == 'anyone' &&
$permission->role == 'reader' &&
@@ -797,12 +810,17 @@ class repository_googledocs extends repository {
}
}
+ // Add Moodle as writer.
+ $this->add_writer_to_file($userservice, $source->id, $systemuseremail);
+
// Now move it to a sensible folder.
$contextlist = array_reverse($context->get_parent_contexts(true));
$parentid = 'root';
foreach ($contextlist as $context) {
// Make sure a folder exists here.
+ $foldername = $context->get_context_name();
+
$folderid = $this->folder_exists_in_folder($systemservice, $foldername, $parentid);
if ($folderid !== false) {
$parentid = $folderid;
@@ -812,39 +830,44 @@ class repository_googledocs extends repository {
}
}
- // See if we have edit capability before the copy.
- $fileinfo = $this->get_file_capabilities($userservice, $source->id);
- $canedit = !empty($fileinfo->capabilities->canEdit);
- $writerscanshare = !empty($fileinfo->writersCanShare);
-
- // The owner was not the system user so we have to update the file.
- if ($ownerupdaterequired) {
-
- $worked = $this->update_file_owner($userservice, $source->id, $systemuseremail);
- if (!$worked) {
- // Updating the owner only works for "google files" like documents etc. For binary
- // files we will get here.
- $source = $this->copy_file($systemservice, $source->id);
-
- $readshareupdaterequired = true;
- $writerscanshare = true;
-
- if ($canedit) {
- $this->add_writer_to_file($systemservice, $source->id, $useremail);
- }
- }
-
- $this->move_file_from_root_to_folder($systemservice, $source->id, $parentid);
- }
-
- if ($writerscanshare) {
- // We don't want anyone but Moodle to change the sharing settings.
- $this->prevent_writers_from_sharing_file($systemservice, $source->id);
- }
+ $this->move_file_from_root_to_folder($systemservice, $source->id, $parentid);
if ($readshareupdaterequired) {
$this->set_file_sharing_anyone_with_link_can_read($systemservice, $source->id);
}
+
+ // We did not update the reference at all.
+ return $reference;
+ }
+
+ /**
+ * Get human readable file info from a the reference.
+ *
+ * @param string $reference
+ * @param int $filestatus
+ */
+ public function get_reference_details($reference, $filestatus = 0) {
+ if (empty($reference)) {
+ return get_string('unknownsource', 'repository');
+ }
+ $source = json_decode($reference);
+ $systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
+
+ if ($systemauth === false) {
+ return '';
+ }
+ $systemservice = new repository_googledocs\rest($systemauth);
+ $info = $this->get_file_summary($systemservice, $source->id);
+
+ $owner = '';
+ if (!empty($info->owners[0]->displayName)) {
+ $owner = $info->owners[0]->displayName;
+ }
+ if ($owner) {
+ return get_string('owner', 'repository_googledocs', $owner);
+ } else {
+ return $info->name;
+ }
}
/**
From 151b0f940966559ba00e124f89ab7c153901f3df Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 7 Mar 2017 22:04:30 +0800
Subject: [PATCH 18/84] MDL-58132 repositories: Controlled link file type
This introduces a new "controlled link" file type where the file is not
stored in Moodle - but Moodle will control the access permissions on the file.
Plugins can "freeze" a filearea which means Moodle will take ownership of all the remote
files of this type.
When accessing a file, if the "filebrowser" infomation indicates the current user can write to the file, they
will be granted temporary write access.
Part of MDL-58220
---
backup/backupfilesedit_form.php | 3 +-
files/renderer.php | 6 +
lang/en/repository.php | 1 +
lib/filelib.php | 17 +-
lib/filestorage/file_storage.php | 31 +++
lib/filestorage/stored_file.php | 9 +
lib/form/editor.php | 4 +-
lib/form/filemanager.php | 2 +-
lib/upgrade.txt | 5 +
mod/assign/assignmentplugin.php | 20 +-
mod/assign/lang/en/assign.php | 1 +
mod/assign/locallib.php | 19 ++
mod/assign/renderable.php | 1 +
mod/assign/renderer.php | 2 +-
mod/assign/submission/file/locallib.php | 24 +-
mod/assign/submission/onlinetext/locallib.php | 2 +-
mod/data/field/file/field.class.php | 4 +-
mod/forum/classes/post_form.php | 2 +-
mod/forum/lib.php | 5 +-
mod/wiki/filesedit.php | 3 +-
mod/workshop/locallib.php | 11 +-
question/type/essay/renderer.php | 2 +-
repository/areafiles/lib.php | 1 +
repository/filepicker.js | 14 +-
repository/googledocs/classes/rest.php | 8 +
repository/googledocs/lib.php | 212 ++++++++++++++++--
repository/lib.php | 17 +-
repository/repository_ajax.php | 3 +-
.../core/filemanager_selectlayout.mustache | 6 +
29 files changed, 391 insertions(+), 44 deletions(-)
diff --git a/backup/backupfilesedit_form.php b/backup/backupfilesedit_form.php
index dce09fe9fa0..fa0257717b5 100644
--- a/backup/backupfilesedit_form.php
+++ b/backup/backupfilesedit_form.php
@@ -30,7 +30,8 @@ class backup_files_edit_form extends moodleform {
public function definition() {
$mform =& $this->_form;
- $options = array('subdirs' => 0, 'maxfiles' => -1, 'accepted_types' => '*', 'return_types' => FILE_INTERNAL | FILE_REFERENCE);
+ $types = (FILE_INTERNAL | FILE_REFERENCE | FILE_CONTRLLED_LINK);
+ $options = array('subdirs' => 0, 'maxfiles' => -1, 'accepted_types' => '*', 'return_types' => $types);
$mform->addElement('filemanager', 'files_filemanager', get_string('files'), null, $options);
diff --git a/files/renderer.php b/files/renderer.php
index 020c24d0baa..f63b336faed 100644
--- a/files/renderer.php
+++ b/files/renderer.php
@@ -772,6 +772,12 @@ class core_files_renderer extends plugin_renderer_base {
+
+
+
+
+
+
diff --git a/lang/en/repository.php b/lang/en/repository.php
index 16f77ddf476..1a89457bfbb 100644
--- a/lang/en/repository.php
+++ b/lang/en/repository.php
@@ -160,6 +160,7 @@ $string['lostsource'] = 'Error. Source is missing. {$a}';
$string['makefileinternal'] = 'Make a copy of the file';
$string['makefilelink'] = 'Link to the file directly';
$string['makefilereference'] = 'Create an alias/shortcut to the file';
+$string['makefilecontrolledlink'] = 'Create an access controlled link to the file';
$string['manage'] = 'Manage repositories';
$string['manageinstances'] = 'Manage instances';
$string['manageurl'] = 'Manage';
diff --git a/lib/filelib.php b/lib/filelib.php
index 8d1d3cf818b..e2bda31f674 100644
--- a/lib/filelib.php
+++ b/lib/filelib.php
@@ -256,6 +256,21 @@ function file_postupdate_standard_editor($data, $field, array $options, $context
return $data;
}
+/**
+ * For all files in this file area - walk the file list and copy each to a system owned account, making them read-only.
+ *
+ * @category files
+ * @param stdClass $context context - must already exist
+ * @param string $component
+ * @param string $filearea file area name
+ * @param int $itemid
+ * @return bool
+ */
+function file_prevent_changes_to_external_files($contextid, $component, $filearea, $itemid=false) {
+ $fs = get_file_storage();
+ return $fs->prevent_changes_to_external_files($contextid, $component, $filearea, $itemid);
+}
+
/**
* Saves text and files modified by Editor formslib element
*
@@ -813,7 +828,7 @@ function file_save_draft_area_files($draftitemid, $contextid, $component, $filea
$options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
}
$allowreferences = true;
- if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
+ if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
// we assume that if $options['return_types'] is NOT specified, we DO allow references.
// this is not exactly right. BUT there are many places in code where filemanager options
// are not passed to file_save_draft_area_files()
diff --git a/lib/filestorage/file_storage.php b/lib/filestorage/file_storage.php
index 1cf24fcd59e..bdc0c6cb100 100644
--- a/lib/filestorage/file_storage.php
+++ b/lib/filestorage/file_storage.php
@@ -2323,4 +2323,35 @@ class file_storage {
$data = array('id' => $referencefileid, 'lastsync' => $lastsync);
$DB->update_record('files_reference', (object)$data);
}
+
+ /**
+ * For an entire file area - walk through the files and for each one that is a controlled link,
+ * call prevent_changes on the repository. Typically this will copy the external file to a system
+ * account controlled by Moodle, remove all write access and update the file reference.
+ *
+ * @param int $contextid
+ * @param string $component
+ * @param string $filearea
+ * @param int $itemid
+ */
+ public function prevent_changes_to_external_files($contextid, $component, $filearea, $itemid = false) {
+ global $DB;
+
+ $transaction = $DB->start_delegated_transaction();
+
+ $files = $this->get_area_files($contextid, $component, $filearea, $itemid, 'id', false);
+
+ foreach ($files as $file) {
+ if ($file->is_external_file()) {
+ // Note that this function uses a cache, so we don't need to
+ // double cache these.
+ $repo = repository::get_repository_by_id($file->get_repository_id(), SYSCONTEXTID);
+
+ // We expect this function to throw exceptions on failure.
+ $repo->prevent_changes_to_external_file($file);
+ }
+ }
+ $transaction->allow_commit();
+ return true;
+ }
}
diff --git a/lib/filestorage/stored_file.php b/lib/filestorage/stored_file.php
index 192e7b8daf2..92478b61114 100644
--- a/lib/filestorage/stored_file.php
+++ b/lib/filestorage/stored_file.php
@@ -102,6 +102,15 @@ class stored_file {
return !empty($this->repository);
}
+ /**
+ * Whether or not this is a controlled link. Note that repositories cannot support FILE_REFERENCE and FILE_CONTROLLED_LINK.
+ *
+ * @return bool
+ */
+ public function is_controlled_link() {
+ return $this->is_external_file() && $this->repository->supported_returntypes() & FILE_CONTROLLED_LINK;
+ }
+
/**
* Update some file record fields
* NOTE: Must remain protected
diff --git a/lib/form/editor.php b/lib/form/editor.php
index 551e30645b5..e391a734508 100644
--- a/lib/form/editor.php
+++ b/lib/form/editor.php
@@ -58,8 +58,8 @@ class MoodleQuickForm_editor extends HTML_QuickForm_element implements templatab
/** @var array options provided to initalize filepicker */
protected $_options = array('subdirs' => 0, 'maxbytes' => 0, 'maxfiles' => 0, 'changeformat' => 0,
'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED, 'context' => null, 'noclean' => 0, 'trusttext' => 0,
- 'return_types' => 7, 'enable_filemanagement' => true);
- // $_options['return_types'] = FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
+ 'return_types' => 15, 'enable_filemanagement' => true);
+ // $_options['return_types'] = FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE | FILE_CONTROLLED_LINK
/** @var array values for editor */
protected $_values = array('text'=>null, 'format'=>null, 'itemid'=>null);
diff --git a/lib/form/filemanager.php b/lib/form/filemanager.php
index 0cbf543ea7e..1c9126fe0c0 100644
--- a/lib/form/filemanager.php
+++ b/lib/form/filemanager.php
@@ -78,7 +78,7 @@ class MoodleQuickForm_filemanager extends HTML_QuickForm_element implements temp
$this->_options['maxbytes'] = get_user_max_upload_file_size($PAGE->context, $CFG->maxbytes, $options['maxbytes']);
}
if (empty($options['return_types'])) {
- $this->_options['return_types'] = (FILE_INTERNAL | FILE_REFERENCE);
+ $this->_options['return_types'] = (FILE_INTERNAL | FILE_REFERENCE | FILE_CONTROLLED_LINK);
}
$this->_type = 'filemanager';
parent::__construct($elementName, $elementLabel, $attributes);
diff --git a/lib/upgrade.txt b/lib/upgrade.txt
index 1f7edcfdb01..b1293039d5e 100644
--- a/lib/upgrade.txt
+++ b/lib/upgrade.txt
@@ -1,6 +1,11 @@
This files describes API changes in core libraries and APIs,
information provided here is intended especially for developers.
=== 3.3 ===
+* Support added for a new type of external file: FILE_CONTROLLED_LINK. This is an external file that Moodle can control
+ the permissions. Moodle can make files read-only or grant temporary write access.
+ To make all the files in file area read only (owned by Moodle) - use file_prevent_changes_to_external_files().
+ When accessing a URL, the info from file_browser::get_file_info will be checked to determine if the user has write access,
+ if they do - the remote file will have access controls set to allow editing.
* The method moodleform::after_definition() has been added and can now be used to add some logic
to be performed after the form's definition was set. This is useful for intermediate subclasses.
* Moodle has support for font-awesome icons. Plugins should use the xxx_get_fontawesome_icon_map callback
diff --git a/mod/assign/assignmentplugin.php b/mod/assign/assignmentplugin.php
index 8861aece6aa..91c62f1840c 100644
--- a/mod/assign/assignmentplugin.php
+++ b/mod/assign/assignmentplugin.php
@@ -580,17 +580,26 @@ abstract class assign_plugin {
public function get_file_info($browser, $filearea, $itemid, $filepath, $filename) {
global $CFG, $DB, $USER;
$urlbase = $CFG->wwwroot.'/pluginfile.php';
-
+ $writeaccess = false;
// Permission check on the itemid.
if ($this->get_subtype() == 'assignsubmission') {
if ($itemid) {
- $record = $DB->get_record('assign_submission', array('id'=>$itemid), 'userid', IGNORE_MISSING);
+ $record = $DB->get_record('assign_submission', array('id'=>$itemid), 'userid,groupid', IGNORE_MISSING);
if (!$record) {
return null;
}
- if (!$this->assignment->can_view_submission($record->userid)) {
- return null;
+ if (!empty($record->userid)) {
+ if (!$this->assignment->can_view_submission($record->userid)) {
+ return null;
+ }
+ $writeaccess = $this->assignment->can_edit_submission($record->userid);
+ } else {
+ // Must be a team submission with a group.
+ if (!$this->assignment->can_view_group_submission($record->groupid)) {
+ return null;
+ }
+ $writeaccess = $this->assignment->can_edit_group_submission($record->groupid);
}
}
} else {
@@ -609,6 +618,7 @@ abstract class assign_plugin {
$filename))) {
return null;
}
+
return new file_info_stored($browser,
$this->assignment->get_context(),
$storedfile,
@@ -616,7 +626,7 @@ abstract class assign_plugin {
$filearea,
$itemid,
true,
- true,
+ $writeaccess,
false);
}
diff --git a/mod/assign/lang/en/assign.php b/mod/assign/lang/en/assign.php
index 9a4e07c6c34..46eaeb92d8e 100644
--- a/mod/assign/lang/en/assign.php
+++ b/mod/assign/lang/en/assign.php
@@ -155,6 +155,7 @@ $string['submissionmodifiedgroup'] = 'The submission has been modified by somebo
$string['duedatereached'] = 'The due date for this assignment has now passed';
$string['duedatevalidation'] = 'Due date must be after the allow submissions from date.';
$string['editattemptfeedback'] = 'Edit the grade and feedback for attempt number {$a}.';
+$string['editonline'] = 'Edit online';
$string['editingpreviousfeedbackwarning'] = 'You are editing the feedback for a previous attempt. This is attempt {$a->attemptnumber} out of {$a->totalattempts}.';
$string['editoverride'] = 'Edit override';
$string['editsubmission'] = 'Edit submission';
diff --git a/mod/assign/locallib.php b/mod/assign/locallib.php
index aec06e8f61e..4deb7ba05d6 100644
--- a/mod/assign/locallib.php
+++ b/mod/assign/locallib.php
@@ -4360,6 +4360,25 @@ class assign {
return false;
}
+ /**
+ * Perform an access check to see if the current $USER can edit this group submission.
+ *
+ * @param int $groupid
+ * @return bool
+ */
+ public function can_edit_group_submission($groupid) {
+ global $USER;
+
+ $members = $this->get_submission_group_members($groupid, true);
+ foreach ($members as $member) {
+ // If we can edit any members submission, we can edit the submission for the group.
+ if ($this->can_edit_submission($member->id)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
/**
* Perform an access check to see if the current $USER can view this group submission.
*
diff --git a/mod/assign/renderable.php b/mod/assign/renderable.php
index 6ee0e490ce7..8c6435e6a4f 100644
--- a/mod/assign/renderable.php
+++ b/mod/assign/renderable.php
@@ -911,6 +911,7 @@ class assign_files implements renderable {
*/
public function preprocess($dir, $filearea, $component) {
global $CFG;
+
foreach ($dir['subdirs'] as $subdir) {
$this->preprocess($subdir, $filearea, $component);
}
diff --git a/mod/assign/renderer.php b/mod/assign/renderer.php
index 2abf463a503..a987385578d 100644
--- a/mod/assign/renderer.php
+++ b/mod/assign/renderer.php
@@ -1420,7 +1420,7 @@ class mod_assign_renderer extends plugin_renderer_base {
$result .= '
');
+ $mform->addElement('html', $OUTPUT->doc_link('calendar/export', get_string('exporthelp', 'calendar'), true));
$export = array();
$export[] = $mform->createElement('radio', 'exportevents', '', get_string('eventsall', 'calendar'), 'all');
diff --git a/lib/classes/oauth2/api.php b/lib/classes/oauth2/api.php
index 436e1cc983e..3ca18ce7034 100644
--- a/lib/classes/oauth2/api.php
+++ b/lib/classes/oauth2/api.php
@@ -242,7 +242,7 @@ class api {
* Get the system account for an installed OAuth service.
* Never ever ever expose this to a webservice because it contains the refresh token which grants API access.
*
- * @param \core\oauth2\issuer $id
+ * @param \core\oauth2\issuer $issuer
* @return \core\oauth2\client
*/
public static function get_system_account(issuer $issuer) {
diff --git a/lib/classes/oauth2/client.php b/lib/classes/oauth2/client.php
index e216e92c316..1ef887a12c7 100644
--- a/lib/classes/oauth2/client.php
+++ b/lib/classes/oauth2/client.php
@@ -17,7 +17,7 @@
/**
* Configurable oauth2 client class.
*
- * @package core\oauth2
+ * @package core
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
diff --git a/lib/classes/oauth2/endpoint.php b/lib/classes/oauth2/endpoint.php
index 9832bc0ef9a..921f9a0e8da 100644
--- a/lib/classes/oauth2/endpoint.php
+++ b/lib/classes/oauth2/endpoint.php
@@ -17,7 +17,7 @@
/**
* Class for loading/storing oauth2 endpoints from the DB.
*
- * @package core_oauth2
+ * @package core
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@@ -36,7 +36,6 @@ use lang_string;
*/
class endpoint extends persistent {
- /** @const TABLE */
const TABLE = 'oauth2_endpoint';
/**
diff --git a/lib/classes/oauth2/issuer.php b/lib/classes/oauth2/issuer.php
index 1ff6cef8384..756d36ba804 100644
--- a/lib/classes/oauth2/issuer.php
+++ b/lib/classes/oauth2/issuer.php
@@ -17,7 +17,7 @@
/**
* Class for loading/storing issuers from the DB.
*
- * @package core_oauth2
+ * @package core
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@@ -35,7 +35,6 @@ use core\persistent;
*/
class issuer extends persistent {
- /** @const TABLE */
const TABLE = 'oauth2_issuer';
/**
diff --git a/lib/classes/oauth2/refresh_system_tokens_task.php b/lib/classes/oauth2/refresh_system_tokens_task.php
index c6e3db8fc08..22cb45ce610 100644
--- a/lib/classes/oauth2/refresh_system_tokens_task.php
+++ b/lib/classes/oauth2/refresh_system_tokens_task.php
@@ -21,12 +21,18 @@
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
+
namespace core\oauth2;
use \core\task\scheduled_task;
+defined('MOODLE_INTERNAL') || die();
+
/**
* Simple task to delete old messaging records.
+ * @package core
+ * @copyright 2017 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class refresh_system_tokens_task extends scheduled_task {
@@ -47,7 +53,7 @@ class refresh_system_tokens_task extends scheduled_task {
$admins = get_admins();
if (empty($admins)) {
- return;
+ return;
}
foreach ($admins as $admin) {
$strparams = ['siteurl' => $CFG->wwwroot, 'issuer' => $issuer->get('name')];
diff --git a/lib/classes/oauth2/rest.php b/lib/classes/oauth2/rest.php
index 4a405f234a7..f7049e6f54c 100644
--- a/lib/classes/oauth2/rest.php
+++ b/lib/classes/oauth2/rest.php
@@ -63,6 +63,7 @@ abstract class rest {
*
* @param string $functionname
* @param array $functionargs
+ * @param string $rawpost Optional param to include in the body of a post.
*/
public function call($functionname, $functionargs, $rawpost = false) {
$functions = $this->get_api_functions();
diff --git a/lib/classes/oauth2/system_account.php b/lib/classes/oauth2/system_account.php
index c30b0d02fea..74aa5c81611 100644
--- a/lib/classes/oauth2/system_account.php
+++ b/lib/classes/oauth2/system_account.php
@@ -16,10 +16,8 @@
/**
* When using OAuth sometimes it makes sense to authenticate as a system user, and not the current user.
- * In this case we use a refresh token to get an access token and the system admin must manually authorize the
- * system account.
*
- * @package core_oauth2
+ * @package core
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@@ -37,7 +35,6 @@ use core\persistent;
*/
class system_account extends persistent {
- /** @const TABLE */
const TABLE = 'oauth2_system_account';
/**
diff --git a/lib/classes/oauth2/user_field_mapping.php b/lib/classes/oauth2/user_field_mapping.php
index a67a089247e..9751bc9009a 100644
--- a/lib/classes/oauth2/user_field_mapping.php
+++ b/lib/classes/oauth2/user_field_mapping.php
@@ -17,7 +17,7 @@
/**
* Class for loading/storing oauth2 endpoints from the DB.
*
- * @package core_oauth2
+ * @package core
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@@ -35,7 +35,6 @@ use core\persistent;
*/
class user_field_mapping extends persistent {
- /** @const TABLE */
const TABLE = 'oauth2_user_field_mapping';
/** @var array $userfields - List of standard Moodle userfields. */
diff --git a/lib/filelib.php b/lib/filelib.php
index e2bda31f674..df71196dbba 100644
--- a/lib/filelib.php
+++ b/lib/filelib.php
@@ -260,7 +260,7 @@ function file_postupdate_standard_editor($data, $field, array $options, $context
* For all files in this file area - walk the file list and copy each to a system owned account, making them read-only.
*
* @category files
- * @param stdClass $context context - must already exist
+ * @param int $contextid context id - must already exist
* @param string $component
* @param string $filearea file area name
* @param int $itemid
@@ -3495,7 +3495,7 @@ class curl {
$options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
unset($this->_tmp_file_post_params);
} else {
- // $params is the raw post data
+ // The variable $params is the raw post data.
$options['CURLOPT_POSTFIELDS'] = $params;
}
return $this->request($url, $options);
diff --git a/lib/form/editor.php b/lib/form/editor.php
index e391a734508..69a78127219 100644
--- a/lib/form/editor.php
+++ b/lib/form/editor.php
@@ -59,7 +59,7 @@ class MoodleQuickForm_editor extends HTML_QuickForm_element implements templatab
protected $_options = array('subdirs' => 0, 'maxbytes' => 0, 'maxfiles' => 0, 'changeformat' => 0,
'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED, 'context' => null, 'noclean' => 0, 'trusttext' => 0,
'return_types' => 15, 'enable_filemanagement' => true);
- // $_options['return_types'] = FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE | FILE_CONTROLLED_LINK
+ // 15 is $_options['return_types'] = FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE | FILE_CONTROLLED_LINK.
/** @var array values for editor */
protected $_values = array('text'=>null, 'format'=>null, 'itemid'=>null);
diff --git a/lib/oauthlib.php b/lib/oauthlib.php
index e77ce051cad..cf62393b61d 100644
--- a/lib/oauthlib.php
+++ b/lib/oauthlib.php
@@ -383,21 +383,21 @@ class oauth_helper {
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class oauth2_client extends curl {
- /** var string client identifier issued to the client */
+ /** @var string $clientid client identifier issued to the client */
private $clientid = '';
- /** var string The client secret. */
+ /** @var string $clientsecret The client secret. */
private $clientsecret = '';
- /** var moodle_url URL to return to after authenticating */
+ /** @var moodle_url $returnurl URL to return to after authenticating */
private $returnurl = null;
- /** var string scope of the authentication request */
+ /** @var string $scope of the authentication request */
protected $scope = '';
- /** var stdClass access token object */
+ /** @var stdClass $accesstoken access token object */
private $accesstoken = null;
- /** var stdClass refresh token string */
+ /** @var string $refreshtoken refresh token string */
private $refreshtoken = '';
- /** var string mocknextresponse string */
+ /** @var string $mocknextresponse string */
private $mocknextresponse = '';
- /** var array $upgradedcodes list of upgraded codes in this request */
+ /** @var array $upgradedcodes list of upgraded codes in this request */
private static $upgradedcodes = [];
/**
diff --git a/mod/assign/assignmentplugin.php b/mod/assign/assignmentplugin.php
index 91c62f1840c..83b8dfa8b39 100644
--- a/mod/assign/assignmentplugin.php
+++ b/mod/assign/assignmentplugin.php
@@ -585,7 +585,7 @@ abstract class assign_plugin {
if ($this->get_subtype() == 'assignsubmission') {
if ($itemid) {
- $record = $DB->get_record('assign_submission', array('id'=>$itemid), 'userid,groupid', IGNORE_MISSING);
+ $record = $DB->get_record('assign_submission', array('id' => $itemid), 'userid,groupid', IGNORE_MISSING);
if (!$record) {
return null;
}
diff --git a/mod/wiki/filesedit.php b/mod/wiki/filesedit.php
index 08378821386..91ed22e61a2 100644
--- a/mod/wiki/filesedit.php
+++ b/mod/wiki/filesedit.php
@@ -84,7 +84,7 @@ $data->returnurl = $returnurl;
$data->subwikiid = $subwiki->id;
$maxbytes = get_max_upload_file_size($CFG->maxbytes, $COURSE->maxbytes);
$types = FILE_INTERNAL | FILE_REFERENCE | FILE_CONTROLLED_LINK;
-$options = array('subdirs'=>0, 'maxbytes'=>$maxbytes, 'maxfiles'=>-1, 'accepted_types'=>'*', 'return_types'=>$types);
+$options = array('subdirs' => 0, 'maxbytes' => $maxbytes, 'maxfiles' => -1, 'accepted_types' => '*', 'return_types' => $types);
file_prepare_standard_filemanager($data, 'files', $options, $context, 'mod_wiki', 'attachments', $subwiki->id);
$mform = new mod_wiki_filesedit_form(null, array('data'=>$data, 'options'=>$options));
diff --git a/repository/googledocs/db/caches.php b/repository/googledocs/db/caches.php
index 0f554b62631..a751ed9b8cd 100644
--- a/repository/googledocs/db/caches.php
+++ b/repository/googledocs/db/caches.php
@@ -25,6 +25,8 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
+defined('MOODLE_INTERNAL') || die();
+
$definitions = array(
// Used to store file ids for folders.
diff --git a/repository/googledocs/lib.php b/repository/googledocs/lib.php
index ad2f1219ee2..f482046561f 100644
--- a/repository/googledocs/lib.php
+++ b/repository/googledocs/lib.php
@@ -73,7 +73,7 @@ class repository_googledocs extends repository {
/**
* Get a cached user authenticated oauth client.
*
- * @param moodle_url $usecurrenturl - Use this url instead of the repo callback.
+ * @param moodle_url $overrideurl - Use this url instead of the repo callback.
* @return \core\oauth2\client
*/
protected function get_user_oauth_client($overrideurl = false) {
@@ -668,9 +668,9 @@ class repository_googledocs extends repository {
/**
* List the permissions on a file.
- * @param \core\oauth2\client $client Authenticated client.
- * @param string $fileid The id of the file.
*
+ * @param \repository_googledocs\rest $client Authenticated client.
+ * @param string $fileid The id of the file.
* @return array
*/
protected function list_file_permissions(\repository_googledocs\rest $client, $fileid) {
@@ -681,10 +681,9 @@ class repository_googledocs extends repository {
/**
* See if a folder exists within a folder
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $foldername The folder we are looking for.
* @param string $parentid The parent folder we are looking in.
- *
* @return string|boolean The file id if it exists or false.
*/
protected function folder_exists_in_folder(\repository_googledocs\rest $client, $foldername, $parentid) {
@@ -704,7 +703,7 @@ class repository_googledocs extends repository {
/**
* Create a folder within a folder
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $foldername The folder we are creating.
* @param string $parentid The parent folder we are creating in.
*
@@ -725,7 +724,7 @@ class repository_googledocs extends repository {
/**
* Get capabilities for a file.
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are checking.
*
* @return stdClass The file info with capabilities.
@@ -742,7 +741,7 @@ class repository_googledocs extends repository {
/**
* Get simple file info for humans.
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are querying.
*
* @return stdClass
@@ -759,8 +758,9 @@ class repository_googledocs extends repository {
/**
* Update file owner.
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are updating.
+ * @param string $owneremail
*
* @return boolean Did it work?
*/
@@ -783,7 +783,7 @@ class repository_googledocs extends repository {
* Copy a file and return the new file details. A side effect of the copy
* is that the owner will be the account authenticated with this oauth client.
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are copying.
* @param string $name The original filename (don't change it).
*
@@ -811,14 +811,13 @@ class repository_googledocs extends repository {
/**
* Delete a file (for the current user).
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are deleting.
* @return boolean
*/
- protected function delete_file($client, $fileid) {
+ protected function delete_file(\repository_googledocs\rest $client, $fileid) {
$params = ['fileid' => $fileid];
$response = $client->call('delete', $params, ' ');
- var_dump($response);
if (empty($response->id)) {
$details = 'Cannot delete file: ' . $fileid;
throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
@@ -829,12 +828,12 @@ class repository_googledocs extends repository {
/**
* Add a writer to the permissions on the file (temporary).
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are updating.
* @param string $email The email of the writer account to add.
* @return boolean
*/
- protected function add_temp_writer_to_file($client, $fileid, $email) {
+ protected function add_temp_writer_to_file(\repository_googledocs\rest $client, $fileid, $email) {
// Expires in 7 days.
$expires = new DateTime();
$expires->add(new DateInterval("P7D"));
@@ -858,12 +857,12 @@ class repository_googledocs extends repository {
/**
* Add a writer to the permissions on the file.
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are updating.
* @param string $email The email of the writer account to add.
* @return boolean
*/
- protected function add_writer_to_file($client, $fileid, $email) {
+ protected function add_writer_to_file(\repository_googledocs\rest $client, $fileid, $email) {
$updateeditor = [
'emailAddress' => $email,
'role' => 'writer',
@@ -881,12 +880,12 @@ class repository_googledocs extends repository {
/**
* Move from root to folder
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are updating.
* @param string $folderid The id of the folder we are moving to
* @return boolean
*/
- protected function move_file_from_root_to_folder($client, $fileid, $folderid) {
+ protected function move_file_from_root_to_folder(\repository_googledocs\rest $client, $fileid, $folderid) {
// Set the parent.
$params = [
'fileid' => $fileid, 'addParents' => $folderid, 'removeParents' => 'root'
@@ -902,12 +901,12 @@ class repository_googledocs extends repository {
/**
* Remove parent
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are updating.
* @param string $folderid The id of the folder we are removing
* @return boolean
*/
- protected function remove_file_parent($client, $fileid, $folderid) {
+ protected function remove_file_parent(\repository_googledocs\rest $client, $fileid, $folderid) {
// Set the parent.
$params = [
'fileid' => $fileid, 'removeParents' => $folderid
@@ -923,11 +922,11 @@ class repository_googledocs extends repository {
/**
* Prevent writers from sharing.
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are updating.
* @return boolean
*/
- protected function prevent_writers_from_sharing_file($client, $fileid) {
+ protected function prevent_writers_from_sharing_file(\repository_googledocs\rest $client, $fileid) {
// We don't want anyone but Moodle to change the sharing settings.
$params = [
'fileid' => $fileid
@@ -946,11 +945,11 @@ class repository_googledocs extends repository {
/**
* Allow anyone with the link to read the file.
*
- * @param \core\oauth2\client $client Authenticated client.
+ * @param \repository_googledocs\rest $client Authenticated client.
* @param string $fileid The file we are updating.
* @return boolean
*/
- protected function set_file_sharing_anyone_with_link_can_read($client, $fileid) {
+ protected function set_file_sharing_anyone_with_link_can_read(\repository_googledocs\rest $client, $fileid) {
$updateread = [
'type' => 'anyone',
'role' => 'reader',
@@ -1030,7 +1029,7 @@ class repository_googledocs extends repository {
$foldername = $context->get_context_name();
$fullpath .= '/' . $foldername;
- $folderid = $cache->get('fullpath');
+ $folderid = $cache->get('fullpath');
if (empty($folderid)) {
$folderid = $this->folder_exists_in_folder($systemservice, $foldername, $parentid);
}
@@ -1179,7 +1178,11 @@ class repository_googledocs extends repository {
}
}
-// Icon from: http://www.iconspedia.com/icon/google-2706.html.
+/**
+ * Callback to get the required scopes for system account.
+ *
+ * @return string
+ */
function repository_googledocs_oauth2_system_scopes() {
return 'https://www.googleapis.com/auth/drive';
}
From 141ee541cad11846d3df8e1aa336ceb8fca89a11 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 14 Mar 2017 12:17:30 +0800
Subject: [PATCH 31/84] MDL-58219 repository: Change how controlled links work
Files are copied to the system user as soon as they are uploaded. Write access is then controlled when
serving links to the file.
Part of MDL-58220
---
lib/classes/oauth2/api.php | 2 +-
lib/classes/oauth2/rest.php | 3 ++-
lib/db/install.xml | 1 -
lib/db/upgrade.php | 1 -
lib/filelib.php | 24 ++++++-----------
lib/filestorage/file_storage.php | 35 ++-----------------------
lib/oauthlib.php | 6 +----
lib/upgrade.txt | 3 +--
mod/assign/submission/file/locallib.php | 13 ---------
mod/data/field/file/field.class.php | 2 --
mod/forum/lib.php | 2 --
mod/workshop/locallib.php | 7 -----
repository/lib.php | 18 +++----------
repository/repository_ajax.php | 4 ---
14 files changed, 19 insertions(+), 102 deletions(-)
diff --git a/lib/classes/oauth2/api.php b/lib/classes/oauth2/api.php
index 3ca18ce7034..c886a1aaecb 100644
--- a/lib/classes/oauth2/api.php
+++ b/lib/classes/oauth2/api.php
@@ -107,7 +107,7 @@ class api {
'name' => 'alternatename',
'last_name' => 'lastname',
'email' => 'email',
- 'id' => 'username',
+ 'third_party_id' => 'username',
'first_name' => 'firstname',
'picture-data-url' => 'picture',
'link' => 'url',
diff --git a/lib/classes/oauth2/rest.php b/lib/classes/oauth2/rest.php
index f7049e6f54c..c790429c891 100644
--- a/lib/classes/oauth2/rest.php
+++ b/lib/classes/oauth2/rest.php
@@ -74,6 +74,7 @@ abstract class rest {
$method = $functions[$functionname]['method'];
$endpoint = $functions[$functionname]['endpoint'];
+
$responsetype = $functions[$functionname]['response'];
if (!in_array($method, $supportedmethods)) {
throw new coding_exception('unsupported api method: ' . $method);
@@ -112,7 +113,7 @@ abstract class rest {
$json = json_decode($response);
if (!empty($json->error)) {
- throw new rest_exception($json->error->message, $json->error->code);
+ throw new rest_exception($json->error->code . ': ' . $json->error->message);
}
return $json;
}
diff --git a/lib/db/install.xml b/lib/db/install.xml
index 7610a685c53..adb86a4f4ed 100755
--- a/lib/db/install.xml
+++ b/lib/db/install.xml
@@ -3531,7 +3531,6 @@
-
diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php
index 5deb30d322b..c5878f7b3a0 100644
--- a/lib/db/upgrade.php
+++ b/lib/db/upgrade.php
@@ -2719,7 +2719,6 @@ function xmldb_main_upgrade($oldversion) {
// Adding keys to table oauth2_user_field_mapping.
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$table->add_key('issuerkey', XMLDB_KEY_FOREIGN, array('issuerid'), 'oauth2_issuer', array('id'));
- $table->add_key('uniqexternal', XMLDB_KEY_UNIQUE, array('issuerid', 'externalfield'));
$table->add_key('uniqinternal', XMLDB_KEY_UNIQUE, array('issuerid', 'internalfield'));
// Conditionally launch create table for oauth2_user_field_mapping.
diff --git a/lib/filelib.php b/lib/filelib.php
index df71196dbba..d9e0b0bb414 100644
--- a/lib/filelib.php
+++ b/lib/filelib.php
@@ -256,21 +256,6 @@ function file_postupdate_standard_editor($data, $field, array $options, $context
return $data;
}
-/**
- * For all files in this file area - walk the file list and copy each to a system owned account, making them read-only.
- *
- * @category files
- * @param int $contextid context id - must already exist
- * @param string $component
- * @param string $filearea file area name
- * @param int $itemid
- * @return bool
- */
-function file_prevent_changes_to_external_files($contextid, $component, $filearea, $itemid=false) {
- $fs = get_file_storage();
- return $fs->prevent_changes_to_external_files($contextid, $component, $filearea, $itemid);
-}
-
/**
* Saves text and files modified by Editor formslib element
*
@@ -968,8 +953,15 @@ function file_save_draft_area_files($draftitemid, $contextid, $component, $filea
if ($file->is_external_file()) {
$repoid = $file->get_repository_id();
if (!empty($repoid)) {
+ $context = context::instance_by_id($contextid, MUST_EXIST);
+ $repo = repository::get_repository_by_id($repoid, $context);
+
$file_record['repositoryid'] = $repoid;
- $file_record['reference'] = $file->get_reference();
+ // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
+ // to the file store. E.g. transfer ownership of the file to a system account etc.
+ $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
+
+ $file_record['reference'] = $reference;
}
}
diff --git a/lib/filestorage/file_storage.php b/lib/filestorage/file_storage.php
index bdc0c6cb100..7fd1eaaa4ac 100644
--- a/lib/filestorage/file_storage.php
+++ b/lib/filestorage/file_storage.php
@@ -1128,9 +1128,8 @@ class file_storage {
// creating a new file from an existing alias creates new alias implicitly.
// here we just check the database consistency.
if (!empty($newrecord->repositoryid)) {
- if ($newrecord->referencefileid != $this->get_referencefileid($newrecord->repositoryid, $newrecord->reference, MUST_EXIST)) {
- throw new file_reference_exception($newrecord->repositoryid, $newrecord->reference, $newrecord->referencefileid);
- }
+ // It is OK if the current reference does not exist. It may have been altered by a repository plugin when the files where saved from a draft area.
+ $newrecord->referencefileid = $this->get_or_create_referencefileid($newrecord->repositoryid, $newrecord->reference);
}
try {
@@ -2324,34 +2323,4 @@ class file_storage {
$DB->update_record('files_reference', (object)$data);
}
- /**
- * For an entire file area - walk through the files and for each one that is a controlled link,
- * call prevent_changes on the repository. Typically this will copy the external file to a system
- * account controlled by Moodle, remove all write access and update the file reference.
- *
- * @param int $contextid
- * @param string $component
- * @param string $filearea
- * @param int $itemid
- */
- public function prevent_changes_to_external_files($contextid, $component, $filearea, $itemid = false) {
- global $DB;
-
- $transaction = $DB->start_delegated_transaction();
-
- $files = $this->get_area_files($contextid, $component, $filearea, $itemid, 'id', false);
-
- foreach ($files as $file) {
- if ($file->is_external_file()) {
- // Note that this function uses a cache, so we don't need to
- // double cache these.
- $repo = repository::get_repository_by_id($file->get_repository_id(), SYSCONTEXTID);
-
- // We expect this function to throw exceptions on failure.
- $repo->prevent_changes_to_external_file($file);
- }
- }
- $transaction->allow_commit();
- return true;
- }
}
diff --git a/lib/oauthlib.php b/lib/oauthlib.php
index cf62393b61d..c684c9c911a 100644
--- a/lib/oauthlib.php
+++ b/lib/oauthlib.php
@@ -576,11 +576,7 @@ abstract class oauth2_client extends curl {
// Expires 10 seconds before actual expiry.
$accesstoken->expires = (time() + ($r->expires_in - 10));
}
- if (isset($r->scope)) {
- $accesstoken->scope = $r->scope;
- } else {
- $accesstoken->scope = $this->scope;
- }
+ $accesstoken->scope = $this->scope;
// Also add the scopes.
self::$upgradedcodes[] = $code;
$this->store_token($accesstoken);
diff --git a/lib/upgrade.txt b/lib/upgrade.txt
index b1293039d5e..088454b38bb 100644
--- a/lib/upgrade.txt
+++ b/lib/upgrade.txt
@@ -2,8 +2,7 @@ This files describes API changes in core libraries and APIs,
information provided here is intended especially for developers.
=== 3.3 ===
* Support added for a new type of external file: FILE_CONTROLLED_LINK. This is an external file that Moodle can control
- the permissions. Moodle can make files read-only or grant temporary write access.
- To make all the files in file area read only (owned by Moodle) - use file_prevent_changes_to_external_files().
+ the permissions. Moodle makes files read-only but can grant temporary write access.
When accessing a URL, the info from file_browser::get_file_info will be checked to determine if the user has write access,
if they do - the remote file will have access controls set to allow editing.
* The method moodleform::after_definition() has been added and can now be used to add some logic
diff --git a/mod/assign/submission/file/locallib.php b/mod/assign/submission/file/locallib.php
index ba222f490d7..cd54142cb34 100644
--- a/mod/assign/submission/file/locallib.php
+++ b/mod/assign/submission/file/locallib.php
@@ -552,19 +552,6 @@ class assign_submission_file extends assign_submission_plugin {
);
}
- /**
- * Make any controlled links in the submission area read-only for the student.
- *
- * @param stdClass $submission the assign_submission record being submitted.
- * @return void
- */
- public function submit_for_grading($submission) {
- file_prevent_changes_to_external_files($this->assignment->get_context()->id,
- 'assignsubmission_file',
- ASSIGNSUBMISSION_FILE_FILEAREA,
- $submission->id);
- }
-
/**
* Return the plugin configs for external functions.
*
diff --git a/mod/data/field/file/field.class.php b/mod/data/field/file/field.class.php
index 0263432c21d..251fa7c93dc 100644
--- a/mod/data/field/file/field.class.php
+++ b/mod/data/field/file/field.class.php
@@ -185,8 +185,6 @@ class data_field_file extends data_field_base {
$usercontext = context_user::instance($USER->id);
$files = $fs->get_area_files($this->context->id, 'mod_data', 'content', $content->id, 'itemid, filepath, filename', false);
- file_prevent_changes_to_external_files($this->context->id, 'mod_data', 'content', $content->id);
-
// We expect no or just one file (maxfiles = 1 option is set for the form_filemanager).
if (count($files) == 0) {
$content->content = null;
diff --git a/mod/forum/lib.php b/mod/forum/lib.php
index cef2dd0e197..a14d1eddb80 100644
--- a/mod/forum/lib.php
+++ b/mod/forum/lib.php
@@ -559,9 +559,7 @@ function forum_cron() {
}
}
- // We need to prevent changes to controlled links in attachments.
$modcontext = context_module::instance($coursemodules[$forumid]->id);
- file_prevent_changes_to_external_files($modcontext->id, 'mod_forum', 'attachment', $pid);
// Save the Inbound Message datakey here to reduce DB queries later.
$messageinboundgenerator->set_data($pid);
diff --git a/mod/workshop/locallib.php b/mod/workshop/locallib.php
index c19a0c02d6b..af0dca3c231 100644
--- a/mod/workshop/locallib.php
+++ b/mod/workshop/locallib.php
@@ -1843,13 +1843,6 @@ class workshop {
workshop_update_grades($workshop);
}
- if (self::PHASE_ASSESSMENT == $newphase) {
- file_prevent_changes_to_external_files($this->context->id, 'mod_workshop', 'submission_content');
- }
- if (self::PHASE_EVALUATION == $newphase) {
- file_prevent_changes_to_external_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment');
- }
-
$DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
$this->phase = $newphase;
$eventdata = array(
diff --git a/repository/lib.php b/repository/lib.php
index f30c5cb7e01..7522ca9247f 100644
--- a/repository/lib.php
+++ b/repository/lib.php
@@ -1290,9 +1290,12 @@ abstract class repository implements cacheable_object {
* @param string $reference this reference is generated by
* repository::get_file_reference()
* @param context $context the target context for this new file.
+ * @param string $component the target component for this new file.
+ * @param string $filearea the target filearea for this new file.
+ * @param string $itemid the target itemid for this new file.
* @return string updated reference (final one before it's saved to db).
*/
- public function reference_file_selected($reference, $context) {
+ public function reference_file_selected($reference, $context, $component, $filearea, $itemid) {
return $reference;
}
@@ -2680,19 +2683,6 @@ abstract class repository implements cacheable_object {
'Use repository::sync_reference instead.');
}
- /**
- * Update an external file so only Moodle has write access to it.
- * This function must be implemented by all repositories supporting FILE_CONTROLLED_LINK return types.
- *
- * Throw exceptions on error and the transaction will be rolled back
- * (because it is called on an entire filearea at a time).
- *
- * @param stored_file $file
- */
- public function prevent_changes_to_external_file(stored_file $file) {
- return;
- }
-
/**
* Performs synchronisation of an external file if the previous one has expired.
*
diff --git a/repository/repository_ajax.php b/repository/repository_ajax.php
index 20ae194f2fc..9cda39912ba 100644
--- a/repository/repository_ajax.php
+++ b/repository/repository_ajax.php
@@ -228,10 +228,6 @@ switch ($action) {
$record->filesize = $sourcefile->get_filesize();
}
- // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
- // to the file store. E.g. transfer ownership of the file to a system account etc.
- $reference = $repo->reference_file_selected($reference, $context);
-
// Check if file exists.
if (repository::draftfile_exists($itemid, $saveas_path, $saveas_filename)) {
// File name being used, rename it.
From 72643dc688a50e67fe2f31769c39f49a86f66b84 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 14 Mar 2017 12:50:09 +0800
Subject: [PATCH 32/84] MDL-58219 googledocs: Update to new model for
controlledlinks
Part of MDL-58220
---
repository/googledocs/classes/rest.php | 9 -
.../lang/en/repository_googledocs.php | 2 +-
repository/googledocs/lib.php | 231 +++---------------
3 files changed, 39 insertions(+), 203 deletions(-)
diff --git a/repository/googledocs/classes/rest.php b/repository/googledocs/classes/rest.php
index 5c5e65a4a6c..6f46c55c05f 100644
--- a/repository/googledocs/classes/rest.php
+++ b/repository/googledocs/classes/rest.php
@@ -123,15 +123,6 @@ class rest extends \core\oauth2\rest {
],
'response' => 'json'
],
- 'list_permissions' => [
- 'endpoint' => 'https://www.googleapis.com/drive/v3/files/{fileid}/permissions',
- 'method' => 'get',
- 'args' => [
- 'fileid' => PARAM_RAW,
- 'fields' => PARAM_RAW
- ],
- 'response' => 'json'
- ],
];
}
}
diff --git a/repository/googledocs/lang/en/repository_googledocs.php b/repository/googledocs/lang/en/repository_googledocs.php
index 940fadce1e7..6374a5cca33 100644
--- a/repository/googledocs/lang/en/repository_googledocs.php
+++ b/repository/googledocs/lang/en/repository_googledocs.php
@@ -42,9 +42,9 @@ $string['supportedreturntypes'] = 'Supported files';
$string['defaultreturntype'] = 'Default return type';
$string['fileoptions'] = 'The types and defaults for returned files is configurable here. Note that all files linked externally will be updated so that the owner is the Moodle system account.';
$string['owner'] = 'Owned by: {$a}';
+$string['cachedef_folder'] = 'Google File IDs for folders in the system account';
// Deprecated since Moodle 3.3.
$string['oauthinfo'] = '
To use this plugin, you must register your site with Google, as described in the documentation Google OAuth 2.0 setup.
As part of the registration process, you will need to enter the following URL as \'Authorized Redirect URIs\':
{$a->callbackurl}
Once registered, you will be provided with a client ID and secret which can be used to configure all Google Drive and Picasa plugins.
Please also note that you will have to enable the service \'Drive API\'.
';
$string['secret'] = 'Secret';
$string['clientid'] = 'Client ID';
-$string['cachedef_folder'] = 'Google File IDs for folders in the system account';
diff --git a/repository/googledocs/lib.php b/repository/googledocs/lib.php
index f482046561f..50894a1432d 100644
--- a/repository/googledocs/lib.php
+++ b/repository/googledocs/lib.php
@@ -317,8 +317,7 @@ class repository_googledocs extends repository {
'id' => $gfile->id,
'name' => $gfile->name,
'exportformat' => 'download',
- 'link' => $link,
- 'claimed' => false
+ 'link' => $link
]);
$title = $gfile->name;
} else {
@@ -366,8 +365,7 @@ class repository_googledocs extends repository {
'id' => $gfile->id,
'exportformat' => $exporttype,
'link' => $link,
- 'name' => $gfile->name,
- 'claimed' => false
+ 'name' => $gfile->name
]);
}
// Adds the file to the file list. Using the itemId along with the name as key
@@ -553,7 +551,7 @@ class repository_googledocs extends repository {
$storedfile->get_filepath(),
$storedfile->get_filename());
- if (!empty($source->claimed) && $info->is_writable()) {
+ if ($info->is_writable()) {
// Add the current user as an OAuth writer.
$systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
@@ -594,90 +592,6 @@ class repository_googledocs extends repository {
}
}
- /**
- * Update an external file so only Moodle has write access to it.
- * This function must be implemented by all repositories supporting FILE_CONTROLLED_LINK return types.
- *
- * Throw exceptions on error and the transaction will be rolled back
- * (because it is called on an entire filearea at a time).
- *
- * @param stored_file $file
- */
- public function prevent_changes_to_external_file(stored_file $file) {
- global $DB;
-
- // Copy the file (will make it owned by moodle system account).
- // Update the sharing settings on the file.
- // Prevent editors from sharing the file.
- $source = json_decode($file->get_reference());
-
- $systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
-
- if ($systemauth === false) {
- $details = 'Cannot connect as system user';
- throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
- }
- $systemservice = new repository_googledocs\rest($systemauth);
-
- // Copy the file so we get a snapshot file owned by Moodle.
- $newsource = $this->copy_file($systemservice, $source->id, $source->name);
-
- // Set the sharing options.
- $this->set_file_sharing_anyone_with_link_can_read($systemservice, $newsource->id);
- $this->prevent_writers_from_sharing_file($systemservice, $newsource->id);
- // Delete the original file from the Moodle account. This only deletes it for us (not the original owner).
-
- $summary = $this->get_file_summary($systemservice, $source->id);
- if (!empty($summary->parents[0])) {
- $myparent = $summary->parents[0];
- $this->remove_file_parent($systemservice, $source->id, $myparent);
- }
- // We need to change the source on the existing file now to point to the new id.
- $source->id = $newsource->id;
- $source->link = isset($newsource->webViewLink) ? $newsource->webViewLink : '';
- if (empty($source->link)) {
- $source->link = isset($newsource->webContentLink) ? $newsource->webContentLink : '';
- }
- $source->claimed = true;
- $reference = json_encode($source);
- $file->set_source($reference);
-
- // We need to update the reference in the file_reference table.
- $refid = $file->get_referencefileid();
- $newref = (object) [
- 'id' => $refid,
- 'reference' => $reference,
- 'referencehash' => sha1($reference)
- ];
- $DB->update_record('files_reference', $newref);
-
- return true;
- }
-
- /**
- * Grant write access and redirect to an edit link for the file.
- *
- * @param stored_file $storedfile the file that contains the reference
- */
- public function edit_external_file($storedfile) {
- // Grant writer access to this file.
-
- // Redirect to the file.
- $this->send_file($storedfile);
- }
-
- /**
- * List the permissions on a file.
- *
- * @param \repository_googledocs\rest $client Authenticated client.
- * @param string $fileid The id of the file.
- * @return array
- */
- protected function list_file_permissions(\repository_googledocs\rest $client, $fileid) {
- $fields = "permissions(id,type,emailAddress,role,allowFileDiscovery,displayName)";
- return $client->call('list_permissions', ['fileid' => $fileid]);
- }
-
/**
* See if a folder exists within a folder
*
@@ -721,23 +635,6 @@ class repository_googledocs extends repository {
return $created->id;
}
- /**
- * Get capabilities for a file.
- *
- * @param \repository_googledocs\rest $client Authenticated client.
- * @param string $fileid The file we are checking.
- *
- * @return stdClass The file info with capabilities.
- */
- protected function get_file_capabilities(\repository_googledocs\rest $client, $fileid) {
- $fields = "id,capabilities,writersCanShare";
- $params = [
- 'fileid' => $fileid,
- 'fields' => $fields
- ];
- return $client->call('get', $params);
- }
-
/**
* Get simple file info for humans.
*
@@ -755,30 +652,6 @@ class repository_googledocs extends repository {
return $client->call('get', $params);
}
- /**
- * Update file owner.
- *
- * @param \repository_googledocs\rest $client Authenticated client.
- * @param string $fileid The file we are updating.
- * @param string $owneremail
- *
- * @return boolean Did it work?
- */
- protected function update_file_owner(\repository_googledocs\rest $client, $fileid, $owneremail) {
- $updateowner = [
- 'emailAddress' => $owneremail,
- 'role' => 'owner',
- 'type' => 'user'
- ];
- $params = ['fileid' => $fileid, 'transferOwnership' => 'true'];
- try {
- $response = $client->call('create_permission', $params, json_encode($updateowner));
- } catch (\core\oauth2\rest_exception $re) {
- return false;
- }
- return !empty($response->id);
- }
-
/**
* Copy a file and return the new file details. A side effect of the copy
* is that the owner will be the account authenticated with this oauth client.
@@ -808,23 +681,6 @@ class repository_googledocs extends repository {
return $fileinfo;
}
- /**
- * Delete a file (for the current user).
- *
- * @param \repository_googledocs\rest $client Authenticated client.
- * @param string $fileid The file we are deleting.
- * @return boolean
- */
- protected function delete_file(\repository_googledocs\rest $client, $fileid) {
- $params = ['fileid' => $fileid];
- $response = $client->call('delete', $params, ' ');
- if (empty($response->id)) {
- $details = 'Cannot delete file: ' . $fileid;
- throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
- }
- return true;
- }
-
/**
* Add a writer to the permissions on the file (temporary).
*
@@ -898,27 +754,6 @@ class repository_googledocs extends repository {
return true;
}
- /**
- * Remove parent
- *
- * @param \repository_googledocs\rest $client Authenticated client.
- * @param string $fileid The file we are updating.
- * @param string $folderid The id of the folder we are removing
- * @return boolean
- */
- protected function remove_file_parent(\repository_googledocs\rest $client, $fileid, $folderid) {
- // Set the parent.
- $params = [
- 'fileid' => $fileid, 'removeParents' => $folderid
- ];
- $response = $client->call('update', $params, ' ');
- if (empty($response->id)) {
- $details = 'Cannot remove the file parent: ' . $fileid . ', ' . $folderid;
- throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
- }
- return true;
- }
-
/**
* Prevent writers from sharing.
*
@@ -971,9 +806,12 @@ class repository_googledocs extends repository {
* @param string $reference this reference is generated by
* repository::get_file_reference()
* @param context $context the target context for this new file.
- * @return string $modifiedreference (final one before saving to DB)
+ * @param string $component the target component for this new file.
+ * @param string $filearea the target filearea for this new file.
+ * @param string $itemid the target itemid for this new file.
+ * @return string updated reference (final one before it's saved to db).
*/
- public function reference_file_selected($reference, $context) {
+ public function reference_file_selected($reference, $context, $component, $filearea, $itemid) {
// What we need to do here is transfer ownership to the system user (or copy)
// then set the permissions so anyone with the share link can view,
// finally update the reference to contain the share link if it was not
@@ -1000,21 +838,6 @@ class repository_googledocs extends repository {
$userservice = new repository_googledocs\rest($userauth);
$systemservice = new repository_googledocs\rest($systemauth);
- // Get the list of existing permissions so we can see if the owner is already the system account,
- // and whether we need to update the link sharing options.
- $permissions = $this->list_file_permissions($userservice, $source->id);
-
- $readshareupdaterequired = true;
- $ownerupdaterequired = true;
- foreach ($permissions->permissions as $permission) {
- if ($permission->id == 'anyoneWithLink' &&
- $permission->type == 'anyone' &&
- $permission->role == 'reader' &&
- $permission->allowFileDiscovery == false) {
- $readshareupdaterequired = false;
- }
- }
-
// Add Moodle as writer.
$this->add_writer_to_file($userservice, $source->id, $systemuseremail);
@@ -1024,12 +847,22 @@ class repository_googledocs extends repository {
$cache = cache::make('repository_googledocs', 'folder');
$parentid = 'root';
$fullpath = 'root';
+ $allfolders = [];
foreach ($contextlist as $context) {
// Make sure a folder exists here.
- $foldername = $context->get_context_name();
+ $foldername = clean_param($context->get_context_name(), PARAM_PATH);
+ $allfolders[] = $foldername;
+ }
+
+ $allfolders[] = clean_param($component, PARAM_PATH);
+ $allfolders[] = clean_param($filearea, PARAM_PATH);
+ $allfolders[] = clean_param($itemid, PARAM_PATH);
+
+ foreach ($allfolders as $foldername) {
+ // Make sure a folder exists here.
$fullpath .= '/' . $foldername;
- $folderid = $cache->get('fullpath');
+ $folderid = $cache->get($fullpath);
if (empty($folderid)) {
$folderid = $this->folder_exists_in_folder($systemservice, $foldername, $parentid);
}
@@ -1043,13 +876,22 @@ class repository_googledocs extends repository {
}
}
- $this->move_file_from_root_to_folder($systemservice, $source->id, $parentid);
+ // Copy the file so we get a snapshot file owned by Moodle.
+ $newsource = $this->copy_file($systemservice, $source->id, $source->name);
+ // Move the copied file to the correct folder.
+ $this->move_file_from_root_to_folder($systemservice, $newsource->id, $parentid);
- if ($readshareupdaterequired) {
- $this->set_file_sharing_anyone_with_link_can_read($systemservice, $source->id);
+ // Set the sharing options.
+ $this->set_file_sharing_anyone_with_link_can_read($systemservice, $newsource->id);
+ $this->prevent_writers_from_sharing_file($systemservice, $newsource->id);
+
+ $source->id = $newsource->id;
+ $source->link = isset($newsource->webViewLink) ? $newsource->webViewLink : '';
+ if (empty($source->link)) {
+ $source->link = isset($newsource->webContentLink) ? $newsource->webContentLink : '';
}
+ $reference = json_encode($source);
- // We did not update the reference at all.
return $reference;
}
@@ -1183,6 +1025,9 @@ class repository_googledocs extends repository {
*
* @return string
*/
-function repository_googledocs_oauth2_system_scopes() {
- return 'https://www.googleapis.com/auth/drive';
+function repository_googledocs_oauth2_system_scopes(\core\oauth2\issuer $issuer) {
+ if ($issuer->get('id') == get_config('googledocs', 'issuerid')) {
+ return 'https://www.googleapis.com/auth/drive';
+ }
+ return '';
}
From af28b228929365d1f473c3c6b92df7101cdb4b07 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 14 Mar 2017 14:20:16 +0800
Subject: [PATCH 33/84] MDL-58219 googledocs: Use google file extensions
Only rename on export for download.
Part of MDL-58220
---
lib/classes/filetypes.php | 5 +++++
repository/googledocs/lib.php | 33 +++++++++++++++++++++++++--------
repository/repository_ajax.php | 4 ++++
3 files changed, 34 insertions(+), 8 deletions(-)
diff --git a/lib/classes/filetypes.php b/lib/classes/filetypes.php
index b2ac0620be8..23d45bde610 100644
--- a/lib/classes/filetypes.php
+++ b/lib/classes/filetypes.php
@@ -100,6 +100,11 @@ abstract class core_filetypes {
'gallery' => array('type' => 'application/x-smarttech-notebook', 'icon' => 'archive'),
'galleryitem' => array('type' => 'application/x-smarttech-notebook', 'icon' => 'archive'),
'gallerycollection' => array('type' => 'application/x-smarttech-notebook', 'icon' => 'archive'),
+ 'gdraw' => array('type' => 'application/vnd.google-apps.drawing', 'icon' => 'image', 'groups' => array('image')),
+ 'gdoc' => array('type' => 'application/vnd.google-apps.document', 'icon' => 'document', 'groups' => array('document')),
+ 'gsheet' => array('type' => 'application/vnd.google-apps.spreadsheet', 'icon' => 'spreadsheet',
+ 'groups' => array('spreadsheet')),
+ 'gslides' => array('type' => 'application/vnd.google-apps.presentation', 'icon' => 'powerpoint', 'groups' => array('presentation')),
'gif' => array('type' => 'image/gif', 'icon' => 'gif', 'groups' => array('image', 'web_image'), 'string' => 'image'),
'gtar' => array('type' => 'application/x-gtar', 'icon' => 'archive',
'groups' => array('archive'), 'string' => 'archive'),
diff --git a/repository/googledocs/lib.php b/repository/googledocs/lib.php
index 50894a1432d..cbc275ff470 100644
--- a/repository/googledocs/lib.php
+++ b/repository/googledocs/lib.php
@@ -331,7 +331,7 @@ class repository_googledocs extends repository {
switch ($type){
case 'document':
$ext = $config->documentformat;
- $title = $gfile->name . '.'. $ext;
+ $title = $gfile->name . '.gdoc';
if ($ext === 'rtf') {
// Moodle user 'text/rtf' as the MIME type for RTF files.
// Google uses 'application/rtf' for the same type of file.
@@ -343,12 +343,12 @@ class repository_googledocs extends repository {
break;
case 'presentation':
$ext = $config->presentationformat;
- $title = $gfile->name . '.'. $ext;
+ $title = $gfile->name . '.gslides';
$exporttype = $types[$ext]['type'];
break;
case 'spreadsheet':
$ext = $config->spreadsheetformat;
- $title = $gfile->name . '.'. $ext;
+ $title = $gfile->name . '.gsheet';
$exporttype = $types[$ext]['type'];
break;
case 'drawing':
@@ -421,6 +421,7 @@ class repository_googledocs extends repository {
$source = json_decode($reference);
+ $newfilename = false;
if ($source->exportformat == 'download') {
$params = ['alt' => 'media'];
$sourceurl = new moodle_url($base . '/files/' . $source->id, $params);
@@ -428,20 +429,36 @@ class repository_googledocs extends repository {
} else {
$params = ['mimeType' => $source->exportformat];
$sourceurl = new moodle_url($base . '/files/' . $source->id . '/export', $params);
+ $types = get_mimetypes_array();
+ $checktype = $source->exportformat;
+ if ($checktype == 'application/rtf') {
+ $checktype = 'text/rtf';
+ }
+ foreach ($types as $extension => $info) {
+ if ($info['type'] == $checktype) {
+ $newfilename = $source->name . '.' . $extension;
+ break;
+ }
+ }
$source = $sourceurl->out(false);
}
// We use download_one and not the rest API because it has special timeouts etc.
$path = $this->prepare_file($filename);
$options = ['filepath' => $path, 'timeout' => 15, 'followlocation' => true, 'maxredirs' => 5];
- $result = $client->download_one($source, null, $options);
+ $success = $client->download_one($source, null, $options);
- if ($result) {
+ if ($success) {
@chmod($path, $CFG->filepermissions);
- return array(
+
+ $result = [
'path' => $path,
- 'url' => $reference
- );
+ 'url' => $reference,
+ ];
+ if (!empty($newfilename)) {
+ $result['newfilename'] = $newfilename;
+ }
+ return $result;
}
throw new repository_exception('cannotdownload', 'repository');
}
diff --git a/repository/repository_ajax.php b/repository/repository_ajax.php
index 9cda39912ba..726486a8e43 100644
--- a/repository/repository_ajax.php
+++ b/repository/repository_ajax.php
@@ -278,6 +278,10 @@ switch ($action) {
} else {
// Download file to moodle.
$downloadedfile = $repo->get_file($reference, $saveas_filename);
+
+ if (!empty($downloadedfile['newfilename'])) {
+ $record->filename = $downloadedfile['newfilename'];
+ }
if (empty($downloadedfile['path'])) {
$err->error = get_string('cannotdownload', 'repository');
die(json_encode($err));
From ffda3e395c78c053c7c9affdffb95d487dd5d960 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 14 Mar 2017 12:18:27 +0800
Subject: [PATCH 34/84] MDL-58127 skydrive: Upgrades to new oauth2
Support for controlled links workflow.
Part of MDL-58220
---
repository/skydrive/classes/access.php | 56 +
.../classes/remove_temp_access_task.php | 79 ++
repository/skydrive/classes/rest.php | 159 +++
repository/skydrive/db/caches.php | 14 +-
repository/skydrive/db/install.xml | 22 +
repository/skydrive/db/tasks.php | 43 +
repository/skydrive/db/upgrade.php | 54 +
.../skydrive/lang/en/repository_skydrive.php | 22 +-
repository/skydrive/lib.php | 987 ++++++++++++++++--
repository/skydrive/microsoftliveapi.php | 245 -----
repository/skydrive/version.php | 2 +-
11 files changed, 1328 insertions(+), 355 deletions(-)
create mode 100644 repository/skydrive/classes/access.php
create mode 100644 repository/skydrive/classes/remove_temp_access_task.php
create mode 100644 repository/skydrive/classes/rest.php
create mode 100644 repository/skydrive/db/install.xml
create mode 100644 repository/skydrive/db/tasks.php
create mode 100644 repository/skydrive/db/upgrade.php
delete mode 100644 repository/skydrive/microsoftliveapi.php
diff --git a/repository/skydrive/classes/access.php b/repository/skydrive/classes/access.php
new file mode 100644
index 00000000000..8c3fd90edc6
--- /dev/null
+++ b/repository/skydrive/classes/access.php
@@ -0,0 +1,56 @@
+.
+
+/**
+ * Class for loading/storing access records from the DB.
+ *
+ * @package core
+ * @copyright 2017 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+namespace repository_skydrive;
+
+defined('MOODLE_INTERNAL') || die();
+
+use core\persistent;
+
+/**
+ * Class for loading/storing issuer from the DB
+ *
+ * @copyright 2017 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class access extends persistent {
+
+ const TABLE = 'repository_skydrive_access';
+
+ /**
+ * Return the definition of the properties of this model.
+ *
+ * @return array
+ */
+ protected static function define_properties() {
+ return array(
+ 'permissionid' => array(
+ 'type' => PARAM_RAW
+ ),
+ 'itemid' => array(
+ 'type' => PARAM_RAW
+ )
+ );
+ }
+
+}
diff --git a/repository/skydrive/classes/remove_temp_access_task.php b/repository/skydrive/classes/remove_temp_access_task.php
new file mode 100644
index 00000000000..98247ec93db
--- /dev/null
+++ b/repository/skydrive/classes/remove_temp_access_task.php
@@ -0,0 +1,79 @@
+.
+
+/**
+ * A scheduled task.
+ *
+ * @package repository_skydrive
+ * @copyright 2017 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace repository_skydrive;
+
+use \core\task\scheduled_task;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Simple task to delete temporary permission records.
+ * @package core
+ * @copyright 2017 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class remove_temp_access_task extends scheduled_task {
+
+ /**
+ * Get a descriptive name for this task (shown to admins).
+ *
+ * @return string
+ */
+ public function get_name() {
+ return get_string('removetempaccesstask', 'repository_skydrive');
+ }
+
+ /**
+ * Do the job.
+ * Throw exceptions on errors (the job will be retried).
+ */
+ public function execute() {
+ $accessrecords = access::get_records();
+ $expires = new DateTime();
+ $expires->sub(new DateInterval("P7D"));
+ $timestamp = $expires->getTimestamp();
+
+ $issuerid = get_config('repository_skydrive', 'issuerid');
+ $issuer = \core\oauth2\api::get_issuer_by_id($issuerid);
+
+ // Add the current user as an OAuth writer.
+ $systemauth = \core\oauth2\api::get_system_oauth_client($issuer);
+
+ if ($systemauth === false) {
+ $details = 'Cannot connect as system user';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ $systemservice = new repository_skydrive\rest($systemauth);
+
+ foreach ($accessrecords as $access) {
+ if ($access->get('timemodified') < $timestamp) {
+ $params = ['permissionid' => $access->get('permissionid'), 'itemid' => $access->get('itemid')];
+ $systemservice->call('delete_permission', $params);
+ $access->delete();
+ }
+ }
+ }
+
+}
diff --git a/repository/skydrive/classes/rest.php b/repository/skydrive/classes/rest.php
new file mode 100644
index 00000000000..5a35baa0a33
--- /dev/null
+++ b/repository/skydrive/classes/rest.php
@@ -0,0 +1,159 @@
+.
+
+/**
+ * Microsoft Graph API Rest Interface.
+ *
+ * @package repository_skydrive
+ * @copyright 2017 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+namespace repository_skydrive;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Microsoft Graph API Rest Interface.
+ *
+ * @copyright 2017 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class rest extends \core\oauth2\rest {
+
+ /**
+ * Define the functions of the rest API.
+ *
+ * @return array Example:
+ * [ 'listFiles' => [ 'method' => 'get', 'endpoint' => 'http://...', 'args' => [ 'folder' => PARAM_STRING ] ] ]
+ */
+ public function get_api_functions() {
+ return [
+ 'list' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/{parent}/children',
+ 'method' => 'get',
+ 'args' => [
+ '$select' => PARAM_RAW,
+ '$expand' => PARAM_RAW,
+ 'parent' => PARAM_RAW,
+ '$skip' => PARAM_INT,
+ '$skipToken' => PARAM_RAW,
+ '$count' => PARAM_INT
+ ],
+ 'response' => 'json'
+ ],
+ 'search' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/{parent}/search(q=\'{search}\')',
+ 'method' => 'get',
+ 'args' => [
+ 'search' => PARAM_NOTAGS,
+ '$select' => PARAM_RAW,
+ 'parent' => PARAM_RAW,
+ '$skip' => PARAM_INT,
+ '$skipToken' => PARAM_RAW,
+ '$count' => PARAM_INT
+ ],
+ 'response' => 'json'
+ ],
+ 'get' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/items/{fileid}',
+ 'method' => 'get',
+ 'args' => [
+ 'fileid' => PARAM_RAW,
+ '$select' => PARAM_RAW,
+ '$expand' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ 'list_permissions' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/items/{fileid}/permissions',
+ 'method' => 'get',
+ 'args' => [
+ '$select' => PARAM_RAW,
+ '$expand' => PARAM_RAW,
+ 'fileid' => PARAM_RAW,
+ '$skip' => PARAM_INT,
+ '$skipToken' => PARAM_RAW,
+ '$count' => PARAM_INT
+ ],
+ 'response' => 'json'
+ ],
+ 'create_permission' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/items/{fileid}/invite',
+ 'method' => 'post',
+ 'args' => [
+ 'fileid' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ 'get_file_by_path' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/root:/{fullpath}',
+ 'method' => 'get',
+ 'args' => [
+ 'fullpath' => PARAM_RAW,
+ '$select' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ 'create_folder' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/items/{parentid}/children',
+ 'method' => 'post',
+ 'args' => [
+ 'parentid' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ 'create_link' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/items/{fileid}/createLink',
+ 'method' => 'post',
+ 'args' => [
+ 'fileid' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ 'get_drive' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive',
+ 'method' => 'get',
+ 'args' => [],
+ 'response' => 'json'
+ ],
+ 'delete_file_by_path' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/root:/{fullpath}',
+ 'method' => 'delete',
+ 'args' => [
+ 'fullpath' => PARAM_RAW,
+ ],
+ 'response' => 'json'
+ ],
+ 'copy_share' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/shares/{sharetoken}/root/copy',
+ 'method' => 'post',
+ 'args' => [
+ 'sharetoken' => PARAM_RAW,
+ ],
+ 'response' => 'json'
+ ],
+ 'delete_permission' => [
+ 'endpoint' => 'https://graph.microsoft.com/v1.0/me/drive/items/{fileid}/permissions/{permissionid}',
+ 'method' => 'delete',
+ 'args' => [
+ 'fileid' => PARAM_RAW,
+ 'permissionid' => PARAM_RAW
+ ],
+ 'response' => 'json'
+ ],
+ ];
+ }
+}
diff --git a/repository/skydrive/db/caches.php b/repository/skydrive/db/caches.php
index 8b61e339ba6..1050c238de2 100644
--- a/repository/skydrive/db/caches.php
+++ b/repository/skydrive/db/caches.php
@@ -25,7 +25,15 @@
defined('MOODLE_INTERNAL') || die();
$definitions = array(
- 'foldername' => array(
- 'mode' => cache_store::MODE_SESSION,
- )
+ // Used to store file ids for folders.
+ // The keys used are full path to the folder, the values are the id in google drive.
+ // The static acceleration size has been based upon the depths of a single path.
+ 'folder' => array(
+ 'mode' => cache_store::MODE_APPLICATION,
+ 'simplekeys' => false,
+ 'simpledata' => true,
+ 'staticacceleration' => true,
+ 'staticaccelerationsize' => 10,
+ 'canuselocalstore' => true
+ ),
);
diff --git a/repository/skydrive/db/install.xml b/repository/skydrive/db/install.xml
new file mode 100644
index 00000000000..f61ae0e88df
--- /dev/null
+++ b/repository/skydrive/db/install.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/repository/skydrive/db/tasks.php b/repository/skydrive/db/tasks.php
new file mode 100644
index 00000000000..b55c4ea3bb6
--- /dev/null
+++ b/repository/skydrive/db/tasks.php
@@ -0,0 +1,43 @@
+.
+
+/**
+ * Definition of repository_skydrive scheduled tasks.
+ *
+ * The handlers defined on this file are processed and registered into
+ * the Moodle DB after any install or upgrade operation. All plugins
+ * support this.
+ *
+ * @package repository_skydrive
+ * @copyright 2017 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+/* List of handlers */
+
+$tasks = array(
+ array(
+ 'classname' => 'repository_skydrive\remove_temp_access_task',
+ 'blocking' => 0,
+ 'minute' => 'R',
+ 'hour' => 'R',
+ 'day' => '*',
+ 'dayofweek' => 'R',
+ 'month' => '*'
+ ),
+);
diff --git a/repository/skydrive/db/upgrade.php b/repository/skydrive/db/upgrade.php
new file mode 100644
index 00000000000..7a714846fcd
--- /dev/null
+++ b/repository/skydrive/db/upgrade.php
@@ -0,0 +1,54 @@
+.
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * @param int $oldversion the version we are upgrading from
+ * @return bool result
+ */
+function xmldb_repository_skydrive_upgrade($oldversion) {
+ global $DB;
+
+ $dbman = $DB->get_manager();
+
+ if ($oldversion < 2017031400) {
+
+ // Define table repository_skydrive_access to be created.
+ $table = new xmldb_table('repository_skydrive_access');
+
+ // Adding fields to table repository_skydrive_access.
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
+ $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
+ $table->add_field('usermodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
+ $table->add_field('permissionid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
+ $table->add_field('itemid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
+
+ // Adding keys to table repository_skydrive_access.
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->add_key('usermodifiedkey', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
+
+ // Conditionally launch create table for repository_skydrive_access.
+ if (!$dbman->table_exists($table)) {
+ $dbman->create_table($table);
+ }
+
+ // Skydrive savepoint reached.
+ upgrade_plugin_savepoint(true, 2017031400, 'repository', 'skydrive');
+ }
+ return true;
+}
diff --git a/repository/skydrive/lang/en/repository_skydrive.php b/repository/skydrive/lang/en/repository_skydrive.php
index 1ed71f48fc5..015647fa9d1 100644
--- a/repository/skydrive/lang/en/repository_skydrive.php
+++ b/repository/skydrive/lang/en/repository_skydrive.php
@@ -22,10 +22,20 @@
* @author Dan Poltawski
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-$string['cachedef_foldername'] = 'Folder name cache';
-$string['clientid'] = 'Client ID';
-$string['configplugin'] = 'Configure Microsoft OneDrive';
-$string['oauthinfo'] = '
To use this plugin, you must register your site with Microsoft.
As part of the registration process, you will need to enter the following URL as \'Redirect domain\':
{$a->callbackurl}
Once registered, you will be provided with a client ID and secret which can be entered here.
';
+$string['configplugin'] = 'Configure OneDrive plugin';
+$string['skydrive:view'] = 'View OneDrive repository';
$string['pluginname'] = 'Microsoft OneDrive';
-$string['secret'] = 'Secret';
-$string['skydrive:view'] = 'View OneDrive';
+$string['issuer'] = 'OAuth 2 service';
+$string['issuer_help'] = 'Select the OAuth 2 service that is configured to talk to the OneDrive API. If the services does not exist yet, you might need to create it.';
+$string['servicenotenabled'] = 'Access not configured.';
+$string['oauth2serviceslink'] = 'OAuth 2 Services Configuration';
+$string['searchfor'] = 'Search for {$a}';
+$string['internal'] = 'Internal (files stored in Moodle)';
+$string['external'] = 'External (only links stored in Moodle)';
+$string['both'] = 'Internal and External';
+$string['supportedreturntypes'] = 'Supported files';
+$string['defaultreturntype'] = 'Default return type';
+$string['fileoptions'] = 'The types and defaults for returned files is configurable here. Note that all files linked externally will be updated so that the owner is the Moodle system account.';
+$string['owner'] = 'Owned by: {$a}';
+$string['cachedef_folder'] = 'OneDrive File IDs for folders in the system account';
+
diff --git a/repository/skydrive/lib.php b/repository/skydrive/lib.php
index 69c6316454d..41c87dc8f8e 100644
--- a/repository/skydrive/lib.php
+++ b/repository/skydrive/lib.php
@@ -25,8 +25,6 @@
defined('MOODLE_INTERNAL') || die();
-require_once('microsoftliveapi.php');
-
/**
* Microsoft skydrive repository plugin.
*
@@ -36,46 +34,80 @@ require_once('microsoftliveapi.php');
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class repository_skydrive extends repository {
- /** @var microsoft_skydrive skydrive oauth2 api helper object */
- private $skydrive = null;
+ /**
+ * OAuth 2 client
+ * @var \core\oauth2\client
+ */
+ private $client = null;
/**
- * Constructor
+ * OAuth 2 Issuer
+ * @var \core\oauth2\issuer
+ */
+ private $issuer = null;
+
+ /**
+ * Additional scopes required for drive.
+ */
+ const SCOPES = 'files.readwrite.all';
+
+ /**
+ * Constructor.
*
* @param int $repositoryid repository instance id.
* @param int|stdClass $context a context id or context object.
* @param array $options repository options.
+ * @param int $readonly indicate this repo is readonly or not.
+ * @return void
*/
- public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array()) {
- parent::__construct($repositoryid, $context, $options);
+ public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
+ parent::__construct($repositoryid, $context, $options, $readonly = 0);
- $clientid = get_config('skydrive', 'clientid');
- $secret = get_config('skydrive', 'secret');
- $returnurl = new moodle_url('/repository/repository_callback.php');
- $returnurl->param('callback', 'yes');
- $returnurl->param('repo_id', $this->id);
- $returnurl->param('sesskey', sesskey());
-
- $this->skydrive = new microsoft_skydrive($clientid, $secret, $returnurl);
- $this->check_login();
+ $this->issuer = \core\oauth2\api::get_issuer(get_config('skydrive', 'issuerid'));
}
/**
- * Checks whether the user is logged in or not.
+ * Get a cached user authenticated oauth client.
*
- * @return bool true when logged in
+ * @param moodle_url $overrideurl - Use this url instead of the repo callback.
+ * @return \core\oauth2\client
+ */
+ protected function get_user_oauth_client($overrideurl = false) {
+ if ($this->client) {
+ return $this->client;
+ }
+ if ($overrideurl) {
+ $returnurl = $overrideurl;
+ } else {
+ $returnurl = new moodle_url('/repository/repository_callback.php');
+ $returnurl->param('callback', 'yes');
+ $returnurl->param('repo_id', $this->id);
+ $returnurl->param('sesskey', sesskey());
+ }
+
+ $this->client = \core\oauth2\api::get_user_oauth_client($this->issuer, $returnurl, self::SCOPES);
+
+ return $this->client;
+ }
+
+ /**
+ * Checks whether the user is authenticate or not.
+ *
+ * @return bool true when logged in.
*/
public function check_login() {
- return $this->skydrive->is_logged_in();
+ $client = $this->get_user_oauth_client();
+ return $client->is_logged_in();
}
/**
- * Print the login form, if required
+ * Print or return the login form.
*
- * @return array of login options
+ * @return void|array for ajax.
*/
public function print_login() {
- $url = $this->skydrive->get_login_url();
+ $client = $this->get_user_oauth_client();
+ $url = $client->get_login_url();
if ($this->options['ajax']) {
$popup = new stdClass();
@@ -88,124 +120,879 @@ class repository_skydrive extends repository {
}
/**
- * Given a path, and perhaps a search, get a list of files.
+ * Build the breadcrumb from a path.
*
- * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
+ * @param string $path to create a breadcrumb from.
+ * @return array containing name and path of each crumb.
+ */
+ protected function build_breadcrumb($path) {
+ $bread = explode('/', $path);
+ $crumbtrail = '';
+ foreach ($bread as $crumb) {
+ list($id, $name) = $this->explode_node_path($crumb);
+ $name = empty($name) ? $id : $name;
+ $breadcrumb[] = array(
+ 'name' => $name,
+ 'path' => $this->build_node_path($id, $name, $crumbtrail)
+ );
+ $tmp = end($breadcrumb);
+ $crumbtrail = $tmp['path'];
+ }
+ return $breadcrumb;
+ }
+
+ /**
+ * Generates a safe path to a node.
*
- * @param string $path identifier for current path
- * @param string $page the page number of file list
- * @return array list of files including meta information as specified by parent.
+ * Typically, a node will be id|Name of the node.
+ *
+ * @param string $id of the node.
+ * @param string $name of the node, will be URL encoded.
+ * @param string $root to append the node on, must be a result of this function.
+ * @return string path to the node.
+ */
+ protected function build_node_path($id, $name = '', $root = '') {
+ $path = $id;
+ if (!empty($name)) {
+ $path .= '|' . urlencode($name);
+ }
+ if (!empty($root)) {
+ $path = trim($root, '/') . '/' . $path;
+ }
+ return $path;
+ }
+
+ /**
+ * Returns information about a node in a path.
+ *
+ * @see self::build_node_path()
+ * @param string $node to extrat information from.
+ * @return array about the node.
+ */
+ protected function explode_node_path($node) {
+ if (strpos($node, '|') !== false) {
+ list($id, $name) = explode('|', $node, 2);
+ $name = urldecode($name);
+ } else {
+ $id = $node;
+ $name = '';
+ }
+ $id = urldecode($id);
+ return array(
+ 0 => $id,
+ 1 => $name,
+ 'id' => $id,
+ 'name' => $name
+ );
+ }
+
+ /**
+ * List the files and folders.
+ *
+ * @param string $path path to browse.
+ * @param string $page page to browse.
+ * @return array of result.
*/
public function get_listing($path='', $page = '') {
- $ret = array();
- $ret['dynload'] = true;
- $ret['nosearch'] = true;
- $ret['manage'] = 'https://skydrive.live.com/';
-
- $fileslist = $this->skydrive->get_file_list($path);
- // Filter list for accepted types. Hopefully this will be done by core some day.
- $fileslist = array_filter($fileslist, array($this, 'filter'));
- $ret['list'] = $fileslist;
-
- // Generate path bar, always start with the plugin name.
- $ret['path'] = array();
- $ret['path'][] = array('name'=> $this->name, 'path'=>'');
-
- // Now add each level folder.
- $trail = '';
- if (!empty($path)) {
- $parts = explode('/', $path);
- foreach ($parts as $folderid) {
- if (!empty($folderid)) {
- $trail .= ('/'.$folderid);
- $ret['path'][] = array('name' => $this->skydrive->get_folder_name($folderid),
- 'path' => $trail);
- }
- }
+ if (empty($path)) {
+ $path = $this->build_node_path('root', get_string('pluginname', 'repository_skydrive'));
}
+ // We analyse the path to extract what to browse.
+ $trail = explode('/', $path);
+ $uri = array_pop($trail);
+ list($id, $name) = $this->explode_node_path($uri);
+
+ // Handle the special keyword 'search', which we defined in self::search() so that
+ // we could set up a breadcrumb in the search results. In any other case ID would be
+ // 'root' which is a special keyword, or a parent (folder) ID.
+ if ($id === 'search') {
+ $q = $name;
+ $id = 'root';
+
+ // Append the active path for search.
+ $str = get_string('searchfor', 'repository_skydrive', $searchtext);
+ $path = $this->build_node_path('search', $str, $path);
+ }
+
+ // Query the Drive.
+ $parent = $id;
+ if ($parent != 'root') {
+ $parent = 'items/' . $parent;
+ }
+ $q = '';
+ $results = $this->query($q, $path, $parent);
+
+ $ret = [];
+ $ret['dynload'] = true;
+ $ret['path'] = $this->build_breadcrumb($path);
+ $ret['list'] = $results;
+ $ret['manage'] = 'https://www.office.com/';
return $ret;
}
/**
- * Downloads a repository file and saves to a path.
+ * Search throughout the Google Drive.
*
- * @param string $id identifier of file
- * @param string $filename to save file as
- * @return array with keys:
- * path: internal location of the file
- * url: URL to the source
+ * @param string $searchtext text to search for.
+ * @param int $page search page.
+ * @return array of results.
*/
- public function get_file($id, $filename = '') {
- $path = $this->prepare_file($filename);
- return $this->skydrive->download_file($id, $path);
+ public function search($searchtext, $page = 0) {
+ $path = $this->build_node_path('root', get_string('pluginname', 'repository_skydrive'));
+ $str = get_string('searchfor', 'repository_skydrive', $searchtext);
+ $path = $this->build_node_path('search', $str, $path);
+
+ // Query the Drive.
+ $parent = 'root';
+ $results = $this->query($searchtext, $path, 'root');
+
+ $ret = [];
+ $ret['dynload'] = true;
+ $ret['path'] = $this->build_breadcrumb($path);
+ $ret['list'] = $results;
+ $ret['manage'] = 'https://www.office.com/';
+ return $ret;
}
/**
- * Return names of the options to display in the repository form
+ * Query Google Drive for files and folders using a search query.
*
- * @return array of option names
+ * Documentation about the query format can be found here:
+ * https://developers.google.com/drive/search-parameters
+ *
+ * This returns a list of files and folders with their details as they should be
+ * formatted and returned by functions such as get_listing() or search().
+ *
+ * @param string $q search query as expected by the Google API.
+ * @param string $path parent path of the current files, will not be used for the query.
+ * @param int $page page.
+ * @return array of files and folders.
*/
- public static function get_type_option_names() {
- return array('clientid', 'secret', 'pluginname');
+ protected function query($q, $path = null, $parent = null, $page = 0) {
+ global $OUTPUT;
+
+ $files = [];
+ $folders = [];
+ $fields = "folder,id,lastModifiedDateTime,name,size,webUrl,thumbnails";
+ $params = ['$select' => $fields, '$expand' => 'thumbnails', 'parent' => $parent];
+
+ try {
+ // Retrieving files and folders.
+ $client = $this->get_user_oauth_client();
+ $service = new repository_skydrive\rest($client);
+
+ if (!empty($q)) {
+ $params['search'] = urlencode($q);
+
+ // MS does not return thumbnails on a search.
+ unset($params['$expand']);
+ $response = $service->call('search', $params);
+ } else {
+ $response = $service->call('list', $params);
+ }
+ } catch (Exception $e) {
+ if ($e->getCode() == 403 && strpos($e->getMessage(), 'Access Not Configured') !== false) {
+ throw new repository_exception('servicenotenabled', 'repository_skydrive');
+ } else {
+ throw $e;
+ }
+ }
+
+ $remotefiles = isset($response->value) ? $response->value : [];
+ foreach ($remotefiles as $remotefile) {
+ if (!empty($remotefile->folder)) {
+ // This is a folder.
+ $folders[$remotefile->id] = [
+ 'title' => $remotefile->name,
+ 'path' => $this->build_node_path($remotefile->id, $remotefile->name, $path),
+ 'date' => strtotime($remotefile->lastModifiedDateTime),
+ 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(64))->out(false),
+ 'thumbnail_height' => 64,
+ 'thumbnail_width' => 64,
+ 'children' => []
+ ];
+ } else {
+ // We can download all other file types.
+ $title = $remotefile->name;
+ $source = json_encode([
+ 'id' => $remotefile->id,
+ 'name' => $remotefile->name,
+ 'link' => $remotefile->webUrl
+ ]);
+
+ // Adds the file to the file list. Using the itemId along with the name as key
+ // of the array because Google Drive allows files with identical names.
+ $thumb = '';
+ $thumbwidth = 0;
+ $thumbheight = 0;
+ $extendedinfoerr = false;
+
+ if (empty($remotefile->thumbnails)) {
+ // Try and get it directly from the item.
+ $params = ['fileid' => $remotefile->id, '$select' => $fields, '$expand' => 'thumbnails'];
+ try {
+ $response = $service->call('get', $params);
+ $remotefile = $response;
+ } catch (Exception $e) {
+ // This is not a failure condition - we just could not get extended info about the file.
+ $extendedinfoerr = true;
+ }
+ }
+
+ if (!empty($remotefile->thumbnails)) {
+ $thumbs = $remotefile->thumbnails;
+ if (count($thumbs)) {
+ $first = reset($thumbs);
+ if (!empty($first->medium) && !empty($first->medium->url)) {
+ $thumb = $first->medium->url;
+ $thumbwidth = min($first->medium->width, 64);
+ $thumbheight = min($first->medium->height, 64);
+ }
+ }
+ }
+
+ $files[$remotefile->id] = [
+ 'title' => $title,
+ 'source' => $source,
+ 'date' => strtotime($remotefile->lastModifiedDateTime),
+ 'size' => isset($remotefile->size) ? $remotefile->size : null,
+ 'thumbnail' => $thumb,
+ 'thumbnail_height' => $thumbwidth,
+ 'thumbnail_width' => $thumbheight,
+ ];
+ }
+ }
+
+ // Filter and order the results.
+ $files = array_filter($files, [$this, 'filter']);
+ core_collator::ksort($files, core_collator::SORT_NATURAL);
+ core_collator::ksort($folders, core_collator::SORT_NATURAL);
+ return array_merge(array_values($folders), array_values($files));
}
/**
- * Setup repistory form.
+ * Logout.
*
- * @param moodleform $mform Moodle form (passed by reference)
- * @param string $classname repository class name
- */
- public static function type_config_form($mform, $classname = 'repository') {
- $a = new stdClass;
- $a->callbackurl = microsoft_skydrive::callback_url()->out(false);
- $mform->addElement('static', null, '', get_string('oauthinfo', 'repository_skydrive', $a));
-
- parent::type_config_form($mform);
- $strrequired = get_string('required');
- $mform->addElement('text', 'clientid', get_string('clientid', 'repository_skydrive'));
- $mform->addElement('text', 'secret', get_string('secret', 'repository_skydrive'));
- $mform->addRule('clientid', $strrequired, 'required', null, 'client');
- $mform->addRule('secret', $strrequired, 'required', null, 'client');
- $mform->setType('clientid', PARAM_RAW_TRIMMED);
- $mform->setType('secret', PARAM_RAW_TRIMMED);
- }
-
- /**
- * Logout from repository instance and return
- * login form.
- *
- * @return page to display
+ * @return string
*/
public function logout() {
- $this->skydrive->log_out();
- return $this->print_login();
+ $client = $this->get_user_oauth_client();
+ $client->log_out();
+ return parent::logout();
}
/**
- * This repository doesn't support global search.
+ * Get a file.
*
- * @return bool if supports global search
+ * @param string $reference reference of the file.
+ * @param string $file name to save the file to.
+ * @return string JSON encoded array of information about the file.
*/
- public function global_search() {
- return false;
+ public function get_file($reference, $filename = '') {
+ global $CFG;
+
+ $client = $this->get_user_oauth_client();
+ $base = 'https://graph.microsoft.com/v1.0/';
+
+ $sourceinfo = json_decode($reference);
+ $sourceurl = new moodle_url($base . 'me/drive/items/' . $sourceinfo->id . '/content');
+ $source = $sourceurl->out(false);
+
+ // We use download_one and not the rest API because it has special timeouts etc.
+ $path = $this->prepare_file($filename);
+ $options = ['filepath' => $path, 'timeout' => 15, 'followlocation' => true, 'maxredirs' => 5];
+ $result = $client->download_one($source, null, $options);
+
+ if ($result) {
+ @chmod($path, $CFG->filepermissions);
+ return array(
+ 'path' => $path,
+ 'url' => $reference
+ );
+ }
+ throw new repository_exception('cannotdownload', 'repository');
}
/**
- * This repoistory supports any filetype.
+ * Prepare file reference information.
*
- * @return string '*' means this repository support any files
+ * We are using this method to clean up the source to make sure that it
+ * is a valid source.
+ *
+ * @param string $source of the file.
+ * @return string file reference.
+ */
+ public function get_file_reference($source) {
+ // We could do some magic upgrade code here.
+ return $source;
+ }
+
+ /**
+ * What kind of files will be in this repository?
+ *
+ * @return array return '*' means this repository support any files, otherwise
+ * return mimetypes of files, it can be an array
*/
public function supported_filetypes() {
return '*';
}
/**
- * This repostiory only supports internal files
+ * Tells how the file can be picked from this repository.
*
- * @return int return type bitmask supported
+ * @return int
*/
public function supported_returntypes() {
- return FILE_INTERNAL;
+ // We can only support references if the system account is connected.
+ if (!empty($this->issuer) && $this->issuer->is_system_account_connected()) {
+ $setting = get_config('skydrive', 'supportedreturntypes');
+ if ($setting == 'internal') {
+ return FILE_INTERNAL;
+ } else if ($setting == 'external') {
+ return FILE_CONTROLLED_LINK;
+ } else {
+ return FILE_CONTROLLED_LINK | FILE_INTERNAL;
+ }
+ } else {
+ return FILE_INTERNAL;
+ }
+ }
+
+ /**
+ * Which return type should be selected by default.
+ *
+ * @return int
+ */
+ public function default_returntype() {
+ $setting = get_config('skydrive', 'defaultreturntype');
+ $supported = get_config('skydrive', 'supportedreturntypes');
+ if (($setting == FILE_INTERNAL && $supported != 'external') || $supported == 'internal') {
+ return FILE_INTERNAL;
+ } else {
+ return FILE_CONTROLLED_LINK;
+ }
+ }
+
+ /**
+ * Return names of the general options.
+ * By default: no general option name.
+ *
+ * @return array
+ */
+ public static function get_type_option_names() {
+ return array('issuerid', 'pluginname', 'defaultreturntype', 'supportedreturntypes');
+ }
+
+ /**
+ * Store the access token.
+ */
+ public function callback() {
+ $client = $this->get_user_oauth_client();
+ // This will upgrade to an access token if we have an authorization code and save the access token in the session.
+ $client->is_logged_in();
+ }
+
+ /**
+ * Repository method to serve the referenced file
+ *
+ * @see send_stored_file
+ *
+ * @param stored_file $storedfile the file that contains the reference
+ * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
+ * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
+ * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
+ * @param array $options additional options affecting the file serving
+ */
+ public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
+ $source = json_decode($storedfile->get_reference());
+
+ $fb = get_file_browser();
+ $context = context::instance_by_id($storedfile->get_contextid(), MUST_EXIST);
+ $info = $fb->get_file_info($context,
+ $storedfile->get_component(),
+ $storedfile->get_filearea(),
+ $storedfile->get_itemid(),
+ $storedfile->get_filepath(),
+ $storedfile->get_filename());
+
+ if ($info->is_writable()) {
+ // Add the current user as an OAuth writer.
+ $systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
+
+ if ($systemauth === false) {
+ $details = 'Cannot connect as system user';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ $systemservice = new repository_skydrive\rest($systemauth);
+
+ // Get the user oauth so we can get the account to add.
+ $url = moodle_url::make_pluginfile_url($storedfile->get_contextid(),
+ $storedfile->get_component(),
+ $storedfile->get_filearea(),
+ $storedfile->get_itemid(),
+ $storedfile->get_filepath(),
+ $storedfile->get_filename(),
+ $forcedownload);
+ $url->param('sesskey', sesskey());
+ $userauth = $this->get_user_oauth_client($url);
+ if (!$userauth->is_logged_in()) {
+ redirect($userauth->get_login_url());
+ }
+ if ($userauth === false) {
+ $details = 'Cannot connect as current user';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ $userinfo = $userauth->get_userinfo();
+ $useremail = $userinfo['email'];
+
+ $this->add_temp_writer_to_file($systemservice, $source->id, $useremail);
+ }
+
+ if ($source->link) {
+ redirect($source->link);
+ } else {
+ $details = 'File is missing source link';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ }
+
+ /**
+ * List the permissions on a file.
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $fileid The id of the file.
+ * @return array
+ */
+ protected function list_file_permissions(\repository_skydrive\rest $client, $fileid) {
+ $fields = "id,roles,link,grantedTo";
+ return $client->call('list_permissions', ['fileid' => $fileid, '$select' => $fields]);
+ }
+
+ /**
+ * See if a folder exists within a folder
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $fullpath
+ * @return string|boolean The file id if it exists or false.
+ */
+ protected function get_file_id_by_path(\repository_skydrive\rest $client, $fullpath) {
+ $fields = "id";
+ try {
+ $response = $client->call('get_file_by_path', ['fullpath' => $fullpath, '$select' => $fields]);
+ } catch (\core\oauth2\rest_exception $re) {
+ return false;
+ }
+ return $response->id;
+ }
+
+ /**
+ * Delete a file by full path.
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $fullpath
+ * @return boolean
+ */
+ protected function delete_file_by_path(\repository_skydrive\rest $client, $fullpath) {
+ try {
+ $response = $client->call('delete_file_by_path', ['fullpath' => $fullpath]);
+ } catch (\core\oauth2\rest_exception $re) {
+ return false;
+ }
+ return true;
+ }
+
+
+ /**
+ * Get a file summary by full path.
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $fullpath
+ * @return stdClass
+ */
+ protected function get_file_summary_by_path(\repository_skydrive\rest $client, $fullpath) {
+ $fields = "folder,id,lastModifiedDateTime,name,size,webUrl,createdByUser";
+ $response = $client->call('get_file_by_path', ['fullpath' => $fullpath, '$select' => $fields]);
+ if (empty($response->id)) {
+ $details = 'Cannot get file summary:' . $fullpath;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return $response;
+ }
+
+ /**
+ * Create a folder within a folder
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $foldername The folder we are creating.
+ * @param string $parentid The parent folder we are creating in.
+ *
+ * @return string The file id of the new folder.
+ */
+ protected function create_folder_in_folder(\repository_skydrive\rest $client, $foldername, $parentid) {
+ $params = ['parentid' => $parentid];
+ $folder = [ 'name' => $foldername, 'folder' => [ 'childCount' => 0 ]];
+ $created = $client->call('create_folder', $params, json_encode($folder));
+ if (empty($created->id)) {
+ $details = 'Cannot create folder:' . $foldername;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return $created->id;
+ }
+
+ /**
+ * Get simple file info for humans.
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $fileid The file we are querying.
+ *
+ * @return stdClass
+ */
+ protected function get_file_summary(\repository_skydrive\rest $client, $fileid) {
+ $fields = "folder,id,lastModifiedDateTime,name,size,webUrl,createdByUser";
+ $response = $client->call('get', ['fileid' => $fileid, '$select' => $fields]);
+ return $response;
+ }
+
+ /**
+ * Get the id of this users root drive.
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ *
+ * @return string id
+ */
+ protected function get_root_drive_id(\repository_skydrive\rest $client) {
+ $response = $client->call('get_drive', []);
+
+ if (empty($response->id)) {
+ $details = 'Cannot get driveid';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return $response->id;
+ }
+
+ /**
+ * Add a writer to the permissions on the file (temporary).
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $fileid The file we are updating.
+ * @param string $email The email of the writer account to add.
+ * @return boolean
+ */
+ protected function add_temp_writer_to_file(\repository_skydrive\rest $client, $fileid, $email) {
+ // Expires in 7 days.
+ $expires = new DateTime();
+ $expires->add(new DateInterval("P7D"));
+
+ $updateeditor = [
+ 'recipients' => [[ 'email' => $email ]],
+ 'roles' => ['write'],
+ 'requireSignIn' => true,
+ 'sendInvitation' => false
+ ];
+ $params = ['fileid' => $fileid];
+ $response = $client->call('create_permission', $params, json_encode($updateeditor));
+ if (empty($response->value[0]->id)) {
+ $details = 'Cannot add user ' . $email . ' as a writer for document: ' . $fileid;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ // Store the permission id in the DB. Scheduled task will remove this permission after 7 days.
+ if ($access = repository_skydrive\access::get_record(['permissionid' => $response->value[0]->id, 'itemid' => $fileid ])) {
+ // Update the timemodified.
+ $access->update();
+ } else {
+ $record = (object) [ 'permissionid' => $response->value[0]->id, 'itemid' => $fileid ];
+ $access = new repository_skydrive\access(0, $record);
+ $access->create();
+ }
+ return true;
+ }
+
+ /**
+ * Add a writer to the permissions on the file.
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $fileid The file we are updating.
+ * @param string $userid The userid of the writer account to add.
+ * @return boolean
+ */
+ protected function add_writer_to_file(\repository_skydrive\rest $client, $fileid, $useremail) {
+ $updateeditor = [
+ 'recipients' => [ [ 'email' => $useremail ] ],
+ 'roles' => ['write'],
+ 'requireSignIn' => true,
+ 'sendInvitation' => false
+ ];
+ $params = [ 'fileid' => $fileid ];
+ $response = $client->call('create_permission', $params, json_encode($updateeditor));
+ if (empty($response->value)) {
+ $details = 'Cannot add user ' . $useremail . ' as a writer for document: ' . $fileid;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return true;
+ }
+
+ /**
+ * Allow anyone with the link to read the file.
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $fileid The file we are updating.
+ * @return boolean
+ */
+ protected function set_file_sharing_anyone_with_link_can_read(\repository_skydrive\rest $client, $fileid) {
+ $updateread = [
+ 'type' => 'view',
+ 'scope' => 'anonymous'
+ ];
+ $params = ['fileid' => $fileid];
+ $response = $client->call('create_link', $params, json_encode($updateread));
+ if (empty($response->link)) {
+ $details = 'Cannot update link sharing for the document: ' . $fileid;
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ return true;
+ }
+
+ /**
+ * Get share info.
+ *
+ * @param \repository_skydrive\rest $client Authenticated client.
+ * @param string $sharetoken The share we are querying.
+ * @return stdClass
+ */
+ protected function copy_share(\repository_skydrive\rest $client, $sharetoken, $newdrive, $parentid) {
+ $folder = [
+ 'parentReference' => ['id' => $parentid, 'driveId' => $newdrive]
+ ];
+ $params = ['sharetoken' => $sharetoken];
+ $response = $client->call('copy_share', $params, json_encode($folder));
+ return true;
+ }
+
+ /**
+ * From MS docs - to get a share token from a url, do this:
+ * Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/shares_get
+ * To access a sharing URL using the shares API, the URL needs to be transformed into a sharing token.
+ * To transform a URL into a sharing token:
+ * Base64 encode the sharing URL.
+ * Convert the base64 encoded data to unpadded base64url format by:
+ * Trim trailing = characeters from the string.
+ * Replace unsafe URL characters with an equivelent character; replace / with _ and + with -.
+ * Append u! to the beginning of the string.
+ *
+ * @param string sharingUrl
+ * @return string sharingtoken
+ */
+ protected function get_share_token($shareurl) {
+ return 'u!' . str_replace(['/', '+'], ['_', '-'], rtrim(base64_encode($shareurl), '='));
+ }
+
+ /**
+ * Called when a file is selected as a "link".
+ * Invoked at MOODLE/repository/repository_ajax.php
+ *
+ * @param string $reference this reference is generated by
+ * repository::get_file_reference()
+ * @param context $context the target context for this new file.
+ * @param string $component the target component for this new file.
+ * @param string $filearea the target filearea for this new file.
+ * @param string $itemid the target itemid for this new file.
+ * @return string $modifiedreference (final one before saving to DB)
+ */
+ public function reference_file_selected($reference, $context, $component, $filearea, $itemid) {
+ // What we need to do here is transfer ownership to the system user (or copy)
+ // then set the permissions so anyone with the share link can view,
+ // finally update the reference to contain the share link if it was not
+ // already there (and point to new file id if we copied).
+ var_dump($reference);
+ $systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
+
+ if ($systemauth === false) {
+ $details = 'Cannot connect as system user';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ $systemuserinfo = $systemauth->get_userinfo();
+ $systemuseremail = $systemuserinfo['email'];
+
+ $source = json_decode($reference);
+
+ $userauth = $this->get_user_oauth_client();
+ if ($userauth === false) {
+ $details = 'Cannot connect as current user';
+ throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
+ }
+ $userinfo = $userauth->get_userinfo();
+ $useremail = $userinfo['email'];
+
+ $userservice = new repository_skydrive\rest($userauth);
+ $systemservice = new repository_skydrive\rest($systemauth);
+
+ // Get the list of existing permissions so we can see if the owner is already the system account,
+ // and whether we need to update the link sharing options.
+ $permissions = $this->list_file_permissions($userservice, $source->id);
+
+ $readshareupdaterequired = true;
+ $ownerupdaterequired = true;
+ foreach ($permissions->value as $permission) {
+ if (!empty($permission->link)) {
+ if ($permission->link->scope == 'anonymous' &&
+ $permission->link->type == 'view') {
+ $shareurl = $permission->link->webUrl;
+ $readshareupdaterequired = false;
+ break;
+ }
+ }
+ }
+
+ // Add Moodle as writer.
+ $this->add_writer_to_file($userservice, $source->id, $systemuseremail);
+
+ // Now copy it to a sensible folder.
+ $contextlist = array_reverse($context->get_parent_contexts(true));
+
+ $cache = cache::make('repository_skydrive', 'folder');
+ $parentid = 'root';
+ $fullpath = '';
+ $allfolders = [];
+ foreach ($contextlist as $context) {
+ // Make sure a folder exists here.
+ $foldername = urlencode(clean_param($context->get_context_name(), PARAM_PATH));
+ $allfolders[] = $foldername;
+ }
+
+ $allfolders[] = urlencode(clean_param($component, PARAM_PATH));
+ $allfolders[] = urlencode(clean_param($filearea, PARAM_PATH));
+ $allfolders[] = urlencode(clean_param($itemid, PARAM_PATH));
+
+ foreach ($allfolders as $foldername) {
+ if ($fullpath) {
+ $fullpath .= '/';
+ }
+ $fullpath .= $foldername;
+
+ $folderid = $cache->get($fullpath);
+ if (empty($folderid)) {
+ $folderid = $this->get_file_id_by_path($systemservice, $fullpath);
+ }
+ if ($folderid !== false) {
+ $cache->set($fullpath, $folderid);
+ $parentid = $folderid;
+ } else {
+ // Create it.
+ $parentid = $this->create_folder_in_folder($systemservice, $foldername, $parentid);
+ $cache->set($fullpath, $parentid);
+ }
+ }
+
+ // Get the users drive id.
+ $newdrive = $this->get_root_drive_id($systemservice);
+
+ if ($readshareupdaterequired) {
+ $response = $this->set_file_sharing_anyone_with_link_can_read($userservice, $source->id);
+ $shareurl = $response->value->webUrl;
+ }
+
+ // Turn the share url into a sharing token.
+ $sharetoken = $this->get_share_token($shareurl);
+
+ // Delete any existing file at this path.
+ $path = $fullpath . '/' . $source->name;
+ $this->delete_file_by_path($systemservice, $path);
+
+ // Copy the file so we have a backup.
+ $this->copy_share($systemservice, $sharetoken, $newdrive, $parentid);
+
+ $summary = $this->get_file_summary_by_path($systemservice, $path);
+
+ // Update the details in the file reference before it is saved.
+ $source->id = $summary->id;
+ $source->link = $summary->webUrl;
+
+ $reference = json_encode($source);
+
+ return $reference;
+ }
+
+ /**
+ * Get human readable file info from the reference.
+ *
+ * @param string $reference
+ * @param int $filestatus
+ */
+ public function get_reference_details($reference, $filestatus = 0) {
+ if (empty($reference)) {
+ return get_string('unknownsource', 'repository');
+ }
+ $source = json_decode($reference);
+ $systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
+
+ if ($systemauth === false) {
+ return '';
+ }
+ $systemservice = new repository_skydrive\rest($systemauth);
+ $info = $this->get_file_summary($systemservice, $source->id);
+
+ $owner = '';
+ if (!empty($info->createdByUser->displayName)) {
+ $owner = $info->createdByUser->displayName;
+ }
+ if ($owner) {
+ return get_string('owner', 'repository_skydrive', $owner);
+ } else {
+ return $info->name;
+ }
+ }
+
+ /**
+ * Edit/Create Admin Settings Moodle form.
+ *
+ * @param moodleform $mform Moodle form (passed by reference).
+ * @param string $classname repository class name.
+ */
+ public static function type_config_form($mform, $classname = 'repository') {
+ $url = new moodle_url('/admin/tool/oauth2/issuers.php');
+ $url = $url->out();
+
+ $mform->addElement('static', null, '', get_string('oauth2serviceslink', 'repository_skydrive', $url));
+
+ parent::type_config_form($mform);
+ $options = [];
+ $issuers = \core\oauth2\api::get_all_issuers();
+
+ foreach ($issuers as $issuer) {
+ $options[$issuer->get('id')] = s($issuer->get('name'));
+ }
+
+ $strrequired = get_string('required');
+
+ $mform->addElement('select', 'issuerid', get_string('issuer', 'repository_skydrive'), $options);
+ $mform->addHelpButton('issuerid', 'issuer', 'repository_skydrive');
+ $mform->addRule('issuerid', $strrequired, 'required', null, 'client');
+
+ $mform->addElement('static', null, '', get_string('fileoptions', 'repository_skydrive'));
+ $choices = [
+ 'internal' => get_string('internal', 'repository_skydrive'),
+ 'external' => get_string('external', 'repository_skydrive'),
+ 'both' => get_string('both', 'repository_skydrive')
+ ];
+ $mform->addElement('select', 'supportedreturntypes', get_string('supportedreturntypes', 'repository_skydrive'), $choices);
+
+ $choices = [
+ FILE_INTERNAL => get_string('internal', 'repository_skydrive'),
+ FILE_CONTROLLED_LINK => get_string('external', 'repository_skydrive'),
+ ];
+ $mform->addElement('select', 'defaultreturntype', get_string('defaultreturntype', 'repository_skydrive'), $choices);
}
}
+
+/**
+ * Callback to get the required scopes for system account.
+ *
+ * @return string
+ */
+function repository_skydrive_oauth2_system_scopes(\core\oauth2\issuer $issuer) {
+ if ($issuer->get('id') == get_config('skydrive', 'issuerid')) {
+ return repository_skydrive::SCOPES;
+ }
+ return '';
+}
diff --git a/repository/skydrive/microsoftliveapi.php b/repository/skydrive/microsoftliveapi.php
deleted file mode 100644
index 5fc52274eae..00000000000
--- a/repository/skydrive/microsoftliveapi.php
+++ /dev/null
@@ -1,245 +0,0 @@
-.
-
-/**
- * Functions for operating with the skydrive API
- *
- * @package repository_skydrive
- * @copyright 2012 Lancaster University Network Services Ltd
- * @author Dan Poltawski
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-
-defined('MOODLE_INTERNAL') || die();
-
-require_once($CFG->libdir.'/oauthlib.php');
-
-/**
- * A helper class to access microsoft live resources using the api.
- *
- * This uses the microsfot API defined in
- * http://msdn.microsoft.com/en-us/library/hh243648.aspx
- *
- * @package repository_skydrive
- * @copyright 2012 Lancaster University Network Services Ltd
- * @author Dan Poltawski
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class microsoft_skydrive extends oauth2_client {
- /** @var string OAuth 2.0 scope */
- const SCOPE = 'wl.skydrive';
- /** @var string Base url to access API */
- const API = 'https://apis.live.net/v5.0';
- /** @var cache_session cache of foldernames */
- var $foldernamecache = null;
-
- /**
- * Construct a skydrive request object
- *
- * @param string $clientid client id for OAuth 2.0 provided by microsoft
- * @param string $clientsecret secret for OAuth 2.0 provided by microsoft
- * @param moodle_url $returnurl url to return to after succseful auth
- */
- public function __construct($clientid, $clientsecret, $returnurl) {
- parent::__construct($clientid, $clientsecret, $returnurl, self::SCOPE);
- // Make a session cache
- $this->foldernamecache = cache::make('repository_skydrive', 'foldername');
- }
-
- /**
- * Returns the auth url for OAuth 2.0 request
- * @return string the auth url
- */
- protected function auth_url() {
- return 'https://login.live.com/oauth20_authorize.srf';
- }
-
- /**
- * Returns the token url for OAuth 2.0 request
- * @return string the auth url
- */
- protected function token_url() {
- return 'https://login.live.com/oauth20_token.srf';
- }
-
- /**
- * Post request.
- *
- * Overridden to convert the data to a string, else curl will set the wrong headers.
- *
- * @param string $url The URL.
- * @param array|string $params The parameters.
- * @param array $options The options.
- * @return bool
- */
- public function post($url, $params = '', $options = array()) {
- return parent::post($url, format_postdata_for_curlcall($params), $options);
- }
-
- /**
- * Downloads a file to a file from skydrive using authenticated request
- *
- * @param string $id id of file
- * @param string $path path to save file to
- * @return array stucture for repository download_file
- */
- public function download_file($id, $path) {
- $url = self::API."/${id}/content";
- // Microsoft live redirects to the real download location..
- $this->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 3));
- $content = $this->get($url);
- file_put_contents($path, $content);
- return array('path'=>$path, 'url'=>$url);
- }
-
- /**
- * Returns a folder name property for a given folderid.
- *
- * @param string $folderid the folder id which is passed
- * @return mixed folder name or false in case of error
- */
- public function get_folder_name($folderid) {
- if (empty($folderid)) {
- throw new coding_exception('Empty folderid passed to get_folder_name');
- }
-
- // Cache based on oauthtoken and folderid.
- $cachekey = $this->folder_cache_key($folderid);
-
- if ($foldername = $this->foldernamecache->get($cachekey)) {
- return $foldername;
- }
-
- $url = self::API."/{$folderid}";
- $ret = json_decode($this->get($url));
- if (isset($ret->error)) {
- $this->log_out();
- return false;
- }
-
- $this->foldernamecache->set($cachekey, $ret->name);
- return $ret->name;
- }
-
- /**
- * Returns a list of files the user has formated for files api
- *
- * @param string $path the path which we are in
- * @return mixed Array of files formated for fileapoi
- */
- public function get_file_list($path = '') {
- global $OUTPUT;
-
- $precedingpath = '';
- if (empty($path)) {
- $url = self::API."/me/skydrive/files/";
- } else {
- $parts = explode('/', $path);
- $currentfolder = array_pop($parts);
- $url = self::API."/{$currentfolder}/files/";
- }
-
- $ret = json_decode($this->get($url));
-
- if (isset($ret->error)) {
- $this->log_out();
- return false;
- }
-
- $files = array();
-
- foreach ($ret->data as $file) {
- switch($file->type) {
- case 'folder':
- case 'album':
- // Cache the foldername for future requests.
- $cachekey = $this->folder_cache_key($file->id);
- $this->foldernamecache->set($cachekey, $file->name);
-
- $files[] = array(
- 'title' => $file->name,
- 'path' => $path.'/'.$file->id,
- 'size' => 0,
- 'date' => strtotime($file->updated_time),
- 'thumbnail' => $OUTPUT->image_url(file_folder_icon(90))->out(false),
- 'children' => array(),
- );
- break;
- case 'photo':
- $files[] = array(
- 'title' => $file->name,
- 'size' => $file->size,
- 'date' => strtotime($file->updated_time),
- 'thumbnail' => $OUTPUT->image_url(file_extension_icon($file->name, 90))->out(false),
- 'realthumbnail' => $file->picture,
- 'source' => $file->id,
- 'url' => $file->link,
- 'image_height' => $file->height,
- 'image_width' => $file->width,
- 'author' => $file->from->name,
- );
- break;
- case 'video':
- $files[] = array(
- 'title' => $file->name,
- 'size' => $file->size,
- 'date' => strtotime($file->updated_time),
- 'thumbnail' => $OUTPUT->image_url(file_extension_icon($file->name, 90))->out(false),
- 'realthumbnail' => $file->picture,
- 'source' => $file->id,
- 'url' => $file->link,
- 'author' => $file->from->name,
- );
- break;
- case 'audio':
- $files[] = array(
- 'title' => $file->name,
- 'size' => $file->size,
- 'date' => strtotime($file->updated_time),
- 'thumbnail' => $OUTPUT->image_url(file_extension_icon($file->name, 90))->out(false),
- 'source' => $file->id,
- 'url' => $file->link,
- 'author' => $file->from->name,
- );
- break;
- case 'file':
- $files[] = array(
- 'title' => $file->name,
- 'size' => $file->size,
- 'date' => strtotime($file->updated_time),
- 'thumbnail' => $OUTPUT->image_url(file_extension_icon($file->name, 90))->out(false),
- 'source' => $file->id,
- 'url' => $file->link,
- 'author' => $file->from->name,
- );
- break;
- }
- }
- return $files;
- }
-
- /**
- * Returns a key for foldernane cache
- *
- * @param string $folderid the folder id which is to be cached
- * @return string the cache key to use
- */
- private function folder_cache_key($folderid) {
- // Cache based on oauthtoken and folderid.
- return $this->get_tokenname().'_'.$folderid;
- }
-}
diff --git a/repository/skydrive/version.php b/repository/skydrive/version.php
index 8afca1d1f90..a3995847071 100644
--- a/repository/skydrive/version.php
+++ b/repository/skydrive/version.php
@@ -25,6 +25,6 @@
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2016120500; // The current plugin version (Date: YYYYMMDDXX).
+$plugin->version = 2017031400; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2016112900; // Requires this Moodle version.
$plugin->component = 'repository_skydrive'; // Full name of the plugin (used for diagnostics).
From 6e0d700de83af2589570895353e0bf45b718ad0e Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 14 Mar 2017 15:41:56 +0800
Subject: [PATCH 35/84] MDL-58220 assign: Only show write access to teachers
In filebrowser api - this is also used by repositories using controlled links.
---
mod/assign/assignmentplugin.php | 16 ++++++++++------
1 file changed, 10 insertions(+), 6 deletions(-)
diff --git a/mod/assign/assignmentplugin.php b/mod/assign/assignmentplugin.php
index 83b8dfa8b39..22c43f82cf2 100644
--- a/mod/assign/assignmentplugin.php
+++ b/mod/assign/assignmentplugin.php
@@ -582,6 +582,7 @@ abstract class assign_plugin {
$urlbase = $CFG->wwwroot.'/pluginfile.php';
$writeaccess = false;
// Permission check on the itemid.
+ $assignment = $this->assignment;
if ($this->get_subtype() == 'assignsubmission') {
if ($itemid) {
@@ -590,16 +591,19 @@ abstract class assign_plugin {
return null;
}
if (!empty($record->userid)) {
- if (!$this->assignment->can_view_submission($record->userid)) {
+ if (!$assignment->can_view_submission($record->userid)) {
return null;
}
- $writeaccess = $this->assignment->can_edit_submission($record->userid);
+
+ // We only report write access for teachers.
+ $writeaccess = $assignment->can_grade() && $assignment->can_edit_submission($record->userid);
} else {
// Must be a team submission with a group.
- if (!$this->assignment->can_view_group_submission($record->groupid)) {
+ if (!$assignment->can_view_group_submission($record->groupid)) {
return null;
}
- $writeaccess = $this->assignment->can_edit_group_submission($record->groupid);
+ // We only report write access for teachers.
+ $writeaccess = $assignment->can_grade() && $assignment->can_edit_group_submission($record->groupid);
}
}
} else {
@@ -610,7 +614,7 @@ abstract class assign_plugin {
$fs = get_file_storage();
$filepath = is_null($filepath) ? '/' : $filepath;
$filename = is_null($filename) ? '.' : $filename;
- if (!($storedfile = $fs->get_file($this->assignment->get_context()->id,
+ if (!($storedfile = $fs->get_file($assignment->get_context()->id,
$this->get_subtype() . '_' . $this->get_type(),
$filearea,
$itemid,
@@ -620,7 +624,7 @@ abstract class assign_plugin {
}
return new file_info_stored($browser,
- $this->assignment->get_context(),
+ $assignment->get_context(),
$storedfile,
$urlbase,
$filearea,
From eca128bf4786a5bd55614525a8fba0be73beaac8 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 14 Mar 2017 16:39:25 +0800
Subject: [PATCH 36/84] MDL-58220 oauth2: Global enable/disable for issuers.
---
admin/tool/oauth2/classes/output/renderer.php | 14 ++++++++
admin/tool/oauth2/issuers.php | 11 +++++++
admin/tool/oauth2/lang/en/tool_oauth2.php | 2 ++
auth/oauth2/classes/auth.php | 3 +-
lib/classes/oauth2/api.php | 33 +++++++++++++++++++
lib/classes/oauth2/issuer.php | 4 +++
lib/db/install.xml | 1 +
lib/db/upgrade.php | 1 +
repository/googledocs/lib.php | 18 ++++++++++
repository/skydrive/lib.php | 13 ++++++++
10 files changed, 99 insertions(+), 1 deletion(-)
diff --git a/admin/tool/oauth2/classes/output/renderer.php b/admin/tool/oauth2/classes/output/renderer.php
index d38d7f00848..7a6fe3aaa68 100644
--- a/admin/tool/oauth2/classes/output/renderer.php
+++ b/admin/tool/oauth2/classes/output/renderer.php
@@ -154,6 +154,20 @@ class renderer extends plugin_renderer_base {
$deleteurl = new moodle_url('/admin/tool/oauth2/issuers.php', ['id' => $issuer->get('id'), 'action' => 'delete']);
$deletelink = html_writer::link($deleteurl, $OUTPUT->pix_icon('t/delete', get_string('delete')));
$links .= ' ' . $deletelink;
+ // Enable / Disable.
+ if ($issuer->get('enabled')) {
+ // Disable.
+ $disableparams = ['id' => $issuer->get('id'), 'sesskey' => sesskey(), 'action' => 'disable'];
+ $disableurl = new moodle_url('/admin/tool/oauth2/issuers.php', $disableparams);
+ $disablelink = html_writer::link($disableurl, $OUTPUT->pix_icon('t/hide', get_string('disable')));
+ $links .= ' ' . $disablelink;
+ } else {
+ // Enable.
+ $enableparams = ['id' => $issuer->get('id'), 'sesskey' => sesskey(), 'action' => 'enable'];
+ $enableurl = new moodle_url('/admin/tool/oauth2/issuers.php', $enableparams);
+ $enablelink = html_writer::link($enableurl, $OUTPUT->pix_icon('t/show', get_string('enable')));
+ $links .= ' ' . $enablelink;
+ }
if (!$last) {
// Move down.
$params = ['id' => $issuer->get('id'), 'action' => 'movedown', 'sesskey' => sesskey()];
diff --git a/admin/tool/oauth2/issuers.php b/admin/tool/oauth2/issuers.php
index b8ada448e0a..7da2c480973 100644
--- a/admin/tool/oauth2/issuers.php
+++ b/admin/tool/oauth2/issuers.php
@@ -111,6 +111,17 @@ if ($mform && $mform->is_cancelled()) {
$editurl = new moodle_url('/admin/tool/oauth2/issuers.php', $params);
redirect($editurl, get_string('changessaved'), null, \core\output\notification::NOTIFY_SUCCESS);
}
+} else if ($action == 'enable') {
+
+ require_sesskey();
+ core\oauth2\api::enable_issuer($issuerid);
+ redirect($PAGE->url, get_string('issuerenabled', 'tool_oauth2'), null, \core\output\notification::NOTIFY_SUCCESS);
+
+} else if ($action == 'disable') {
+
+ require_sesskey();
+ core\oauth2\api::disable_issuer($issuerid);
+ redirect($PAGE->url, get_string('issuerdisabled', 'tool_oauth2'), null, \core\output\notification::NOTIFY_SUCCESS);
} else if ($action == 'delete') {
diff --git a/admin/tool/oauth2/lang/en/tool_oauth2.php b/admin/tool/oauth2/lang/en/tool_oauth2.php
index 2ee10daa14c..7c751416b51 100644
--- a/admin/tool/oauth2/lang/en/tool_oauth2.php
+++ b/admin/tool/oauth2/lang/en/tool_oauth2.php
@@ -84,6 +84,8 @@ $string['deleteconfirm'] = 'Are you sure you want to delete the identity issuer
$string['deleteendpointconfirm'] = 'Are you sure you want to delete the endpoint "{$a->endpoint}" for issuer "{$a->issuer}"? Any plugins relying on this endpoint will stop working.';
$string['deleteuserfieldmappingconfirm'] = 'Are you sure you want to delete the user field mapping for issuer "{$a}"?';
$string['issuerdeleted'] = 'Identity issuer deleted';
+$string['issuerenabled'] = 'Identity issuer enabled';
+$string['issuerdisabled'] = 'Identity issuer disabled';
$string['endpointdeleted'] = 'Endpoint deleted';
$string['userfieldmappingdeleted'] = 'User field mapping deleted';
$string['connectsystemaccount'] = 'Connect to a system account';
diff --git a/auth/oauth2/classes/auth.php b/auth/oauth2/classes/auth.php
index b82124e317b..832d1f0398b 100644
--- a/auth/oauth2/classes/auth.php
+++ b/auth/oauth2/classes/auth.php
@@ -180,7 +180,8 @@ class auth extends \auth_plugin_base {
* @return boolean
*/
private function is_ready_for_login_page(\core\oauth2\issuer $issuer) {
- return !empty($issuer->get('clientid')) &&
+ return $issuer->get('enabled') &&
+ !empty($issuer->get('clientid')) &&
!empty($issuer->get('clientsecret')) &&
$issuer->is_authentication_supported() &&
!empty($issuer->get('showonloginpage'));
diff --git a/lib/classes/oauth2/api.php b/lib/classes/oauth2/api.php
index c886a1aaecb..02320cefc1b 100644
--- a/lib/classes/oauth2/api.php
+++ b/lib/classes/oauth2/api.php
@@ -616,6 +616,39 @@ class api {
return $result;
}
+ /**
+ * Disable an identity issuer.
+ *
+ * Requires moodle/site:config capability at the system context.
+ *
+ * @param int $id The id of the identity issuer to enable.
+ * @return boolean
+ */
+ public static function disable_issuer($id) {
+ require_capability('moodle/site:config', context_system::instance());
+ $issuer = new issuer($id);
+
+ $issuer->set('enabled', 0);
+ return $issuer->update();
+ }
+
+
+ /**
+ * Enable an identity issuer.
+ *
+ * Requires moodle/site:config capability at the system context.
+ *
+ * @param int $id The id of the identity issuer to enable.
+ * @return boolean
+ */
+ public static function enable_issuer($id) {
+ require_capability('moodle/site:config', context_system::instance());
+ $issuer = new issuer($id);
+
+ $issuer->set('enabled', 1);
+ return $issuer->update();
+ }
+
/**
* Delete an identity issuer.
*
diff --git a/lib/classes/oauth2/issuer.php b/lib/classes/oauth2/issuer.php
index 756d36ba804..6ef3ca1d0b4 100644
--- a/lib/classes/oauth2/issuer.php
+++ b/lib/classes/oauth2/issuer.php
@@ -64,6 +64,10 @@ class issuer extends persistent {
'type' => PARAM_URL,
'default' => ''
),
+ 'enabled' => array(
+ 'type' => PARAM_BOOL,
+ 'default' => true
+ ),
'showonloginpage' => array(
'type' => PARAM_BOOL,
'default' => false
diff --git a/lib/db/install.xml b/lib/db/install.xml
index adb86a4f4ed..63545257b2e 100755
--- a/lib/db/install.xml
+++ b/lib/db/install.xml
@@ -3494,6 +3494,7 @@
+
diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php
index c5878f7b3a0..29eaf7471bd 100644
--- a/lib/db/upgrade.php
+++ b/lib/db/upgrade.php
@@ -2632,6 +2632,7 @@ function xmldb_main_upgrade($oldversion) {
$table->add_field('loginparamsoffline', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
$table->add_field('scopessupported', XMLDB_TYPE_TEXT, null, null, null, null, null);
$table->add_field('showonloginpage', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1');
+ $table->add_field('enabled', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1');
$table->add_field('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
// Adding keys to table oauth2_issuer.
diff --git a/repository/googledocs/lib.php b/repository/googledocs/lib.php
index cbc275ff470..eb9d83988a1 100644
--- a/repository/googledocs/lib.php
+++ b/repository/googledocs/lib.php
@@ -201,6 +201,10 @@ class repository_googledocs extends repository {
if (empty($path)) {
$path = $this->build_node_path('root', get_string('pluginname', 'repository_googledocs'));
}
+ if (!$this->issuer->get('enabled')) {
+ // Empty list of files for disabled repository.
+ return ['dynload' => false, 'list' => [], 'nologin' => true];
+ }
// We analyse the path to extract what to browse.
$trail = explode('/', $path);
@@ -416,6 +420,10 @@ class repository_googledocs extends repository {
public function get_file($reference, $filename = '') {
global $CFG;
+ if (!$this->issuer->get('enabled')) {
+ throw new repository_exception('cannotdownload', 'repository');
+ }
+
$client = $this->get_user_oauth_client();
$base = 'https://www.googleapis.com/drive/v3';
@@ -557,6 +565,10 @@ class repository_googledocs extends repository {
* @param array $options additional options affecting the file serving
*/
public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
+ if (!$this->issuer->get('enabled')) {
+ throw new repository_exception('cannotdownload', 'repository');
+ }
+
$source = json_decode($storedfile->get_reference());
$fb = get_file_browser();
@@ -829,6 +841,9 @@ class repository_googledocs extends repository {
* @return string updated reference (final one before it's saved to db).
*/
public function reference_file_selected($reference, $context, $component, $filearea, $itemid) {
+ if (!$this->issuer->get('enabled')) {
+ throw new repository_exception('cannotdownload', 'repository');
+ }
// What we need to do here is transfer ownership to the system user (or copy)
// then set the permissions so anyone with the share link can view,
// finally update the reference to contain the share link if it was not
@@ -919,6 +934,9 @@ class repository_googledocs extends repository {
* @param int $filestatus
*/
public function get_reference_details($reference, $filestatus = 0) {
+ if (!$this->issuer->get('enabled')) {
+ throw new repository_exception('cannotdownload', 'repository');
+ }
if (empty($reference)) {
return get_string('unknownsource', 'repository');
}
diff --git a/repository/skydrive/lib.php b/repository/skydrive/lib.php
index 41c87dc8f8e..d7b56a31482 100644
--- a/repository/skydrive/lib.php
+++ b/repository/skydrive/lib.php
@@ -198,6 +198,11 @@ class repository_skydrive extends repository {
$path = $this->build_node_path('root', get_string('pluginname', 'repository_skydrive'));
}
+ if (!$this->issuer->get('enabled')) {
+ // Empty list of files for disabled repository.
+ return ['dynload' => false, 'list' => [], 'nologin' => true];
+ }
+
// We analyse the path to extract what to browse.
$trail = explode('/', $path);
$uri = array_pop($trail);
@@ -392,6 +397,10 @@ class repository_skydrive extends repository {
public function get_file($reference, $filename = '') {
global $CFG;
+ if (!$this->issuer->get('enabled')) {
+ throw new repository_exception('cannotdownload', 'repository');
+ }
+
$client = $this->get_user_oauth_client();
$base = 'https://graph.microsoft.com/v1.0/';
@@ -505,6 +514,10 @@ class repository_skydrive extends repository {
* @param array $options additional options affecting the file serving
*/
public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
+ if (!$this->issuer->get('enabled')) {
+ throw new repository_exception('cannotdownload', 'repository');
+ }
+
$source = json_decode($storedfile->get_reference());
$fb = get_file_browser();
From 979d1f66dd1e15f64e941525c299bf7a272eb2e2 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Wed, 15 Mar 2017 10:13:07 +0800
Subject: [PATCH 37/84] MDL-58220 auth_oauth2: Fix new account creation
This was not allowing new accounts to be registered.
---
auth/oauth2/classes/auth.php | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/auth/oauth2/classes/auth.php b/auth/oauth2/classes/auth.php
index 832d1f0398b..b2fa8f6626e 100644
--- a/auth/oauth2/classes/auth.php
+++ b/auth/oauth2/classes/auth.php
@@ -76,6 +76,7 @@ class auth extends \auth_plugin_base {
if ($verifyusername == $username) {
return true;
}
+ return false;
}
/**
@@ -369,7 +370,7 @@ class auth extends \auth_plugin_base {
$this->set_static_user_info($userinfo);
- $user = get_complete_user_data('username', $userinfo['username']);
+ $user = authenticate_user_login($userinfo['username'], '');
if ($user) {
complete_user_login($user);
From c21a66e40af7e24bec5bc984304c2f3ee3453f52 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Wed, 15 Mar 2017 10:48:20 +0800
Subject: [PATCH 38/84] MDL-58220 auth_oauth2: Restrict logins to a set of
domains
This is set on the issuer, so you can have different lists for each oauth2 provider.
---
admin/tool/oauth2/classes/form/issuer.php | 8 +++++++
admin/tool/oauth2/lang/en/tool_oauth2.php | 3 +++
auth/oauth2/classes/auth.php | 9 ++++++--
lib/classes/oauth2/issuer.php | 27 +++++++++++++++++++++++
lib/db/upgrade.php | 17 +++++++-------
version.php | 2 +-
6 files changed, 55 insertions(+), 11 deletions(-)
diff --git a/admin/tool/oauth2/classes/form/issuer.php b/admin/tool/oauth2/classes/form/issuer.php
index 80a44820af0..b3356a1e411 100644
--- a/admin/tool/oauth2/classes/form/issuer.php
+++ b/admin/tool/oauth2/classes/form/issuer.php
@@ -99,6 +99,11 @@ class issuer extends persistent {
$mform->addRule('baseurl', get_string('maximumchars', '', 1024), 'maxlength', 1024, 'client');
$mform->addHelpButton('baseurl', 'issuerbaseurl', 'tool_oauth2');
+ // Allowed Domains.
+ $mform->addElement('text', 'alloweddomains', get_string('issueralloweddomains', 'tool_oauth2'), 'maxlength="1024"');
+ $mform->addRule('alloweddomains', get_string('maximumchars', '', 1024), 'maxlength', 1024, 'client');
+ $mform->addHelpButton('alloweddomains', 'issueralloweddomains', 'tool_oauth2');
+
// Image.
$mform->addElement('text', 'image', get_string('issuerimage', 'tool_oauth2'), 'maxlength="1024"');
$mform->addRule('image', get_string('maximumchars', '', 1024), 'maxlength', 1024, 'client');
@@ -114,6 +119,9 @@ class issuer extends persistent {
$mform->addElement('hidden', 'action', 'edit');
$mform->setType('action', PARAM_RAW);
+ $mform->addElement('hidden', 'enabled', $endpoint->get('enabled'));
+ $mform->setType('enabled', PARAM_BOOL);
+
$mform->addElement('hidden', 'id', $endpoint->get('id'));
$mform->setType('id', PARAM_INT);
diff --git a/admin/tool/oauth2/lang/en/tool_oauth2.php b/admin/tool/oauth2/lang/en/tool_oauth2.php
index 7c751416b51..63edd815de0 100644
--- a/admin/tool/oauth2/lang/en/tool_oauth2.php
+++ b/admin/tool/oauth2/lang/en/tool_oauth2.php
@@ -51,6 +51,9 @@ $string['issuerloginparams'] = 'Additional parameters included in a login reques
$string['issuerloginparams_help'] = 'Some systems require additional parameters for a login request in order to read the users basic profile.';
$string['issuerloginparamsoffline'] = 'Additional parameters included in a login request for offline access.';
$string['issuerloginparamsoffline_help'] = 'Each OAuth system defines a different way to request offline access. E.g. Google requires the additional params: "access_type=offline&prompt=consent" these parameters should be in url query parameter format.';
+$string['issueralloweddomains'] = 'Login domains';
+$string['issueralloweddomains_help'] = 'If set, this setting is a comma separated list of domains that logins will be restricted to when using this provider.';
+$string['issueralloweddomains_link'] = 'OAuth_2_login_domains';
$string['issuershowonloginpage'] = 'Show on login page.';
$string['issuershowonloginpage_help'] = 'If the OpenID Connect Authentication plugin is enabled, this login issuer will be listed on the login page to allow users to login with accounts from this issuer.';
$string['issuerbehaviour'] = 'Behaviour';
diff --git a/auth/oauth2/classes/auth.php b/auth/oauth2/classes/auth.php
index b2fa8f6626e..82e58e24311 100644
--- a/auth/oauth2/classes/auth.php
+++ b/auth/oauth2/classes/auth.php
@@ -368,9 +368,14 @@ class auth extends \auth_plugin_base {
}
}
- $this->set_static_user_info($userinfo);
+ $issuer = $client->get_issuer();
- $user = authenticate_user_login($userinfo['username'], '');
+ $user = false;
+ if ($issuer->is_valid_login_domain($userinfo['email'])) {
+
+ $this->set_static_user_info($userinfo);
+ $user = authenticate_user_login($userinfo['username'], '');
+ }
if ($user) {
complete_user_login($user);
diff --git a/lib/classes/oauth2/issuer.php b/lib/classes/oauth2/issuer.php
index 6ef3ca1d0b4..58709a922ca 100644
--- a/lib/classes/oauth2/issuer.php
+++ b/lib/classes/oauth2/issuer.php
@@ -93,6 +93,10 @@ class issuer extends persistent {
'type' => PARAM_RAW,
'default' => ''
),
+ 'alloweddomains' => array(
+ 'type' => PARAM_RAW,
+ 'default' => ''
+ ),
'sortorder' => array(
'type' => PARAM_INT,
'default' => 0,
@@ -128,6 +132,29 @@ class issuer extends persistent {
return false;
}
+ /**
+ * Perform matching against the list of allowed login domains for this issuer.
+ * @return boolean
+ */
+ public function is_valid_login_domain($email) {
+ if (empty($this->get('alloweddomains'))) {
+ return true;
+ }
+ $validdomains = explode(',', $this->get('alloweddomains'));
+
+ list($unused, $emaildomain) = explode('@', $email, 2);
+
+ foreach ($validdomains as $checkdomain) {
+ $checkdomain = \core_text::strtolower(trim($checkdomain));
+
+ if ((\core_text::strlen($checkdomain) == \core_text::strlen($emaildomain)) &&
+ (\core_text::strpos($checkdomain, $emaildomain) === 0)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
/**
* Does this OAuth service support user authentication?
* @return boolean
diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php
index 29eaf7471bd..99798247d77 100644
--- a/lib/db/upgrade.php
+++ b/lib/db/upgrade.php
@@ -2611,7 +2611,7 @@ function xmldb_main_upgrade($oldversion) {
upgrade_main_savepoint(true, 2017031400.00);
}
- if ($oldversion < 2017032400.21) {
+ if ($oldversion < 2017033100.01) {
// Define table oauth2_issuer to be created.
$table = new xmldb_table('oauth2_issuer');
@@ -2630,6 +2630,7 @@ function xmldb_main_upgrade($oldversion) {
$table->add_field('loginscopesoffline', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
$table->add_field('loginparams', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
$table->add_field('loginparamsoffline', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
+ $table->add_field('alloweddomains', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
$table->add_field('scopessupported', XMLDB_TYPE_TEXT, null, null, null, null, null);
$table->add_field('showonloginpage', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1');
$table->add_field('enabled', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1');
@@ -2644,10 +2645,10 @@ function xmldb_main_upgrade($oldversion) {
}
// Main savepoint reached.
- upgrade_main_savepoint(true, 2017032400.21);
+ upgrade_main_savepoint(true, 2017033100.01);
}
- if ($oldversion < 2017032400.22) {
+ if ($oldversion < 2017033100.02) {
// Define table oauth2_endpoint to be created.
$table = new xmldb_table('oauth2_endpoint');
@@ -2671,10 +2672,10 @@ function xmldb_main_upgrade($oldversion) {
}
// Main savepoint reached.
- upgrade_main_savepoint(true, 2017032400.22);
+ upgrade_main_savepoint(true, 2017033100.02);
}
- if ($oldversion < 2017032400.23) {
+ if ($oldversion < 2017033100.03) {
// Define table oauth2_system_account to be created.
$table = new xmldb_table('oauth2_system_account');
@@ -2700,10 +2701,10 @@ function xmldb_main_upgrade($oldversion) {
}
// Main savepoint reached.
- upgrade_main_savepoint(true, 2017032400.23);
+ upgrade_main_savepoint(true, 2017033100.03);
}
- if ($oldversion < 2017033100.01) {
+ if ($oldversion < 2017033100.04) {
// Define table oauth2_user_field_mapping to be created.
$table = new xmldb_table('oauth2_user_field_mapping');
@@ -2728,7 +2729,7 @@ function xmldb_main_upgrade($oldversion) {
}
// Main savepoint reached.
- upgrade_main_savepoint(true, 2017033100.01);
+ upgrade_main_savepoint(true, 2017033100.04);
}
return true;
diff --git a/version.php b/version.php
index aaed5ce20e3..b45e6e930a9 100644
--- a/version.php
+++ b/version.php
@@ -29,7 +29,7 @@
defined('MOODLE_INTERNAL') || die();
-$version = 2017033100.03; // YYYYMMDD = weekly release date of this DEV branch.
+$version = 2017033100.04; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
From 738c4a2a73462c24137cb5d76f71968764485e2f Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Wed, 15 Mar 2017 14:04:49 +0800
Subject: [PATCH 39/84] MDL-58220 oauth2: More help buttons
Add help for system account connections and discovery.
---
admin/tool/oauth2/classes/output/renderer.php | 3 +++
admin/tool/oauth2/lang/en/tool_oauth2.php | 2 ++
2 files changed, 5 insertions(+)
diff --git a/admin/tool/oauth2/classes/output/renderer.php b/admin/tool/oauth2/classes/output/renderer.php
index 7a6fe3aaa68..43633c1dab8 100644
--- a/admin/tool/oauth2/classes/output/renderer.php
+++ b/admin/tool/oauth2/classes/output/renderer.php
@@ -110,6 +110,8 @@ class renderer extends plugin_renderer_base {
$discovered = '-';
}
}
+ $discovered .= ' ' . $OUTPUT->help_icon('discovered', 'tool_oauth2');
+
$discoverystatuscell = new html_table_cell($discovered);
// Connected.
@@ -128,6 +130,7 @@ class renderer extends plugin_renderer_base {
$authlink = html_writer::link($authurl, $icon);
$systemauth .= ' ' . $authlink;
}
+ $systemauth .= ' ' . $OUTPUT->help_icon('systemaccountconnected', 'tool_oauth2');
$systemauthstatuscell = new html_table_cell($systemauth);
diff --git a/admin/tool/oauth2/lang/en/tool_oauth2.php b/admin/tool/oauth2/lang/en/tool_oauth2.php
index 63edd815de0..4d697b16c3a 100644
--- a/admin/tool/oauth2/lang/en/tool_oauth2.php
+++ b/admin/tool/oauth2/lang/en/tool_oauth2.php
@@ -23,6 +23,8 @@
*/
$string['pluginname'] = 'OAuth 2 Services';
+$string['discovered_help'] = 'Discovered means that the OAuth2 endpoints could be automatically determined from the base url for the OAuth service. Not all services are required to be "discovered", but if they are not, then the endpoints and user mapping information will need to be entered manually.';
+$string['systemaccountconnected_help'] = 'System accounts are used to provide advanced functionality for plugins. They are not required for login functionality only, but other plugins using the OAuth service may offer a reduced set of features if the system account has not been connected. For example repositories cannot support "controlled links" without a system account to perform file operations.';
$string['editissuer'] = 'Edit identity issuer: {$a}';
$string['editendpoint'] = 'Edit endpoint: {$a->endpoint} for issuer {$a->issuer}';
$string['endpointsforissuer'] = 'Endpoints for issuer: {$a}';
From 092304a3decc86a4277dbc7e5e45943f00219a9e Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Wed, 15 Mar 2017 15:07:41 +0800
Subject: [PATCH 40/84] MDL-58220 oauth2: Cibot fixes
Missing phpdocs.
---
lib/classes/oauth2/issuer.php | 2 ++
repository/googledocs/lib.php | 1 +
repository/skydrive/classes/access.php | 3 ++-
.../skydrive/classes/remove_temp_access_task.php | 2 +-
repository/skydrive/db/upgrade.php | 1 +
repository/skydrive/lib.php | 13 ++++++++-----
6 files changed, 15 insertions(+), 7 deletions(-)
diff --git a/lib/classes/oauth2/issuer.php b/lib/classes/oauth2/issuer.php
index 58709a922ca..5bbb9e8d049 100644
--- a/lib/classes/oauth2/issuer.php
+++ b/lib/classes/oauth2/issuer.php
@@ -134,6 +134,8 @@ class issuer extends persistent {
/**
* Perform matching against the list of allowed login domains for this issuer.
+ *
+ * @param string $email The email to check.
* @return boolean
*/
public function is_valid_login_domain($email) {
diff --git a/repository/googledocs/lib.php b/repository/googledocs/lib.php
index eb9d83988a1..5137d519e32 100644
--- a/repository/googledocs/lib.php
+++ b/repository/googledocs/lib.php
@@ -1058,6 +1058,7 @@ class repository_googledocs extends repository {
/**
* Callback to get the required scopes for system account.
*
+ * @param \core\oauth2\issuer $issuer
* @return string
*/
function repository_googledocs_oauth2_system_scopes(\core\oauth2\issuer $issuer) {
diff --git a/repository/skydrive/classes/access.php b/repository/skydrive/classes/access.php
index 8c3fd90edc6..35a9bdd1d9a 100644
--- a/repository/skydrive/classes/access.php
+++ b/repository/skydrive/classes/access.php
@@ -17,7 +17,7 @@
/**
* Class for loading/storing access records from the DB.
*
- * @package core
+ * @package repository_skydrive
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@@ -30,6 +30,7 @@ use core\persistent;
/**
* Class for loading/storing issuer from the DB
*
+ * @package repository_skydrive
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
diff --git a/repository/skydrive/classes/remove_temp_access_task.php b/repository/skydrive/classes/remove_temp_access_task.php
index 98247ec93db..b7f928449bf 100644
--- a/repository/skydrive/classes/remove_temp_access_task.php
+++ b/repository/skydrive/classes/remove_temp_access_task.php
@@ -30,7 +30,7 @@ defined('MOODLE_INTERNAL') || die();
/**
* Simple task to delete temporary permission records.
- * @package core
+ * @package repository_skydrive
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
diff --git a/repository/skydrive/db/upgrade.php b/repository/skydrive/db/upgrade.php
index 7a714846fcd..a9922abe2f1 100644
--- a/repository/skydrive/db/upgrade.php
+++ b/repository/skydrive/db/upgrade.php
@@ -18,6 +18,7 @@ defined('MOODLE_INTERNAL') || die();
/**
* @param int $oldversion the version we are upgrading from
+ * @package repository_skydrive
* @return bool result
*/
function xmldb_repository_skydrive_upgrade($oldversion) {
diff --git a/repository/skydrive/lib.php b/repository/skydrive/lib.php
index d7b56a31482..89c3b174559 100644
--- a/repository/skydrive/lib.php
+++ b/repository/skydrive/lib.php
@@ -271,6 +271,7 @@ class repository_skydrive extends repository {
*
* @param string $q search query as expected by the Google API.
* @param string $path parent path of the current files, will not be used for the query.
+ * @param string $parent Parent id.
* @param int $page page.
* @return array of files and folders.
*/
@@ -391,7 +392,7 @@ class repository_skydrive extends repository {
* Get a file.
*
* @param string $reference reference of the file.
- * @param string $file name to save the file to.
+ * @param string $filename filename to save the file to.
* @return string JSON encoded array of information about the file.
*/
public function get_file($reference, $filename = '') {
@@ -726,7 +727,7 @@ class repository_skydrive extends repository {
*
* @param \repository_skydrive\rest $client Authenticated client.
* @param string $fileid The file we are updating.
- * @param string $userid The userid of the writer account to add.
+ * @param string $useremail The user email of the writer account to add.
* @return boolean
*/
protected function add_writer_to_file(\repository_skydrive\rest $client, $fileid, $useremail) {
@@ -767,10 +768,12 @@ class repository_skydrive extends repository {
}
/**
- * Get share info.
+ * Copy a shared file to a new folder.
*
* @param \repository_skydrive\rest $client Authenticated client.
* @param string $sharetoken The share we are querying.
+ * @param string $newdrive Id of the drive to copy to.
+ * @param string $parentid Id of the folder to copy to.
* @return stdClass
*/
protected function copy_share(\repository_skydrive\rest $client, $sharetoken, $newdrive, $parentid) {
@@ -793,8 +796,8 @@ class repository_skydrive extends repository {
* Replace unsafe URL characters with an equivelent character; replace / with _ and + with -.
* Append u! to the beginning of the string.
*
- * @param string sharingUrl
- * @return string sharingtoken
+ * @param string $shareurl
+ * @return string The sharing token
*/
protected function get_share_token($shareurl) {
return 'u!' . str_replace(['/', '+'], ['_', '-'], rtrim(base64_encode($shareurl), '='));
From fa78244d17d8b0acaed91b7e7b9f9d79f59e0ab0 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Wed, 15 Mar 2017 16:29:25 +0800
Subject: [PATCH 41/84] MDL-58220 oauth2: Fix unit tests and add more
---
lib/classes/oauth2/issuer.php | 6 ++-
lib/tests/oauth2_test.php | 72 ++++++++++++++++++++++++++++++++++-
2 files changed, 76 insertions(+), 2 deletions(-)
diff --git a/lib/classes/oauth2/issuer.php b/lib/classes/oauth2/issuer.php
index 5bbb9e8d049..3f56d7aedc1 100644
--- a/lib/classes/oauth2/issuer.php
+++ b/lib/classes/oauth2/issuer.php
@@ -144,7 +144,11 @@ class issuer extends persistent {
}
$validdomains = explode(',', $this->get('alloweddomains'));
- list($unused, $emaildomain) = explode('@', $email, 2);
+ $parts = explode('@', $email, 2);
+ $emaildomain = '';
+ if (count($parts) > 1) {
+ $emaildomain = $parts[1];
+ }
foreach ($validdomains as $checkdomain) {
$checkdomain = \core_text::strtolower(trim($checkdomain));
diff --git a/lib/tests/oauth2_test.php b/lib/tests/oauth2_test.php
index 1831dc26b3d..a8b50c11449 100644
--- a/lib/tests/oauth2_test.php
+++ b/lib/tests/oauth2_test.php
@@ -74,7 +74,10 @@ class core_oauth2_testcase extends advanced_testcase {
$issuer = \core\oauth2\api::create_standard_issuer('microsoft');
$same = \core\oauth2\api::get_issuer($issuer->get('id'));
- $this->assertEquals($issuer, $same);
+
+ foreach ($same->properties_definition() as $name => $def) {
+ $this->assertTrue($issuer->get($name) == $same->get($name));
+ }
$endpoints = \core\oauth2\api::get_endpoints($issuer);
$same = \core\oauth2\api::get_endpoint($endpoints[0]->get('id'));
@@ -132,4 +135,71 @@ class core_oauth2_testcase extends advanced_testcase {
$client = \core\oauth2\api::get_system_oauth_client($issuer);
$this->assertTrue($client->is_logged_in());
}
+
+ /**
+ * Tests we can enable and disable an issuer.
+ */
+ public function test_enable_disable_issuer() {
+ global $SESSION;
+
+ $this->resetAfterTest();
+ $this->setAdminUser();
+
+ $issuer = \core\oauth2\api::create_standard_issuer('microsoft');
+
+ $issuerid = $issuer->get('id');
+
+ \core\oauth2\api::enable_issuer($issuerid);
+ $check = \core\oauth2\api::get_issuer($issuer->get('id'));
+ $this->assertTrue((boolean)$check->get('enabled'));
+
+ \core\oauth2\api::enable_issuer($issuerid);
+ $check = \core\oauth2\api::get_issuer($issuer->get('id'));
+ $this->assertTrue((boolean)$check->get('enabled'));
+
+ \core\oauth2\api::disable_issuer($issuerid);
+ $check = \core\oauth2\api::get_issuer($issuer->get('id'));
+ $this->assertFalse((boolean)$check->get('enabled'));
+
+ \core\oauth2\api::enable_issuer($issuerid);
+ $check = \core\oauth2\api::get_issuer($issuer->get('id'));
+ $this->assertTrue((boolean)$check->get('enabled'));
+ }
+
+ /**
+ * Test the alloweddomains for an issuer.
+ */
+ public function test_issuer_alloweddomains() {
+ global $SESSION;
+
+ $this->resetAfterTest();
+ $this->setAdminUser();
+
+ $issuer = \core\oauth2\api::create_standard_issuer('microsoft');
+
+ $issuer->set('alloweddomains', '');
+
+ // Anything is allowed when domain is empty.
+ $this->assertTrue($issuer->is_valid_login_domain(''));
+ $this->assertTrue($issuer->is_valid_login_domain('a@b'));
+ $this->assertTrue($issuer->is_valid_login_domain('longer.example@example.com'));
+
+ $issuer->set('alloweddomains', 'example.com');
+
+ // One domain - must match exactly - no substrings etc.
+ $this->assertFalse($issuer->is_valid_login_domain(''));
+ $this->assertFalse($issuer->is_valid_login_domain('a@b'));
+ $this->assertFalse($issuer->is_valid_login_domain('longer.example@example'));
+ $this->assertTrue($issuer->is_valid_login_domain('longer.example@example.com'));
+
+ $issuer->set('alloweddomains', 'example.com,example.net');
+ // Multiple domains - must match any exactly - no substrings etc.
+ $this->assertFalse($issuer->is_valid_login_domain(''));
+ $this->assertFalse($issuer->is_valid_login_domain('a@b'));
+ $this->assertFalse($issuer->is_valid_login_domain('longer.example@example'));
+ $this->assertFalse($issuer->is_valid_login_domain('invalid@email@example.net'));
+ $this->assertTrue($issuer->is_valid_login_domain('longer.example@example.net'));
+ $this->assertTrue($issuer->is_valid_login_domain('longer.example@example.com'));
+ }
+
}
From d5bb9f1ffca8eb4110881f989421f0a09e9d88b0 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 21 Mar 2017 13:16:29 +0800
Subject: [PATCH 42/84] MDL-58334 repositories: Offline downloads
Support an optional param for offline downloads for repositories supporting external links (googledrive and skydrive).
Part of MDL-58220
---
lib/filelib.php | 70 ++++++++++++++++++-----------------
pluginfile.php | 5 ++-
repository/googledocs/lib.php | 12 +++++-
repository/skydrive/lib.php | 9 +++--
4 files changed, 57 insertions(+), 39 deletions(-)
diff --git a/lib/filelib.php b/lib/filelib.php
index d9e0b0bb414..0c314f547ba 100644
--- a/lib/filelib.php
+++ b/lib/filelib.php
@@ -3856,9 +3856,11 @@ class curl_cache {
* @param string $relativepath
* @param bool $forcedownload
* @param null|string $preview the preview mode, defaults to serving the original file
+ * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
+ * offline (e.g. mobile app).
* @todo MDL-31088 file serving improments
*/
-function file_pluginfile($relativepath, $forcedownload, $preview = null) {
+function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false) {
global $DB, $CFG, $USER;
// relative path must start with '/'
if (!$relativepath) {
@@ -3882,6 +3884,8 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
$fs = get_file_storage();
+ $sendfileoptions = ['preview' => $preview, 'offline' => $offline];
+
// ========================================================================================================================
if ($component === 'blog') {
// Blog file serving
@@ -3934,7 +3938,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
send_file_not_found();
}
- send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
+ send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
// ========================================================================================================================
} else if ($component === 'grade') {
@@ -3951,7 +3955,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
//TODO: nobody implemented this yet in grade edit form!!
@@ -3968,7 +3972,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else {
send_file_not_found();
}
@@ -3989,7 +3993,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, true, $sendfileoptions);
} else {
send_file_not_found();
@@ -4011,14 +4015,14 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close();
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
send_file_not_found();
}
\core\session\manager::write_close();
- send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, true, $sendfileoptions);
}
// ========================================================================================================================
} else if ($component === 'calendar') {
@@ -4045,7 +4049,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
@@ -4073,7 +4077,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 0, 0, true, array('preview' => $preview));
+ send_stored_file($file, 0, 0, true, $sendfileoptions);
} else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
@@ -4120,7 +4124,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else {
send_file_not_found();
@@ -4174,7 +4178,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
send_file($imagefile, basename($imagefile), 60*60*24*14);
}
- $options = array('preview' => $preview);
+ $options = $sendfileoptions;
if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
// Profile images should be cache-able by both browsers and proxies according
// to $CFG->forcelogin and $CFG->forceloginforprofileimage.
@@ -4200,7 +4204,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
+ send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
} else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
@@ -4247,7 +4251,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
+ send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
} else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
$userid = (int)array_shift($args);
@@ -4285,7 +4289,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
+ send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
} else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
require_login();
@@ -4306,7 +4310,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
+ send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
} else {
send_file_not_found();
@@ -4339,7 +4343,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else {
send_file_not_found();
}
@@ -4362,7 +4366,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else if ($filearea === 'section') {
if ($CFG->forcelogin) {
@@ -4384,7 +4388,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else {
send_file_not_found();
@@ -4413,7 +4417,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
&& !$file->is_directory()) {
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
}
}
@@ -4445,7 +4449,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else if ($filearea === 'icon') {
$filename = array_pop($args);
@@ -4460,7 +4464,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, false, $sendfileoptions);
} else {
send_file_not_found();
@@ -4485,7 +4489,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else {
send_file_not_found();
@@ -4504,7 +4508,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
} else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
require_login($course);
@@ -4519,7 +4523,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close();
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
require_login($course, false, $cm);
@@ -4532,7 +4536,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close();
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
} else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
// Backup files that were generated by the automated backup systems.
@@ -4547,7 +4551,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
} else {
send_file_not_found();
@@ -4556,7 +4560,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
// ========================================================================================================================
} else if ($component === 'question') {
require_once($CFG->libdir . '/questionlib.php');
- question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
+ question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
send_file_not_found();
// ========================================================================================================================
@@ -4593,7 +4597,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
\core\session\manager::write_close(); // Unlock session during file serving.
- send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
+ send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
}
// ========================================================================================================================
@@ -4625,17 +4629,17 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
}
// finally send the file
- send_stored_file($file, null, 0, false, array('preview' => $preview));
+ send_stored_file($file, null, 0, false, $sendfileoptions);
}
$filefunction = $component.'_pluginfile';
$filefunctionold = $modname.'_pluginfile';
if (function_exists($filefunction)) {
// if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
- $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
+ $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
} else if (function_exists($filefunctionold)) {
// if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
- $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
+ $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
}
send_file_not_found();
@@ -4676,7 +4680,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
$filefunction = $component.'_pluginfile';
if (function_exists($filefunction)) {
// if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
- $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
+ $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
}
send_file_not_found();
@@ -4697,7 +4701,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) {
$filefunction = $component.'_pluginfile';
if (function_exists($filefunction)) {
// if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
- $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
+ $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
}
send_file_not_found();
diff --git a/pluginfile.php b/pluginfile.php
index 8cc087786dd..9148b624447 100644
--- a/pluginfile.php
+++ b/pluginfile.php
@@ -33,5 +33,8 @@ require_once('lib/filelib.php');
$relativepath = get_file_argument();
$forcedownload = optional_param('forcedownload', 0, PARAM_BOOL);
$preview = optional_param('preview', null, PARAM_ALPHANUM);
+// Offline means download the file from the repository and serve it, even if it was an external link.
+// The repository may have to export the file to an offline format.
+$offline = optional_param('offline', 0, PARAM_BOOL);
-file_pluginfile($relativepath, $forcedownload, $preview);
+file_pluginfile($relativepath, $forcedownload, $preview, $offline);
diff --git a/repository/googledocs/lib.php b/repository/googledocs/lib.php
index 5137d519e32..0cafa7b0f56 100644
--- a/repository/googledocs/lib.php
+++ b/repository/googledocs/lib.php
@@ -580,7 +580,7 @@ class repository_googledocs extends repository {
$storedfile->get_filepath(),
$storedfile->get_filename());
- if ($info->is_writable()) {
+ if (empty($options['offline']) && $info->is_writable()) {
// Add the current user as an OAuth writer.
$systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
@@ -613,7 +613,15 @@ class repository_googledocs extends repository {
$this->add_temp_writer_to_file($systemservice, $source->id, $useremail);
}
- if ($source->link) {
+ if (!empty($options['offline'])) {
+ $downloaded = $this->get_file($storedfile->get_reference(), $storedfile->get_filename());
+
+ $filename = $storedfile->get_filename();
+ if (isset($downloaded['newfilename'])) {
+ $filename = $downloaded['newfilename'];
+ }
+ send_file($downloaded['path'], $filename, $lifetime, $filter, false, $forcedownload, '', false, $options);
+ } else if ($source->link) {
redirect($source->link);
} else {
$details = 'File is missing source link';
diff --git a/repository/skydrive/lib.php b/repository/skydrive/lib.php
index 89c3b174559..569526c58ec 100644
--- a/repository/skydrive/lib.php
+++ b/repository/skydrive/lib.php
@@ -530,7 +530,7 @@ class repository_skydrive extends repository {
$storedfile->get_filepath(),
$storedfile->get_filename());
- if ($info->is_writable()) {
+ if (empty($options['offline']) && $info->is_writable()) {
// Add the current user as an OAuth writer.
$systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
@@ -563,7 +563,11 @@ class repository_skydrive extends repository {
$this->add_temp_writer_to_file($systemservice, $source->id, $useremail);
}
- if ($source->link) {
+ if (!empty($options['offline'])) {
+ $downloaded = $this->get_file($storedfile->get_reference(), $storedfile->get_filename());
+ $filename = $storedfile->get_filename();
+ send_file($downloaded['path'], $filename, $lifetime, $filter, false, $forcedownload, '', false, $options);
+ } else if ($source->link) {
redirect($source->link);
} else {
$details = 'File is missing source link';
@@ -820,7 +824,6 @@ class repository_skydrive extends repository {
// then set the permissions so anyone with the share link can view,
// finally update the reference to contain the share link if it was not
// already there (and point to new file id if we copied).
- var_dump($reference);
$systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer);
if ($systemauth === false) {
From 28b592d5a6957a4e9d0642f246da945ffa599f6e Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 21 Mar 2017 16:43:23 +0800
Subject: [PATCH 43/84] MDL-58338 oauth2: Force email confirmation
New accounts and linking a login to an existing account MUST go through email verification.
We cannot trust the emails we get from oauth providers have been confirmed.
Part of MDL-58220
---
auth/oauth2/classes/api.php | 194 +++++++++++++++++++++++++--
auth/oauth2/classes/auth.php | 151 +++++++++++++++++----
auth/oauth2/classes/linked_login.php | 6 +
auth/oauth2/config.html | 20 ---
auth/oauth2/confirm-account.php | 91 +++++++++++++
auth/oauth2/confirm-linkedlogin.php | 78 +++++++++++
auth/oauth2/db/install.xml | 6 +-
auth/oauth2/db/upgrade.php | 22 +++
auth/oauth2/lang/en/auth_oauth2.php | 45 +++++++
auth/oauth2/version.php | 2 +-
lib/classes/user.php | 23 ++++
11 files changed, 573 insertions(+), 65 deletions(-)
create mode 100644 auth/oauth2/confirm-account.php
create mode 100644 auth/oauth2/confirm-linkedlogin.php
diff --git a/auth/oauth2/classes/api.php b/auth/oauth2/classes/api.php
index a7090bdf95b..58028a9f573 100644
--- a/auth/oauth2/classes/api.php
+++ b/auth/oauth2/classes/api.php
@@ -26,6 +26,7 @@ namespace auth_oauth2;
use context_user;
use stdClass;
use moodle_exception;
+use moodle_url;
defined('MOODLE_INTERNAL') || die();
@@ -60,7 +61,7 @@ class api {
$context = context_user::instance($userid);
require_capability('auth/oauth2:managelinkedlogins', $context);
- return linked_login::get_records(['userid' => $userid]);
+ return linked_login::get_records(['userid' => $userid, 'confirmtoken' => '']);
}
/**
@@ -75,14 +76,7 @@ class api {
'issuerid' => $issuer->get('id'),
'username' => $username
];
- $match = linked_login::get_record($params);
-
- if ($match) {
- $user = get_complete_user_data('id', $match->get('userid'));
-
- return $user;
- }
- return false;
+ return linked_login::get_record($params);
}
/**
@@ -93,9 +87,10 @@ class api {
* @param array $userinfo as returned from an oauth client.
* @param \core\oauth2\issuer $issuer
* @param int $userid (defaults to $USER->id)
- * @return boolean
+ * @param bool $skippermissions During signup we need to set this before the user is setup for capability checks.
+ * @return bool
*/
- public static function link_login($userinfo, $issuer, $userid = false) {
+ public static function link_login($userinfo, $issuer, $userid = false, $skippermissions = false) {
global $USER;
if ($userid === false) {
@@ -107,21 +102,194 @@ class api {
}
$context = context_user::instance($userid);
- require_capability('auth/oauth2:managelinkedlogins', $context);
+ if (!$skippermissions) {
+ require_capability('auth/oauth2:managelinkedlogins', $context);
+ }
$record = new stdClass();
$record->issuerid = $issuer->get('id');
$record->username = $userinfo['username'];
- $record->email = $userinfo['email'];
$record->userid = $userid;
$existing = linked_login::get_record((array)$record);
if ($existing) {
+ $existing->set('confirmtoken', '');
+ $existing->update();
return $existing;
}
+ $record->email = $userinfo['email'];
+ $record->confirmtoken = '';
$linkedlogin = new linked_login(0, $record);
return $linkedlogin->create();
}
+ /**
+ * Send an email with a link to confirm linking this account.
+ *
+ * @param array $userinfo as returned from an oauth client.
+ * @param \core\oauth2\issuer $issuer
+ * @param int $userid (defaults to $USER->id)
+ * @return bool
+ */
+ public static function send_confirm_link_login_email($userinfo, $issuer, $userid) {
+
+ $record = new stdClass();
+ $record->issuerid = $issuer->get('id');
+ $record->username = $userinfo['username'];
+ $record->userid = $userid;
+ $existing = linked_login::get_record((array)$record);
+ if ($existing) {
+ return false;
+ }
+ $record->email = $userinfo['email'];
+ $record->confirmtoken = random_string(32);
+ $expires = new \DateTime('NOW');
+ $expires->add(new \DateInterval('PT30M'));
+ $record->confirmtokenexpires = $expires->getTimestamp();
+
+ $linkedlogin = new linked_login(0, $record);
+ $linkedlogin->create();
+
+ // Construct the email.
+ $site = get_site();
+ $supportuser = \core_user::get_support_user();
+ $user = get_complete_user_data('id', $userid);
+
+ $data = new stdClass();
+ $data->fullname = fullname($user);
+ $data->sitename = format_string($site->fullname);
+ $data->admin = generate_email_signoff();
+ $data->issuername = format_string($issuer->get('name'));
+ $data->linkedemail = format_string($linkedlogin->get('email'));
+
+ $subject = get_string('confirmlinkedloginemailsubject', 'auth_oauth2', format_string($site->fullname));
+
+ $params = [
+ 'token' => $linkedlogin->get('confirmtoken'),
+ 'userid' => $userid,
+ 'username' => $userinfo['username'],
+ 'issuerid' => $issuer->get('id'),
+ ];
+ $confirmationurl = new moodle_url('/auth/oauth2/confirm-linkedlogin.php', $params);
+
+ // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
+ $data->link = $confirmationurl->out();
+
+ $message = get_string('confirmlinkedloginemail', 'auth_oauth2', $data);
+ $messagehtml = text_to_html(get_string('confirmlinkedloginemail', 'auth_oauth2', $data), false, false, true);
+
+ $user->mailformat = 1; // Always send HTML version as well.
+
+ // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
+ return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
+ }
+
+ /**
+ * Look for a waiting confirmation token, and if we find a match - confirm it.
+ *
+ * @param int $userid
+ * @param string $username
+ * @param int $issuerid
+ * @param string $token
+ * @return boolean True if we linked.
+ */
+ public static function confirm_link_login($userid, $username, $issuerid, $token) {
+ if (empty($token) || empty($userid) || empty($issuerid) || empty($username)) {
+ return false;
+ }
+ $params = [
+ 'userid' => $userid,
+ 'username' => $username,
+ 'issuerid' => $issuerid,
+ 'confirmtoken' => $token,
+ ];
+
+ $login = linked_login::get_record($params);
+ if (empty($login)) {
+ return false;
+ }
+ $expires = $login->get('confirmtokenexpires');
+ if (time() > $expires) {
+ $login->delete();
+ return;
+ }
+ $login->set('confirmtokenexpires', 0);
+ $login->set('confirmtoken', '');
+ $login->update();
+ return true;
+ }
+
+ /**
+ * Send an email with a link to confirm creating this account.
+ *
+ * @param array $userinfo as returned from an oauth client.
+ * @param \core\oauth2\issuer $issuer
+ * @param int $userid (defaults to $USER->id)
+ * @return bool
+ */
+ public static function send_confirm_account_email($userinfo, $issuer) {
+ global $CFG, $DB;
+ require_once($CFG->dirroot.'/user/profile/lib.php');
+ require_once($CFG->dirroot.'/user/lib.php');
+
+ $user = new stdClass();
+ $user->username = $userinfo['username'];
+ $user->email = $userinfo['email'];
+ $user->auth = 'oauth2';
+ $user->mnethostid = $CFG->mnet_localhost_id;
+ $user->lastname = isset($userinfo['lastname']) ? $userinfo['lastname'] : '';
+ $user->firstname = isset($userinfo['firstname']) ? $userinfo['firstname'] : '';
+ $user->url = isset($userinfo['url']) ? $userinfo['url'] : '';
+ $user->alternatename = isset($userinfo['alternatename']) ? $userinfo['alternatename'] : '';
+ $user->secret = random_string(15);
+
+ $user->password = '';
+ // This user is not confirmed.
+ $user->confirmed = 0;
+
+ $user->id = user_create_user($user, false, true);
+
+ // The linked account is pre-confirmed.
+ $record = new stdClass();
+ $record->issuerid = $issuer->get('id');
+ $record->username = $userinfo['username'];
+ $record->userid = $user->id;
+ $record->email = $userinfo['email'];
+ $record->confirmtoken = '';
+ $record->confirmtokenexpires = 0;
+
+ $linkedlogin = new linked_login(0, $record);
+ $linkedlogin->create();
+
+ // Construct the email.
+ $site = get_site();
+ $supportuser = \core_user::get_support_user();
+ $user = get_complete_user_data('id', $user->id);
+
+ $data = new stdClass();
+ $data->fullname = fullname($user);
+ $data->sitename = format_string($site->fullname);
+ $data->admin = generate_email_signoff();
+
+ $subject = get_string('confirmaccountemailsubject', 'auth_oauth2', format_string($site->fullname));
+
+ $params = [
+ 'token' => $user->secret,
+ 'username' => $userinfo['username']
+ ];
+ $confirmationurl = new moodle_url('/auth/oauth2/confirm-account.php', $params);
+
+ $data->link = $confirmationurl->out();
+
+ $message = get_string('confirmaccountemail', 'auth_oauth2', $data);
+ $messagehtml = text_to_html(get_string('confirmaccountemail', 'auth_oauth2', $data), false, false, true);
+
+ $user->mailformat = 1; // Always send HTML version as well.
+
+ // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
+ email_to_user($user, $supportuser, $subject, $message, $messagehtml);
+ return $user;
+ }
+
/**
* Delete linked login
*
diff --git a/auth/oauth2/classes/auth.php b/auth/oauth2/classes/auth.php
index 82e58e24311..951d8757d77 100644
--- a/auth/oauth2/classes/auth.php
+++ b/auth/oauth2/classes/auth.php
@@ -29,6 +29,7 @@ defined('MOODLE_INTERNAL') || die();
use pix_icon;
use moodle_url;
use core_text;
+use context_system;
use stdClass;
use core\oauth2\issuer;
use core\oauth2\client;
@@ -105,7 +106,7 @@ class auth extends \auth_plugin_base {
* @return bool true means automatically copy data from ext to user table
*/
public function is_synchronised_with_external() {
- return true;
+ return false;
}
/**
@@ -309,15 +310,45 @@ class auth extends \auth_plugin_base {
}
/**
- * Process the config after the form is saved.
- * @param stdClass $config
+ * Confirm the new user as registered.
+ *
+ * @param string $username
+ * @param string $confirmsecret
*/
- public function process_config($config) {
- // Set to defaults if undefined.
- if (!isset($config->allowlinkedlogins)) {
- $config->allowlinkedlogins = false;
+ function user_confirm($username, $confirmsecret) {
+ global $DB;
+ $user = get_complete_user_data('username', $username);
+
+ if (!empty($user)) {
+ if ($user->auth != $this->authtype) {
+ return AUTH_CONFIRM_ERROR;
+
+ } else if ($user->secret == $confirmsecret && $user->confirmed) {
+ return AUTH_CONFIRM_ALREADY;
+
+ } else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in
+ $DB->set_field("user", "confirmed", 1, array("id"=>$user->id));
+ return AUTH_CONFIRM_OK;
+ }
+ } else {
+ return AUTH_CONFIRM_ERROR;
}
- set_config('allowlinkedlogins', trim($config->allowlinkedlogins), 'auth_oauth2');
+ }
+
+ /**
+ * Print a page showing that a confirm email was sent with instructions.
+ *
+ * @param string title
+ * @param string message
+ */
+ public function print_confirm_required($title, $message) {
+ global $PAGE, $OUTPUT, $CFG;
+
+ $PAGE->navbar->add($title);
+ $PAGE->set_title($title);
+ $PAGE->set_heading($PAGE->course->fullname);
+ echo $OUTPUT->header();
+ notice($message, "$CFG->httpswwwroot/index.php");
}
/**
@@ -327,7 +358,7 @@ class auth extends \auth_plugin_base {
* @return none Either redirects or throws an exception
*/
public function complete_login(client $client, $redirecturl) {
- global $CFG, $SESSION;
+ global $CFG, $SESSION, $PAGE;
$userinfo = $client->get_userinfo();
@@ -336,7 +367,7 @@ class auth extends \auth_plugin_base {
$SESSION->loginerrormsg = $errormsg;
redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
}
- if (empty($userinfo['username'])) {
+ if (empty($userinfo['username']) || empty($userinfo['email'])) {
$errormsg = get_string('notloggedin', 'auth_oauth2');
$SESSION->loginerrormsg = $errormsg;
redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
@@ -344,38 +375,100 @@ class auth extends \auth_plugin_base {
$userinfo['username'] = trim(core_text::strtolower($userinfo['username']));
+ // Once we get here we have the user info from oauth.
$userwasmapped = false;
- if (get_config('auth_oauth2', 'allowlinkedlogins')) {
- $mappeduser = api::match_username_to_user($userinfo['username'], $client->get_issuer());
- if ($mappeduser) {
+ // Clean and remember the picture / lang.
+ if (!empty($userinfo['picture'])) {
+ $this->set_static_user_picture($userinfo['picture']);
+ unset($userinfo['picture']);
+ }
+
+ if (!empty($userinfo['lang'])) {
+ $userinfo['lang'] = str_replace('-', '_', trim(core_text::strtolower($userinfo['lang'])));
+ if (!get_string_manager()->translation_exists($userinfo['lang'], false)) {
+ unset($userinfo['lang']);
+ }
+ }
+
+ // First we try and find a defined mapping.
+ $linkedlogin = api::match_username_to_user($userinfo['username'], $client->get_issuer());
+
+ if (!empty($linkedlogin) && empty($linkedlogin->get('confirmtoken'))) {
+ $mappeduser = get_complete_user_data('id', $linkedlogin->get('userid'));
+
+ if ($mappeduser && $mappeduser->confirmed) {
$userinfo = (array) $mappeduser;
$userwasmapped = true;
+ } else {
+ $errormsg = get_string('confirmationpending', 'auth_oauth2');
+ $SESSION->loginerrormsg = $errormsg;
+ redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
}
+ } else if (!empty($linkedlogin)) {
+ $errormsg = get_string('confirmationpending', 'auth_oauth2');
+ $SESSION->loginerrormsg = $errormsg;
+ redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
+ }
+ $issuer = $client->get_issuer();
+ if (!$issuer->is_valid_login_domain($userinfo['email'])) {
+ $errormsg = get_string('notloggedin', 'auth_oauth2');
+ $SESSION->loginerrormsg = $errormsg;
+ redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
}
if (!$userwasmapped) {
- if (!empty($userinfo['picture'])) {
- $this->set_static_user_picture($userinfo['picture']);
- unset($userinfo['picture']);
- }
+ // No defined mapping - we need to see if there is an existing account with the same email.
- if (!empty($userinfo['lang'])) {
- $userinfo['lang'] = str_replace('-', '_', trim(core_text::strtolower($userinfo['lang'])));
- if (!get_string_manager()->translation_exists($userinfo['lang'], false)) {
- unset($userinfo['lang']);
+ $moodleuser = \core_user::get_user_by_email($userinfo['email']);
+ if (!empty($moodleuser)) {
+ $PAGE->set_url('/auth/oauth2/confirm-link-login.php');
+ $PAGE->set_context(context_system::instance());
+
+ \auth_oauth2\api::send_confirm_link_login_email($userinfo, $issuer, $moodleuser->id);
+ // Request to link to existing account.
+ $emailconfirm = get_string('emailconfirmlink', 'auth_oauth2');
+ $message = get_string('emailconfirmlinksent', 'auth_oauth2', $moodleuser->email);
+ $this->print_confirm_required($emailconfirm, $message);
+ exit();
+
+ } else {
+ // This is a new account.
+ $exists = \core_user::get_user_by_username($userinfo['username']);
+ // Creating a new user?
+ if ($exists) {
+
+ // The username exists but the emails don't match. Refuse to continue.
+ $errormsg = get_string('accountexists', 'auth_oauth2');
+ $SESSION->loginerrormsg = $errormsg;
+ redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
}
+
+ if (email_is_not_allowed($userinfo['email'])) {
+ // The username exists but the emails don't match. Refuse to continue.
+ $errormsg = get_string('emailnotallowed', 'auth_oauth2');
+ $SESSION->loginerrormsg = $errormsg;
+ redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
+ }
+
+ $PAGE->set_url('/auth/oauth2/confirm-account.php');
+ $PAGE->set_context(context_system::instance());
+
+ // Create a new (unconfirmed account) and send an email to confirm it.
+ $user = \auth_oauth2\api::send_confirm_account_email($userinfo, $issuer);
+
+ $this->update_picture($user);
+ $emailconfirm = get_string('emailconfirm');
+ $message = get_string('emailconfirmsent', '', $userinfo['email']);
+ $this->print_confirm_required($emailconfirm, $message);
+ exit();
+
}
}
- $issuer = $client->get_issuer();
-
- $user = false;
- if ($issuer->is_valid_login_domain($userinfo['email'])) {
-
- $this->set_static_user_info($userinfo);
- $user = authenticate_user_login($userinfo['username'], '');
- }
+ // If we got to here - we must have found a real user account that is confirmed.
+ $this->set_static_user_info($userinfo);
+ $user = authenticate_user_login($userinfo['username'], '');
if ($user) {
complete_user_login($user);
diff --git a/auth/oauth2/classes/linked_login.php b/auth/oauth2/classes/linked_login.php
index 7098e4ece5c..e4a56ca600b 100644
--- a/auth/oauth2/classes/linked_login.php
+++ b/auth/oauth2/classes/linked_login.php
@@ -55,6 +55,12 @@ class linked_login extends persistent {
),
'email' => array(
'type' => PARAM_RAW
+ ),
+ 'confirmtoken' => array(
+ 'type' => PARAM_RAW
+ ),
+ 'confirmtokenexpires' => array(
+ 'type' => PARAM_INT
)
);
}
diff --git a/auth/oauth2/config.html b/auth/oauth2/config.html
index b78655a748d..e7ce6066b3d 100644
--- a/auth/oauth2/config.html
+++ b/auth/oauth2/config.html
@@ -2,28 +2,8 @@
-allowlinkedlogins)) {
- $config->allowlinkedlogins = true;
-}
-?>
-
\ No newline at end of file
+
diff --git a/auth/oauth2/db/upgrade.php b/auth/oauth2/db/upgrade.php
index ca1bd5851a7..71dd0a5e1a9 100644
--- a/auth/oauth2/db/upgrade.php
+++ b/auth/oauth2/db/upgrade.php
@@ -85,5 +85,27 @@ function xmldb_auth_oauth2_upgrade($oldversion) {
upgrade_plugin_savepoint(true, 2017031000, 'auth', 'oauth2');
}
+ if ($oldversion < 2017032300) {
+
+ // Define field confirmtoken to be added to auth_oauth2_linked_login.
+ $table = new xmldb_table('auth_oauth2_linked_login');
+ $field = new xmldb_field('confirmtoken', XMLDB_TYPE_CHAR, '64', null, XMLDB_NOTNULL, null, null, 'email');
+
+ // Conditionally launch add field confirmtoken.
+ if (!$dbman->field_exists($table, $field)) {
+ $dbman->add_field($table, $field);
+ }
+
+ $field = new xmldb_field('confirmtokenexpires', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'confirmtoken');
+
+ // Conditionally launch add field confirmtokenexpires.
+ if (!$dbman->field_exists($table, $field)) {
+ $dbman->add_field($table, $field);
+ }
+
+ // Oauth2 savepoint reached.
+ upgrade_plugin_savepoint(true, 2017032300, 'auth', 'oauth2');
+ }
+
return true;
}
diff --git a/auth/oauth2/lang/en/auth_oauth2.php b/auth/oauth2/lang/en/auth_oauth2.php
index 74ee233d0c4..f4395bf4e36 100644
--- a/auth/oauth2/lang/en/auth_oauth2.php
+++ b/auth/oauth2/lang/en/auth_oauth2.php
@@ -27,13 +27,58 @@ $string['auth_oauth2settings'] = 'OAuth 2 authentication settings.';
$string['notloggedin'] = 'The login attempt failed.';
$string['plugindescription'] = 'This authentication plugin displays a list of the configured identity providers on the moodle login page. Selecting an identity provider allows users to login with their credentials from an OAuth 2 provider.';
$string['pluginname'] = 'OAuth 2';
+$string['emailconfirmlink'] = 'Link your accounts';
+$string['emailconfirmlinksent'] = '
An existing account was found with this email address but it is not linked yet.
+
The accounts must be linked before you can login.
+
An email should have been sent to your address at {$a}
+
It contains easy instructions to link your accounts.
+
If you continue to have difficulty, contact the site administrator.
';
$string['oauth2:managelinkedlogins'] = 'Manage own linked login accounts';
$string['linkedlogins'] = 'Linked logins';
+$string['accountexists'] = 'A user already exists on this site with this username. If this is your account, login manually and link this link from your preferences page.';
$string['linkedloginshelp'] = 'Help with linked logins.';
$string['notwhileloggedinas'] = 'Linked logins cannot be managed while logged in as another user.';
$string['issuer'] = 'OAuth 2 Service';
$string['info'] = 'External account';
$string['createnewlinkedlogin'] = 'Link a new account ({$a})';
+$string['confirmationpending'] = 'This account is pending email confirmation.';
+$string['emailnotallowed'] = 'The email address is not permitted at this site.';
$string['allowlinkedlogins'] = 'Allow linked logins';
$string['allowlinkedloginsdesc'] = 'Linked logins allow users to link their Moodle account to another external account which they can use to login with.';
$string['createaccountswarning'] = 'This authentication plugin allows users to create accounts on your site. You may want to enable the setting "authpreventaccountcreation" if you use this plugin.';
+$string['selfregistrationdisabled'] = 'No matching account could be found on this site, and this site does not allow self registration.';
+$string['confirmlinkedloginemail'] = 'Hi {$a->fullname},
+
+A request has been made to link the {$a->issuername} login
+{$a->linkedemail} to your account at \'{$a->sitename}\'
+using your email address.
+
+To confirm this request and link these logins, please go to this web address:
+
+{$a->link}
+
+In most mail programs, this should appear as a blue link
+which you can just click on. If that doesn\'t work,
+then cut and paste the address into the address
+line at the top of your web browser window.
+
+If you need help, please contact the site administrator,
+{$a->admin}';
+$string['confirmlinkedloginemailsubject'] = '{$a}: linked login confirmation';
+$string['confirmaccountemail'] = 'Hi {$a->fullname},
+
+A new account has been requested at \'{$a->sitename}\'
+using your email address.
+
+To confirm your new account, please go to this web address:
+
+{$a->link}
+
+In most mail programs, this should appear as a blue link
+which you can just click on. If that doesn\'t work,
+then cut and paste the address into the address
+line at the top of your web browser window.
+
+If you need help, please contact the site administrator,
+{$a->admin}';
+$string['confirmaccountemailsubject'] = '{$a}: account confirmation';
diff --git a/auth/oauth2/version.php b/auth/oauth2/version.php
index 0a014690f25..2ff2041e851 100644
--- a/auth/oauth2/version.php
+++ b/auth/oauth2/version.php
@@ -24,6 +24,6 @@
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2017031000; // The current plugin version (Date: YYYYMMDDXX).
+$plugin->version = 2017032300; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2016112900; // Requires this Moodle version.
$plugin->component = 'auth_oauth2'; // Full name of the plugin (used for diagnostics).
diff --git a/lib/classes/user.php b/lib/classes/user.php
index 8ae89dcc87e..26cb195df67 100644
--- a/lib/classes/user.php
+++ b/lib/classes/user.php
@@ -100,6 +100,29 @@ class core_user {
}
}
+ /**
+ * Return user object from db based on their email.
+ *
+ * @param string $email The email of the user searched.
+ * @param string $fields A comma separated list of user fields to be returned, support and noreply user.
+ * @param int $mnethostid The id of the remote host.
+ * @param int $strictness IGNORE_MISSING means compatible mode, false returned if user not found, debug message if more found;
+ * IGNORE_MULTIPLE means return first user, ignore multiple user records found(not recommended);
+ * MUST_EXIST means throw an exception if no user record or multiple records found.
+ * @return stdClass|bool user record if found, else false.
+ * @throws dml_exception if user record not found and respective $strictness is set.
+ */
+ public static function get_user_by_email($email, $fields = '*', $mnethostid = null, $strictness = IGNORE_MISSING) {
+ global $DB, $CFG;
+
+ // Because we use the username as the search criteria, we must also restrict our search based on mnet host.
+ if (empty($mnethostid)) {
+ // If empty, we restrict to local users.
+ $mnethostid = $CFG->mnet_localhost_id;
+ }
+
+ return $DB->get_record('user', array('email' => $email, 'mnethostid' => $mnethostid), $fields, $strictness);
+ }
/**
* Return user object from db based on their username.
From 99e3c347f961031a2c849d290c2780b0c2a69c7f Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Thu, 23 Mar 2017 16:53:07 +0800
Subject: [PATCH 44/84] MDL-58220 oauth2: Minor cleanups
Fixes spotted by Jun in peer review.
---
lib/classes/oauth2/api.php | 2 +-
lib/classes/oauth2/issuer.php | 1 +
lib/tests/oauth2_test.php | 4 ----
3 files changed, 2 insertions(+), 5 deletions(-)
diff --git a/lib/classes/oauth2/api.php b/lib/classes/oauth2/api.php
index 02320cefc1b..0c70f42e0f7 100644
--- a/lib/classes/oauth2/api.php
+++ b/lib/classes/oauth2/api.php
@@ -621,7 +621,7 @@ class api {
*
* Requires moodle/site:config capability at the system context.
*
- * @param int $id The id of the identity issuer to enable.
+ * @param int $id The id of the identity issuer to disable.
* @return boolean
*/
public static function disable_issuer($id) {
diff --git a/lib/classes/oauth2/issuer.php b/lib/classes/oauth2/issuer.php
index 3f56d7aedc1..aea47205704 100644
--- a/lib/classes/oauth2/issuer.php
+++ b/lib/classes/oauth2/issuer.php
@@ -150,6 +150,7 @@ class issuer extends persistent {
$emaildomain = $parts[1];
}
+ $emaildomain = \core_text::strtolower(trim($emaildomain));
foreach ($validdomains as $checkdomain) {
$checkdomain = \core_text::strtolower(trim($checkdomain));
diff --git a/lib/tests/oauth2_test.php b/lib/tests/oauth2_test.php
index a8b50c11449..50022826d2f 100644
--- a/lib/tests/oauth2_test.php
+++ b/lib/tests/oauth2_test.php
@@ -140,8 +140,6 @@ class core_oauth2_testcase extends advanced_testcase {
* Tests we can enable and disable an issuer.
*/
public function test_enable_disable_issuer() {
- global $SESSION;
-
$this->resetAfterTest();
$this->setAdminUser();
@@ -170,8 +168,6 @@ class core_oauth2_testcase extends advanced_testcase {
* Test the alloweddomains for an issuer.
*/
public function test_issuer_alloweddomains() {
- global $SESSION;
-
$this->resetAfterTest();
$this->setAdminUser();
From 13b449f4a56490b6cef22b976ce286c8e12ac036 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Fri, 24 Mar 2017 15:34:15 +0800
Subject: [PATCH 45/84] MDL-58220 oauth2: cibot cleanups
---
auth/oauth2/classes/api.php | 1 -
auth/oauth2/classes/auth.php | 10 +++++-----
auth/oauth2/lang/en/auth_oauth2.php | 30 ++++++++++++++---------------
lib/classes/filetypes.php | 3 ++-
lib/classes/oauth2/rest.php | 1 +
lib/filestorage/file_storage.php | 3 ++-
repository/skydrive/db/upgrade.php | 2 ++
repository/skydrive/lib.php | 1 +
8 files changed, 28 insertions(+), 23 deletions(-)
diff --git a/auth/oauth2/classes/api.php b/auth/oauth2/classes/api.php
index 58028a9f573..793fe895c66 100644
--- a/auth/oauth2/classes/api.php
+++ b/auth/oauth2/classes/api.php
@@ -131,7 +131,6 @@ class api {
* @return bool
*/
public static function send_confirm_link_login_email($userinfo, $issuer, $userid) {
-
$record = new stdClass();
$record->issuerid = $issuer->get('id');
$record->username = $userinfo['username'];
diff --git a/auth/oauth2/classes/auth.php b/auth/oauth2/classes/auth.php
index 951d8757d77..af536865861 100644
--- a/auth/oauth2/classes/auth.php
+++ b/auth/oauth2/classes/auth.php
@@ -315,7 +315,7 @@ class auth extends \auth_plugin_base {
* @param string $username
* @param string $confirmsecret
*/
- function user_confirm($username, $confirmsecret) {
+ public function user_confirm($username, $confirmsecret) {
global $DB;
$user = get_complete_user_data('username', $username);
@@ -326,8 +326,8 @@ class auth extends \auth_plugin_base {
} else if ($user->secret == $confirmsecret && $user->confirmed) {
return AUTH_CONFIRM_ALREADY;
- } else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in
- $DB->set_field("user", "confirmed", 1, array("id"=>$user->id));
+ } else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in.
+ $DB->set_field("user", "confirmed", 1, array("id" => $user->id));
return AUTH_CONFIRM_OK;
}
} else {
@@ -338,8 +338,8 @@ class auth extends \auth_plugin_base {
/**
* Print a page showing that a confirm email was sent with instructions.
*
- * @param string title
- * @param string message
+ * @param string $title
+ * @param string $message
*/
public function print_confirm_required($title, $message) {
global $PAGE, $OUTPUT, $CFG;
diff --git a/auth/oauth2/lang/en/auth_oauth2.php b/auth/oauth2/lang/en/auth_oauth2.php
index f4395bf4e36..53f850e7714 100644
--- a/auth/oauth2/lang/en/auth_oauth2.php
+++ b/auth/oauth2/lang/en/auth_oauth2.php
@@ -65,20 +65,20 @@ line at the top of your web browser window.
If you need help, please contact the site administrator,
{$a->admin}';
$string['confirmlinkedloginemailsubject'] = '{$a}: linked login confirmation';
-$string['confirmaccountemail'] = 'Hi {$a->fullname},
-
-A new account has been requested at \'{$a->sitename}\'
-using your email address.
-
-To confirm your new account, please go to this web address:
-
-{$a->link}
-
-In most mail programs, this should appear as a blue link
-which you can just click on. If that doesn\'t work,
-then cut and paste the address into the address
-line at the top of your web browser window.
-
-If you need help, please contact the site administrator,
+$string['confirmaccountemail'] = 'Hi {$a->fullname},
+
+A new account has been requested at \'{$a->sitename}\'
+using your email address.
+
+To confirm your new account, please go to this web address:
+
+{$a->link}
+
+In most mail programs, this should appear as a blue link
+which you can just click on. If that doesn\'t work,
+then cut and paste the address into the address
+line at the top of your web browser window.
+
+If you need help, please contact the site administrator,
{$a->admin}';
$string['confirmaccountemailsubject'] = '{$a}: account confirmation';
diff --git a/lib/classes/filetypes.php b/lib/classes/filetypes.php
index 23d45bde610..97ff4568271 100644
--- a/lib/classes/filetypes.php
+++ b/lib/classes/filetypes.php
@@ -104,7 +104,8 @@ abstract class core_filetypes {
'gdoc' => array('type' => 'application/vnd.google-apps.document', 'icon' => 'document', 'groups' => array('document')),
'gsheet' => array('type' => 'application/vnd.google-apps.spreadsheet', 'icon' => 'spreadsheet',
'groups' => array('spreadsheet')),
- 'gslides' => array('type' => 'application/vnd.google-apps.presentation', 'icon' => 'powerpoint', 'groups' => array('presentation')),
+ 'gslides' => array('type' => 'application/vnd.google-apps.presentation', 'icon' => 'powerpoint',
+ 'groups' => array('presentation')),
'gif' => array('type' => 'image/gif', 'icon' => 'gif', 'groups' => array('image', 'web_image'), 'string' => 'image'),
'gtar' => array('type' => 'application/x-gtar', 'icon' => 'archive',
'groups' => array('archive'), 'string' => 'archive'),
diff --git a/lib/classes/oauth2/rest.php b/lib/classes/oauth2/rest.php
index c790429c891..b4a78732999 100644
--- a/lib/classes/oauth2/rest.php
+++ b/lib/classes/oauth2/rest.php
@@ -64,6 +64,7 @@ abstract class rest {
* @param string $functionname
* @param array $functionargs
* @param string $rawpost Optional param to include in the body of a post.
+ * @return string|object
*/
public function call($functionname, $functionargs, $rawpost = false) {
$functions = $this->get_api_functions();
diff --git a/lib/filestorage/file_storage.php b/lib/filestorage/file_storage.php
index 7fd1eaaa4ac..1b26eba8860 100644
--- a/lib/filestorage/file_storage.php
+++ b/lib/filestorage/file_storage.php
@@ -1128,7 +1128,8 @@ class file_storage {
// creating a new file from an existing alias creates new alias implicitly.
// here we just check the database consistency.
if (!empty($newrecord->repositoryid)) {
- // It is OK if the current reference does not exist. It may have been altered by a repository plugin when the files where saved from a draft area.
+ // It is OK if the current reference does not exist. It may have been altered by a repository plugin when the files
+ // where saved from a draft area.
$newrecord->referencefileid = $this->get_or_create_referencefileid($newrecord->repositoryid, $newrecord->reference);
}
diff --git a/repository/skydrive/db/upgrade.php b/repository/skydrive/db/upgrade.php
index a9922abe2f1..0439640d1f1 100644
--- a/repository/skydrive/db/upgrade.php
+++ b/repository/skydrive/db/upgrade.php
@@ -17,6 +17,8 @@
defined('MOODLE_INTERNAL') || die();
/**
+ * Upgrade this plugin.
+ *
* @param int $oldversion the version we are upgrading from
* @package repository_skydrive
* @return bool result
diff --git a/repository/skydrive/lib.php b/repository/skydrive/lib.php
index 569526c58ec..d3ca1b16cf8 100644
--- a/repository/skydrive/lib.php
+++ b/repository/skydrive/lib.php
@@ -1007,6 +1007,7 @@ class repository_skydrive extends repository {
/**
* Callback to get the required scopes for system account.
*
+ * @param \core\oauth2\issuer $issuer
* @return string
*/
function repository_skydrive_oauth2_system_scopes(\core\oauth2\issuer $issuer) {
From f59d81f487d7f4189c0736fc4d1c4260e6102081 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 28 Mar 2017 09:41:33 +0800
Subject: [PATCH 46/84] MDL-58220 block_login: Update icon rendering of idp
list
---
blocks/login/block_login.php | 9 +++++++--
lib/upgrade.txt | 2 ++
2 files changed, 9 insertions(+), 2 deletions(-)
diff --git a/blocks/login/block_login.php b/blocks/login/block_login.php
index c08835d6e94..4f5fe467b50 100644
--- a/blocks/login/block_login.php
+++ b/blocks/login/block_login.php
@@ -114,8 +114,13 @@ class block_login extends block_base {
$this->content->text .= '
' . get_string('potentialidps', 'auth') . '
';
$this->content->text .= '
';
foreach ($potentialidps as $idp) {
- $this->content->text .= '
';
$this->content->text .= '';
diff --git a/lib/upgrade.txt b/lib/upgrade.txt
index 088454b38bb..3b0f4188c8b 100644
--- a/lib/upgrade.txt
+++ b/lib/upgrade.txt
@@ -1,6 +1,8 @@
This files describes API changes in core libraries and APIs,
information provided here is intended especially for developers.
=== 3.3 ===
+* The information returned by the idp list has changed. This is usually only rendered by the login page and login block.
+ The icon attribute is removed and an iconurl attribute has been added.
* Support added for a new type of external file: FILE_CONTROLLED_LINK. This is an external file that Moodle can control
the permissions. Moodle makes files read-only but can grant temporary write access.
When accessing a URL, the info from file_browser::get_file_info will be checked to determine if the user has write access,
From bfc60d386ddb6f5811f011043b4184afd118c199 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 28 Mar 2017 10:27:19 +0800
Subject: [PATCH 47/84] MDL-58220 auth_oauth: return false for non-oauth
Always return false for non-oauth logins.
---
auth/oauth2/classes/auth.php | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/auth/oauth2/classes/auth.php b/auth/oauth2/classes/auth.php
index af536865861..d3ba71c172f 100644
--- a/auth/oauth2/classes/auth.php
+++ b/auth/oauth2/classes/auth.php
@@ -73,6 +73,10 @@ class auth extends \auth_plugin_base {
*/
public function user_login($username, $password) {
$cached = $this->get_static_user_info();
+ if (empty($cached)) {
+ // This means we were called as part of a normal login flow - without using oauth.
+ return false;
+ }
$verifyusername = $cached['username'];
if ($verifyusername == $username) {
return true;
From 4a32445dc9db3e4bb368cf91911fb53adb3518e8 Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 28 Mar 2017 10:51:03 +0800
Subject: [PATCH 48/84] MDL-58220 oauth2: use PARAM_RAW_TRIMMED
Client ID and secret and copy/pasted from elsewhere so trim them.
---
lib/classes/oauth2/issuer.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/lib/classes/oauth2/issuer.php b/lib/classes/oauth2/issuer.php
index aea47205704..785d5db60f5 100644
--- a/lib/classes/oauth2/issuer.php
+++ b/lib/classes/oauth2/issuer.php
@@ -53,11 +53,11 @@ class issuer extends persistent {
'default' => null
),
'clientid' => array(
- 'type' => PARAM_RAW,
+ 'type' => PARAM_RAW_TRIMMED,
'default' => ''
),
'clientsecret' => array(
- 'type' => PARAM_RAW,
+ 'type' => PARAM_RAW_TRIMMED,
'default' => ''
),
'baseurl' => array(
From 818e789a00bbb3e31a57a073184971454eaca23b Mon Sep 17 00:00:00 2001
From: Damyon Wiese
Date: Tue, 28 Mar 2017 10:51:44 +0800
Subject: [PATCH 49/84] MDL-58220 oauth2: Remove extra step
Show create google/facebook/office365 buttons on the main page instead
of hiding them behind a click.
---
admin/tool/oauth2/issuers.php | 40 +++++++++--------------
admin/tool/oauth2/lang/en/tool_oauth2.php | 1 -
2 files changed, 15 insertions(+), 26 deletions(-)
diff --git a/admin/tool/oauth2/issuers.php b/admin/tool/oauth2/issuers.php
index 7da2c480973..1115ae21465 100644
--- a/admin/tool/oauth2/issuers.php
+++ b/admin/tool/oauth2/issuers.php
@@ -66,7 +66,6 @@ if ($mform && $mform->is_cancelled()) {
} else if ($action == 'edit') {
if ($data = $mform->get_data()) {
-
try {
if (!empty($data->id)) {
core\oauth2\api::update_issuer($data);
@@ -89,28 +88,12 @@ if ($mform && $mform->is_cancelled()) {
}
} else if ($action == 'edittemplate') {
- $type = optional_param('type', '', PARAM_ALPHA);
- if (empty($type)) {
- echo $OUTPUT->header();
- echo $OUTPUT->heading(get_string('createfromtemplate', 'tool_oauth2'));
- echo '