Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 402 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  namespace core\external;
  18  
  19  use context_course;
  20  use core\http_client;
  21  use core\moodlenet\activity_sender;
  22  use core\moodlenet\moodlenet_client;
  23  use core\moodlenet\utilities;
  24  use core\oauth2\api;
  25  use core_external\external_api;
  26  use core_external\external_function_parameters;
  27  use core_external\external_single_structure;
  28  use core_external\external_value;
  29  use core_external\external_warnings;
  30  use moodle_url;
  31  
  32  /**
  33   * The external API to send activity to MoodleNet.
  34   *
  35   * @package    core
  36   * @copyright  2023 Huong Nguyen <huongnv13@gmail.com>
  37   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  38   */
  39  class moodlenet_send_activity extends external_api {
  40  
  41      /**
  42       * Describes the parameters for sending the activity.
  43       *
  44       * @return external_function_parameters
  45       * @since Moodle 4.2
  46       */
  47      public static function execute_parameters(): external_function_parameters {
  48          return new external_function_parameters([
  49              'issuerid' => new external_value(PARAM_INT, 'OAuth 2 issuer ID', VALUE_REQUIRED),
  50              'cmid' => new external_value(PARAM_INT, 'Course module ID', VALUE_REQUIRED),
  51              'shareformat' => new external_value(PARAM_INT, 'Share format', VALUE_REQUIRED),
  52          ]);
  53      }
  54  
  55      /**
  56       * External function to send the activity to MoodleNet.
  57       *
  58       * @param int $issuerid The MoodleNet OAuth 2 issuer ID
  59       * @param int $cmid The course module ID of the activity that being shared
  60       * @param int $shareformat The share format being used, as defined by \core\moodlenet\activity_sender
  61       * @return array
  62       * @since Moodle 4.2
  63       */
  64      public static function execute(int $issuerid, int $cmid, int $shareformat): array {
  65          global $CFG, $USER;
  66  
  67          [
  68              'issuerid' => $issuerid,
  69              'cmid' => $cmid,
  70              'shareformat' => $shareformat,
  71          ] = self::validate_parameters(self::execute_parameters(), [
  72              'issuerid' => $issuerid,
  73              'cmid' => $cmid,
  74              'shareformat' => $shareformat,
  75          ]);
  76  
  77          // Check capability.
  78          [$course] = get_course_and_cm_from_cmid($cmid);
  79          $coursecontext = context_course::instance($course->id);
  80          $usercanshare = utilities::can_user_share($coursecontext, $USER->id);
  81          if (!$usercanshare) {
  82              return self::return_errors($cmid, 'errorpermission',
  83                  get_string('nopermissions', 'error', get_string('moodlenet:sharetomoodlenet', 'moodle')));
  84          }
  85  
  86          // Check format.
  87          if (!in_array($shareformat, [activity_sender::SHARE_FORMAT_BACKUP])) {
  88              return self::return_errors($shareformat, 'errorinvalidformat', get_string('invalidparameter', 'debug'));
  89          }
  90  
  91          // Get the issuer.
  92          $issuer = api::get_issuer($issuerid);
  93          // Validate the issuer and check if it is enabled or not.
  94          if (!utilities::is_valid_instance($issuer)) {
  95              return self::return_errors($issuerid, 'errorissuernotenabled', get_string('invalidparameter', 'debug'));
  96          }
  97  
  98          // Get the OAuth Client.
  99          if (!$oauthclient = api::get_user_oauth_client(
 100              $issuer,
 101              new moodle_url($CFG->wwwroot),
 102              moodlenet_client::API_SCOPE_CREATE_RESOURCE
 103          )) {
 104              return self::return_errors($issuerid, 'erroroauthclient', get_string('invalidparameter', 'debug'));
 105          }
 106  
 107          // Check login state.
 108          if (!$oauthclient->is_logged_in()) {
 109              return self::return_errors($issuerid, 'erroroauthclient', get_string('moodlenet:issuerisnotauthorized', 'moodle'));
 110          }
 111  
 112          // Get the HTTP Client.
 113          $client = new http_client();
 114  
 115          // Share activity.
 116          try {
 117              $moodlenetclient = new moodlenet_client($client, $oauthclient);
 118              $activitysender = new activity_sender($cmid, $USER->id, $moodlenetclient, $oauthclient, $shareformat);
 119              $result = $activitysender->share_activity();
 120              if (empty($result['drafturl'])) {
 121                  return self::return_errors($result['responsecode'], 'errorsendingactivity',
 122                      get_string('moodlenet:cannotconnecttoserver', 'moodle'));
 123              }
 124          } catch (\moodle_exception $e) {
 125              return self::return_errors(0, 'errorsendingactivity', $e->getMessage());
 126          }
 127  
 128          return [
 129              'status' => true,
 130              'resourceurl' => $result['drafturl'],
 131              'warnings' => [],
 132          ];
 133      }
 134  
 135      /**
 136       * Describes the data returned from the external function.
 137       *
 138       * @return external_single_structure
 139       * @since Moodle 4.2
 140       */
 141      public static function execute_returns(): external_single_structure {
 142          return new external_single_structure([
 143              'status' => new external_value(PARAM_BOOL, 'Status: true if success'),
 144              // We used PARAM_TEXT instead of PARAM_URL because the URL return from MoodleNet may contain some characters.
 145              // It does not match with PARAM_URL, but the URL still works.
 146              // Since we just show the response resource URL to the user for them to navigate to MoodleNet, it would be safe.
 147              'resourceurl' => new external_value(PARAM_TEXT, 'Resource URL from MoodleNet'),
 148              'warnings' => new external_warnings(),
 149          ]);
 150      }
 151  
 152      /**
 153       * Handle return error.
 154       *
 155       * @param int $itemid Item id
 156       * @param string $warningcode Warning code
 157       * @param string $message Message
 158       * @return array
 159       */
 160      protected static function return_errors(int $itemid, string $warningcode, string $message): array {
 161          $warnings[] = [
 162              'item' => $itemid,
 163              'warningcode' => $warningcode,
 164              'message' => $message,
 165          ];
 166  
 167          return [
 168              'status' => false,
 169              'resourceurl' => '',
 170              'warnings' => $warnings,
 171          ];
 172      }
 173  }