Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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\moodlenet\share_recorder;
25
use core\oauth2\api;
26
use core_external\external_api;
27
use core_external\external_function_parameters;
28
use core_external\external_single_structure;
29
use core_external\external_value;
30
use core_external\external_warnings;
31
use moodle_url;
32
 
33
/**
34
 * The external API to send activity to MoodleNet.
35
 *
36
 * @package    core
37
 * @copyright  2023 Huong Nguyen <huongnv13@gmail.com>
38
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39
 */
40
class moodlenet_send_activity extends external_api {
41
 
42
    /**
43
     * Describes the parameters for sending the activity.
44
     *
45
     * @return external_function_parameters
46
     * @since Moodle 4.2
47
     */
48
    public static function execute_parameters(): external_function_parameters {
49
        return new external_function_parameters([
50
            'issuerid' => new external_value(PARAM_INT, 'OAuth 2 issuer ID', VALUE_REQUIRED),
51
            'cmid' => new external_value(PARAM_INT, 'Course module ID', VALUE_REQUIRED),
52
            'shareformat' => new external_value(PARAM_INT, 'Share format', VALUE_REQUIRED),
53
        ]);
54
    }
55
 
56
    /**
57
     * External function to send the activity to MoodleNet.
58
     *
59
     * @param int $issuerid The MoodleNet OAuth 2 issuer ID
60
     * @param int $cmid The course module ID of the activity that being shared
61
     * @param int $shareformat The share format being used, as defined by \core\moodlenet\activity_sender
62
     * @return array
63
     * @since Moodle 4.2
64
     */
65
    public static function execute(int $issuerid, int $cmid, int $shareformat): array {
66
        global $CFG, $USER;
67
 
68
        [
69
            'issuerid' => $issuerid,
70
            'cmid' => $cmid,
71
            'shareformat' => $shareformat,
72
        ] = self::validate_parameters(self::execute_parameters(), [
73
            'issuerid' => $issuerid,
74
            'cmid' => $cmid,
75
            'shareformat' => $shareformat,
76
        ]);
77
 
78
        // Check capability.
79
        [$course] = get_course_and_cm_from_cmid($cmid);
80
        $coursecontext = context_course::instance($course->id);
81
        $usercanshare = utilities::can_user_share($coursecontext, $USER->id);
82
        if (!$usercanshare) {
83
            return self::return_errors($cmid, 'errorpermission',
84
                get_string('nopermissions', 'error', get_string('moodlenet:sharetomoodlenet', 'moodle')));
85
        }
86
 
87
        // Check format.
88
        if (!in_array($shareformat, [activity_sender::SHARE_FORMAT_BACKUP])) {
89
            return self::return_errors($shareformat, 'errorinvalidformat', get_string('invalidparameter', 'debug'));
90
        }
91
 
92
        // Get the issuer.
93
        $issuer = api::get_issuer($issuerid);
94
        // Validate the issuer and check if it is enabled or not.
95
        if (!utilities::is_valid_instance($issuer)) {
96
            return self::return_errors($issuerid, 'errorissuernotenabled', get_string('invalidparameter', 'debug'));
97
        }
98
 
99
        // Get the OAuth Client.
100
        if (!$oauthclient = api::get_user_oauth_client(
101
            $issuer,
102
            new moodle_url($CFG->wwwroot),
103
            moodlenet_client::API_SCOPE_CREATE_RESOURCE
104
        )) {
105
            return self::return_errors($issuerid, 'erroroauthclient', get_string('invalidparameter', 'debug'));
106
        }
107
 
108
        // Check login state.
109
        if (!$oauthclient->is_logged_in()) {
110
            return self::return_errors($issuerid, 'erroroauthclient', get_string('moodlenet:issuerisnotauthorized', 'moodle'));
111
        }
112
 
113
        // Get the HTTP Client.
114
        $client = new http_client();
115
 
116
        // Share activity.
117
        try {
118
            // Record activity share progress.
119
            $shareid = share_recorder::insert_share_progress(share_recorder::TYPE_ACTIVITY, $USER->id, $course->id, $cmid);
120
 
121
            $moodlenetclient = new moodlenet_client($client, $oauthclient);
122
            $activitysender = new activity_sender($cmid, $USER->id, $moodlenetclient, $oauthclient, $shareformat);
123
            $result = $activitysender->share_resource();
124
            if (empty($result['drafturl'])) {
125
 
126
                share_recorder::update_share_progress($shareid, share_recorder::STATUS_ERROR);
127
 
128
                return self::return_errors($result['responsecode'], 'errorsendingactivity',
129
                    get_string('moodlenet:cannotconnecttoserver', 'moodle'));
130
            }
131
        } catch (\moodle_exception $e) {
132
 
133
            share_recorder::update_share_progress($shareid, share_recorder::STATUS_ERROR);
134
 
135
            return self::return_errors(0, 'errorsendingactivity', $e->getMessage());
136
        }
137
 
138
        share_recorder::update_share_progress($shareid, share_recorder::STATUS_SENT, $result['drafturl']);
139
 
140
        return [
141
            'status' => true,
142
            'resourceurl' => $result['drafturl'],
143
            'warnings' => [],
144
        ];
145
    }
146
 
147
    /**
148
     * Describes the data returned from the external function.
149
     *
150
     * @return external_single_structure
151
     * @since Moodle 4.2
152
     */
153
    public static function execute_returns(): external_single_structure {
154
        return new external_single_structure([
155
            'status' => new external_value(PARAM_BOOL, 'Status: true if success'),
156
            // We used PARAM_TEXT instead of PARAM_URL because the URL return from MoodleNet may contain some characters.
157
            // It does not match with PARAM_URL, but the URL still works.
158
            // Since we just show the response resource URL to the user for them to navigate to MoodleNet, it would be safe.
159
            'resourceurl' => new external_value(PARAM_TEXT, 'Resource URL from MoodleNet'),
160
            'warnings' => new external_warnings(),
161
        ]);
162
    }
163
 
164
    /**
165
     * Handle return error.
166
     *
167
     * @param int $itemid Item id
168
     * @param string $warningcode Warning code
169
     * @param string $message Message
170
     * @return array
171
     */
172
    protected static function return_errors(int $itemid, string $warningcode, string $message): array {
173
        $warnings[] = [
174
            'item' => $itemid,
175
            'warningcode' => $warningcode,
176
            'message' => $message,
177
        ];
178
 
179
        return [
180
            'status' => false,
181
            'resourceurl' => '',
182
            'warnings' => $warnings,
183
        ];
184
    }
185
}