Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | 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
/**
18
 * Class communication
19
 *
20
 * @package    core
21
 * @copyright  2017 Marina Glancy
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
namespace core\hub;
26
defined('MOODLE_INTERNAL') || die();
27
 
28
use moodle_exception;
29
use curl;
30
use stdClass;
31
use coding_exception;
32
use moodle_url;
33
 
34
/**
35
 * Provides methods to communicate with the hub (sites directory) web services.
36
 *
37
 * @package    core
38
 * @copyright  2017 Marina Glancy
39
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40
 */
41
class api {
42
 
43
    /** @var File type: Course screenshot */
44
    const HUB_SCREENSHOT_FILE_TYPE = 'screenshot';
45
 
46
    /** @var File type: Hub screenshot */
47
    const HUB_HUBSCREENSHOT_FILE_TYPE = 'hubscreenshot';
48
 
49
    /** @var File type: Backup */
50
    const HUB_BACKUP_FILE_TYPE = 'backup';
51
 
52
    /**
53
     * Calls a remote function exposed via web services on the hub.
54
     *
55
     * @param string $function name of WS function
56
     * @param array $data parameters of WS function
57
     * @param bool $allowpublic allow request without registration on the hub
58
     * @return mixed depends on the function
59
     * @throws moodle_exception
60
     */
61
    protected static function call($function, array $data = [], $allowpublic = false) {
62
 
63
        $token = registration::get_token() ?: 'publichub';
64
        if (!$allowpublic && $token === 'publichub') {
65
            // This will throw an exception.
66
            registration::require_registration();
67
        }
68
 
69
        return self::call_rest($token, $function, $data);
70
    }
71
 
72
    /**
73
     * Performs a REST request to the hub site (using the GET method).
74
     *
75
     * @param string $token
76
     * @param string $function
77
     * @param array $data
78
     * @return mixed
79
     * @throws moodle_exception
80
     */
81
    protected static function call_rest($token, $function, array $data) {
82
        $params = [
83
                'wstoken' => $token,
84
                'wsfunction' => $function,
85
                'moodlewsrestformat' => 'json'
86
            ] + $data;
87
 
88
        $curl = new curl();
89
        $serverurl = HUB_MOODLEORGHUBURL . "/local/hub/webservice/webservices.php";
90
        $query = http_build_query($params, '', '&');
91
        $curloutput = @json_decode($curl->post($serverurl, $query), true);
92
        $info = $curl->get_info();
93
        if ($curl->get_errno()) {
94
            // Connection error.
95
            throw new moodle_exception('errorconnect', 'hub', '', $curl->error);
96
        } else if (isset($curloutput['exception'])) {
97
            // Exception occurred on the remote side.
98
            self::process_curl_exception($token, $curloutput);
1441 ariadna 99
        } else if (!empty($info['http_code']) && $info['http_code'] != 200) {
1 efrain 100
            throw new moodle_exception('errorconnect', 'hub', '', $info['http_code']);
101
        } else {
102
            return $curloutput;
103
        }
104
    }
105
 
106
    /**
107
     * Analyses exception received from the hub server.
108
     *
109
     * @param string $token token used for CURL request
110
     * @param array $curloutput output from CURL request
111
     * @throws moodle_exception
112
     */
113
    protected static function process_curl_exception($token, $curloutput) {
114
        if (!isset($curloutput['exception'])) {
115
            return;
116
        }
117
        if ($token === registration::get_token()) {
118
            // Check if registration token was rejected or there are other problems with registration.
119
            if (($curloutput['exception'] === 'moodle_exception' && $curloutput['errorcode'] === 'invalidtoken')
120
                    || $curloutput['exception'] === 'registration_exception') {
121
                // Force admin to repeat site registration process.
122
                registration::reset_token();
123
                throw new moodle_exception('errorwstokenreset', 'hub', '', $curloutput['message']);
124
            }
125
        }
126
        throw new moodle_exception('errorws', 'hub', '', $curloutput['message']);
127
    }
128
 
129
    /**
130
     * Update site registration on the hub.
131
     *
132
     * @param array $siteinfo
133
     * @throws moodle_exception
134
     */
135
    public static function update_registration(array $siteinfo) {
136
        $params = array('siteinfo' => $siteinfo, 'validateurl' => 1);
137
        self::call('hub_update_site_info', $params);
138
    }
139
 
140
    /**
141
     * Returns information about the hub.
142
     *
143
     * Example of the return array:
144
     * {
145
     *     "courses": 384,
146
     *     "description": "Official Moodle sites directory.",
147
     *     "downloadablecourses": 0,
148
     *     "enrollablecourses": 0,
149
     *     "hublogo": 1,
150
     *     "language": "en",
151
     *     "name": "moodle",
152
     *     "sites": 274175,
153
     *     "url": "https://stats.moodle.org",
154
     *     "imgurl": "https://stats.moodle.org/local/hub/webservice/download.php?filetype=hubscreenshot"
155
     * }
156
     *
157
     * @return array
158
     * @throws moodle_exception
159
     */
160
    public static function get_hub_info() {
161
        $info = self::call('hub_get_info', [], true);
162
        $info['imgurl'] = new moodle_url(HUB_MOODLEORGHUBURL . '/local/hub/webservice/download.php',
163
            ['filetype' => self::HUB_HUBSCREENSHOT_FILE_TYPE]);
164
        return $info;
165
    }
166
 
167
    /**
1441 ariadna 168
     * Checks if current site is registered in hub.
169
     *
170
     * @return bool
171
     */
172
    public static function is_site_registered_in_hub(): bool {
173
        global $CFG;
174
 
175
        return self::call('hub_site_is_registered', [
176
            'siteurl' => $CFG->wwwroot,
177
            'sitesecret' => registration::get_secret(),
178
        ]);
179
    }
180
 
181
    /**
1 efrain 182
     * Calls WS function hub_get_courses
183
     *
184
     * @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
185
     *
186
     * Parameter $options may have any of these fields:
187
     * [
188
     *     'ids' => new external_multiple_structure(new external_value(PARAM_INT, 'id of a course in the hub course
189
     *          directory'), 'ids of course', VALUE_OPTIONAL),
190
     *     'sitecourseids' => new external_multiple_structure(new external_value(PARAM_INT, 'id of a course in the
191
     *          site'), 'ids of course in the site', VALUE_OPTIONAL),
192
     *     'coverage' => new external_value(PARAM_TEXT, 'coverage', VALUE_OPTIONAL),
193
     *     'licenceshortname' => new external_value(PARAM_ALPHANUMEXT, 'licence short name', VALUE_OPTIONAL),
194
     *     'subject' => new external_value(PARAM_ALPHANUM, 'subject', VALUE_OPTIONAL),
195
     *     'audience' => new external_value(PARAM_ALPHA, 'audience', VALUE_OPTIONAL),
196
     *     'educationallevel' => new external_value(PARAM_ALPHA, 'educational level', VALUE_OPTIONAL),
197
     *     'language' => new external_value(PARAM_ALPHANUMEXT, 'language', VALUE_OPTIONAL),
198
     *     'orderby' => new external_value(PARAM_ALPHA, 'orderby method: newest, eldest, publisher, fullname,
199
     *          ratingaverage', VALUE_OPTIONAL),
200
     *     'givememore' => new external_value(PARAM_INT, 'next range of result - range size being set by the hub
201
     *          server ', VALUE_OPTIONAL),
202
     *     'allsitecourses' => new external_value(PARAM_INT,
203
     *          'if 1 return all not visible and visible courses whose siteid is the site
204
     *          matching token. Only courses of this site are returned.
205
     *          givememore parameter is ignored if this param = 1.
206
     *          In case of public token access, this param option is ignored', VALUE_DEFAULT, 0),
207
     * ]
208
     *
209
     * Each course in the returned array of courses will have fields:
210
     * [
211
     *     'id' => new external_value(PARAM_INT, 'id'),
212
     *     'fullname' => new external_value(PARAM_TEXT, 'course name'),
213
     *     'shortname' => new external_value(PARAM_TEXT, 'course short name'),
214
     *     'description' => new external_value(PARAM_TEXT, 'course description'),
215
     *     'language' => new external_value(PARAM_ALPHANUMEXT, 'course language'),
216
     *     'publishername' => new external_value(PARAM_TEXT, 'publisher name'),
217
     *     'publisheremail' => new external_value(PARAM_EMAIL, 'publisher email', VALUE_OPTIONAL),
218
     *     'privacy' => new external_value(PARAM_INT, 'privacy: published or not', VALUE_OPTIONAL),
219
     *     'sitecourseid' => new external_value(PARAM_INT, 'course id on the site', VALUE_OPTIONAL),
220
     *     'contributornames' => new external_value(PARAM_TEXT, 'contributor names', VALUE_OPTIONAL),
221
     *     'coverage' => new external_value(PARAM_TEXT, 'coverage', VALUE_OPTIONAL),
222
     *     'creatorname' => new external_value(PARAM_TEXT, 'creator name'),
223
     *     'licenceshortname' => new external_value(PARAM_ALPHANUMEXT, 'licence short name'),
224
     *     'subject' => new external_value(PARAM_ALPHANUM, 'subject'),
225
     *     'audience' => new external_value(PARAM_ALPHA, 'audience'),
226
     *     'educationallevel' => new external_value(PARAM_ALPHA, 'educational level'),
227
     *     'creatornotes' => new external_value(PARAM_RAW, 'creator notes'),
228
     *     'creatornotesformat' => new external_value(PARAM_INT, 'notes format'),
229
     *     'demourl' => new external_value(PARAM_URL, 'demo URL', VALUE_OPTIONAL),
230
     *     'courseurl' => new external_value(PARAM_URL, 'course URL', VALUE_OPTIONAL),
231
     *     'backupsize' => new external_value(PARAM_INT, 'course backup size in bytes', VALUE_OPTIONAL),
232
     *     'enrollable' => new external_value(PARAM_BOOL, 'is the course enrollable'),
233
     *     'screenshots' => new external_value(PARAM_INT, 'total number of screenshots'),
234
     *     'timemodified' => new external_value(PARAM_INT, 'time of last modification - timestamp'),
235
     *     'contents' => new external_multiple_structure(new external_single_structure(
236
     *         array(
237
     *             'moduletype' => new external_value(PARAM_ALPHA, 'the type of module (activity/block)'),
238
     *             'modulename' => new external_value(PARAM_TEXT, 'the name of the module (forum, resource etc)'),
239
     *             'contentcount' => new external_value(PARAM_INT, 'how many time the module is used in the course'),
240
     *         )), 'contents', VALUE_OPTIONAL),
241
     *     'rating' => new external_single_structure (
242
     *         array(
243
     *              'aggregate' =>  new external_value(PARAM_FLOAT, 'Rating average', VALUE_OPTIONAL),
244
     *              'scaleid' => new external_value(PARAM_INT, 'Rating scale'),
245
     *              'count' => new external_value(PARAM_INT, 'Rating count'),
246
     *         ), 'rating', VALUE_OPTIONAL),
247
     *     'comments' => new external_multiple_structure(new external_single_structure (
248
     *          array(
249
     *              'comment' => new external_value(PARAM_TEXT, 'the comment'),
250
     *              'commentator' => new external_value(PARAM_TEXT, 'the name of commentator'),
251
     *              'date' => new external_value(PARAM_INT, 'date of the comment'),
252
     *         )), 'contents', VALUE_OPTIONAL),
253
     *     'outcomes' => new external_multiple_structure(new external_single_structure(
254
     *          array(
255
     *              'fullname' => new external_value(PARAM_TEXT, 'the outcome fullname')
256
     *          )), 'outcomes', VALUE_OPTIONAL)
257
     * ]
258
     *
259
     * Additional fields for each course:
260
     *      'screenshotbaseurl' (moodle_url) URL of the first screenshot, only set if $course['screenshots']>0
261
     *      'commenturl' (moodle_url) URL for comments
262
     *
263
     * @param string $search search string
264
     * @param bool $downloadable return downloadable courses
265
     * @param bool $enrollable return enrollable courses
266
     * @param array|\stdClass $options other options from the list of allowed options:
267
     *              'ids', 'sitecourseids', 'coverage', 'licenceshortname', 'subject', 'audience',
268
     *              'educationallevel', 'language', 'orderby', 'givememore', 'allsitecourses'
269
     * @return array of two elements: [$courses, $coursetotal]
270
     * @throws \coding_exception
271
     * @throws moodle_exception
272
     */
273
    public static function get_courses($search, $downloadable, $enrollable, $options) {
274
        debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
275
        return [[], 0];
276
    }
277
 
278
    /**
279
     * Unregister the site
280
     *
281
     * @throws moodle_exception
282
     */
283
    public static function unregister_site() {
284
        global $CFG;
285
        self::call('hub_unregister_site', ['url' => [$CFG->wwwroot]]);
286
    }
287
 
288
    /**
289
     * Unpublish courses
290
     *
291
     * @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
292
     *
293
     * @param int[]|int $courseids
294
     * @throws moodle_exception
295
     */
296
    public static function unregister_courses($courseids) {
297
        debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
298
    }
299
 
300
    /**
301
     * Publish one course
302
     *
303
     * @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
304
     *
305
     * Expected contents of $courseinfo:
306
     * [
307
     *     'sitecourseid' => new external_value(PARAM_INT, 'the id of the course on the publishing site'),
308
     *     'fullname' => new external_value(PARAM_TEXT, 'course name'),
309
     *     'shortname' => new external_value(PARAM_TEXT, 'course short name'),
310
     *     'description' => new external_value(PARAM_TEXT, 'course description'),
311
     *     'language' => new external_value(PARAM_ALPHANUMEXT, 'course language'),
312
     *     'publishername' => new external_value(PARAM_TEXT, 'publisher name'),
313
     *     'publisheremail' => new external_value(PARAM_EMAIL, 'publisher email'),
314
     *     'contributornames' => new external_value(PARAM_TEXT, 'contributor names'),
315
     *     'coverage' => new external_value(PARAM_TEXT, 'coverage'),
316
     *     'creatorname' => new external_value(PARAM_TEXT, 'creator name'),
317
     *     'licenceshortname' => new external_value(PARAM_ALPHANUMEXT, 'licence short name'),
318
     *     'subject' => new external_value(PARAM_ALPHANUM, 'subject'),
319
     *     'audience' => new external_value(PARAM_ALPHA, 'audience'),
320
     *     'educationallevel' => new external_value(PARAM_ALPHA, 'educational level'),
321
     *     'creatornotes' => new external_value(PARAM_RAW, 'creator notes'),
322
     *     'creatornotesformat' => new external_value(PARAM_INT, 'notes format'),
323
     *     'demourl' => new external_value(PARAM_URL, 'demo URL', VALUE_OPTIONAL),
324
     *     'courseurl' => new external_value(PARAM_URL, 'course URL', VALUE_OPTIONAL),
325
     *     'enrollable' => new external_value(PARAM_BOOL, 'is the course enrollable', VALUE_DEFAULT, 0),
326
     *     'screenshots' => new external_value(PARAM_INT, 'the number of screenhots', VALUE_OPTIONAL),
327
     *     'deletescreenshots' => new external_value(PARAM_INT, 'ask to delete all the existing screenshot files
328
     *          (it does not reset the screenshot number)', VALUE_DEFAULT, 0),
329
     *     'contents' => new external_multiple_structure(new external_single_structure(
330
     *          array(
331
     *              'moduletype' => new external_value(PARAM_ALPHA, 'the type of module (activity/block)'),
332
     *              'modulename' => new external_value(PARAM_TEXT, 'the name of the module (forum, resource etc)'),
333
     *              'contentcount' => new external_value(PARAM_INT, 'how many time the module is used in the course'),
334
     *          )), 'contents', VALUE_OPTIONAL),
335
     *     'outcomes' => new external_multiple_structure(new external_single_structure(
336
     *         array(
337
     *              'fullname' => new external_value(PARAM_TEXT, 'the outcome fullname')
338
     *          )), 'outcomes', VALUE_OPTIONAL)
339
     * ]
340
     *
341
     * @param array|\stdClass $courseinfo
342
     * @return int id of the published course on the hub
343
     * @throws moodle_exception if the communication with the hub failed or the course could not be published
344
     */
345
    public static function register_course($courseinfo) {
346
        debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
347
        throw new moodle_exception('errorcoursewronglypublished', 'hub');
348
    }
349
 
350
    /**
351
     * Uploads a screenshot for the published course
352
     *
353
     * @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
354
     *
355
     * @param int $hubcourseid id of the published course on the hub, it must be published from this site
356
     * @param \stored_file $file
357
     * @param int $screenshotnumber ordinal number of the screenshot
358
     */
359
    public static function add_screenshot($hubcourseid, \stored_file $file, $screenshotnumber) {
360
        debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
361
    }
362
 
363
    /**
364
     * Downloads course backup
365
     *
366
     * @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
367
     *
368
     * @param int $hubcourseid id of the course on the hub
369
     * @param string $path local path (in tempdir) to save the downloaded backup to.
370
     */
371
    public static function download_course_backup($hubcourseid, $path) {
372
        debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
373
    }
374
 
375
    /**
376
     * Uploads a course backup
377
     *
378
     * @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
379
     *
380
     * @param int $hubcourseid id of the published course on the hub, it must be published from this site
381
     * @param \stored_file $backupfile
382
     */
383
    public static function upload_course_backup($hubcourseid, \stored_file $backupfile) {
384
        debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
385
    }
386
}