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
use core_external\external_api;
18
use core_external\external_multiple_structure;
19
use core_external\external_single_structure;
20
 
21
/**
22
 * Web service documentation renderer.
23
 *
24
 * @package    core_webservice
25
 * @category   output
26
 * @copyright  2009 Jerome Mouneyrac <jerome@moodle.com>
27
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28
 */
29
class core_webservice_renderer extends plugin_renderer_base {
30
 
31
    /**
32
     * Display the authorised user selector
33
     *
34
     * @param stdClass $options It contains alloweduserselector, potentialuserselector and serviceid
35
     * @return string html
36
     */
37
    public function admin_authorised_user_selector(&$options) {
38
        global $CFG;
39
        $formcontent = html_writer::empty_tag('input',
40
                        array('name' => 'sesskey', 'value' => sesskey(), 'type' => 'hidden'));
41
 
42
        $table = new html_table();
43
        $table->size = array('45%', '10%', '45%');
44
        $table->attributes['class'] = 'roleassigntable generaltable generalbox boxaligncenter';
45
        $table->summary = '';
46
        $table->cellspacing = 0;
47
        $table->cellpadding = 0;
48
 
49
        // LTR/RTL support, for drawing button arrows in the right direction
50
        if (right_to_left()) {
51
            $addarrow = 'â–¶';
52
            $removearrow = 'â—€';
53
        } else {
54
            $addarrow = 'â—€';
55
            $removearrow = 'â–¶';
56
        }
57
 
58
        //create the add and remove button
59
        $addinput = html_writer::empty_tag('input',
60
                        array('name' => 'add', 'id' => 'add', 'type' => 'submit',
61
                            'value' => $addarrow . ' ' . get_string('add'),
62
                            'title' => get_string('add')));
63
        $addbutton = html_writer::tag('div', $addinput, array('id' => 'addcontrols'));
64
        $removeinput = html_writer::empty_tag('input',
65
                        array('name' => 'remove', 'id' => 'remove', 'type' => 'submit',
66
                            'value' => $removearrow . ' ' . get_string('remove'),
67
                            'title' => get_string('remove')));
68
        $removebutton = html_writer::tag('div', $removeinput, array('id' => 'removecontrols'));
69
 
70
 
71
        //create the three cells
72
        $label = html_writer::tag('label', get_string('serviceusers', 'webservice'),
73
                        array('for' => 'removeselect'));
74
        $label = html_writer::tag('p', $label);
75
        $authoriseduserscell = new html_table_cell($label .
76
                        $options->alloweduserselector->display(true));
77
        $authoriseduserscell->id = 'existingcell';
78
        $buttonscell = new html_table_cell($addbutton . html_writer::empty_tag('br') . $removebutton);
79
        $buttonscell->id = 'buttonscell';
80
        $label = html_writer::tag('label', get_string('potusers', 'webservice'),
81
                        array('for' => 'addselect'));
82
        $label = html_writer::tag('p', $label);
83
        $otheruserscell = new html_table_cell($label .
84
                        $options->potentialuserselector->display(true));
85
        $otheruserscell->id = 'potentialcell';
86
 
87
        $cells = array($authoriseduserscell, $buttonscell, $otheruserscell);
88
        $row = new html_table_row($cells);
89
        $table->data[] = $row;
90
        $formcontent .= html_writer::table($table);
91
 
92
        $formcontent = html_writer::tag('div', $formcontent);
93
 
94
        $actionurl = new moodle_url('/' . $CFG->admin . '/webservice/service_users.php',
95
                        array('id' => $options->serviceid));
96
        $html = html_writer::tag('form', $formcontent,
97
                        array('id' => 'assignform', 'action' => $actionurl, 'method' => 'post'));
98
        return $html;
99
    }
100
 
101
    /**
102
     * Display list of authorised users for the given external service.
103
     *
104
     * @param array $users authorised users
105
     * @param int $serviceid service id
106
     * @return string $html
107
     */
108
    public function admin_authorised_user_list($users, $serviceid) {
109
        global $CFG;
110
 
111
        $listitems = [];
112
        $extrafields = \core_user\fields::get_identity_fields(context_system::instance());
113
 
114
        foreach ($users as $user) {
115
            $settingsurl = new moodle_url('/admin/webservice/service_user_settings.php',
116
                ['userid' => $user->id, 'serviceid' => $serviceid]);
117
 
118
            $identity = [];
119
            foreach ($extrafields as $extrafield) {
120
                if (isset($user->{$extrafield})) {
121
                    $identity[] = s($user->{$extrafield});
122
                }
123
            }
124
            $identity = $identity ? html_writer::div(implode(', ', $identity), 'small') : '';
125
 
126
            $link = html_writer::link($settingsurl, fullname($user));
127
 
128
            if (!empty($user->missingcapabilities)) {
129
                $count = html_writer::span(count($user->missingcapabilities), 'badge bg-danger text-white');
130
                $links = array_map(function($capname) {
131
                    return get_capability_docs_link((object)['name' => $capname]) . html_writer::div($capname, 'text-muted');
132
                }, $user->missingcapabilities);
133
                $list = html_writer::alist($links);
134
                $help = $this->output->help_icon('missingcaps', 'webservice');
135
                $missingcaps = print_collapsible_region(html_writer::div($list . $help, 'missingcaps'), 'small',
136
                    html_writer::random_id('usermissingcaps'), get_string('usermissingcaps', 'webservice', $count), '', true, true);
137
 
138
            } else {
139
                $missingcaps = '';
140
            }
141
 
142
            $listitems[] = $link . $identity . $missingcaps;
143
        }
144
 
145
        $html = html_writer::div(html_writer::alist($listitems), 'alloweduserlist');
146
 
147
        return $html;
148
    }
149
 
150
    /**
151
     * Display a confirmation page to remove a function from a service
152
     *
153
     * @param stdClass $function It needs function id + function name properties.
154
     * @param stdClass $service It needs service id + service name properties.
155
     * @return string html
156
     */
157
    public function admin_remove_service_function_confirmation($function, $service) {
158
        $optionsyes = array('id' => $service->id, 'action' => 'delete',
159
            'confirm' => 1, 'sesskey' => sesskey(), 'fid' => $function->id);
160
        $optionsno = array('id' => $service->id);
161
        $formcontinue = new single_button(new moodle_url('service_functions.php',
162
                                $optionsyes), get_string('remove'));
163
        $formcancel = new single_button(new moodle_url('service_functions.php',
164
                                $optionsno), get_string('cancel'), 'get');
165
        return $this->output->confirm(get_string('removefunctionconfirm', 'webservice',
166
                        (object) array('service' => $service->name, 'function' => $function->name)),
167
                $formcontinue, $formcancel);
168
    }
169
 
170
    /**
171
     * Display a confirmation page to remove a service
172
     *
173
     * @param stdClass $service It needs service id + service name properties.
174
     * @return string html
175
     */
176
    public function admin_remove_service_confirmation($service) {
177
        global $CFG;
178
        $optionsyes = array('id' => $service->id, 'action' => 'delete',
179
            'confirm' => 1, 'sesskey' => sesskey());
180
        $optionsno = array('section' => 'externalservices');
181
        $formcontinue = new single_button(new moodle_url('service.php', $optionsyes),
182
                        get_string('delete'), 'post');
183
        $formcancel = new single_button(
184
                        new moodle_url($CFG->wwwroot . "/" . $CFG->admin . "/settings.php", $optionsno),
185
                        get_string('cancel'), 'get');
186
        return $this->output->confirm(get_string('deleteserviceconfirm', 'webservice', $service->name),
187
                $formcontinue, $formcancel);
188
    }
189
 
190
    /**
191
     * Display a list of functions for a given service
192
     * If the service is built-in, do not display remove/add operation (read-only)
193
     *
194
     * @param array $functions list of functions
195
     * @param stdClass $service the given service
196
     * @return string the table html + add operation html
197
     */
198
    public function admin_service_function_list($functions, $service) {
199
        global $CFG;
200
        if (!empty($functions)) {
201
            $table = new html_table();
202
            $table->head = array(get_string('function', 'webservice'),
203
                get_string('description'), get_string('requiredcaps', 'webservice'));
204
            $table->align = array('left', 'left', 'left');
205
            $table->size = array('15%', '40%', '40%');
206
            $table->width = '100%';
207
            $table->align[] = 'left';
208
 
209
            //display remove function operation (except for build-in service)
210
            if (empty($service->component)) {
211
                $table->head[] = get_string('edit');
212
                $table->align[] = 'center';
213
            }
214
 
215
            $anydeprecated = false;
216
            foreach ($functions as $function) {
217
                $function = external_api::external_function_info($function);
218
 
219
                if (!empty($function->deprecated)) {
220
                    $anydeprecated = true;
221
                }
222
                $requiredcaps = html_writer::tag('div',
223
                                empty($function->capabilities) ? '' : $function->capabilities,
224
                                array('class' => 'functiondesc'));
225
                ;
226
                $description = html_writer::tag('div', $function->description,
227
                                array('class' => 'functiondesc'));
228
                //display remove function operation (except for build-in service)
229
                if (empty($service->component)) {
230
                    $removeurl = new moodle_url('/' . $CFG->admin . '/webservice/service_functions.php',
231
                                    array('sesskey' => sesskey(), 'fid' => $function->id,
232
                                        'id' => $service->id,
233
                                        'action' => 'delete'));
234
                    $removelink = html_writer::tag('a',
235
                                    get_string('removefunction', 'webservice'),
236
                                    array('href' => $removeurl));
237
                    $table->data[] = array($function->name, $description, $requiredcaps, $removelink);
238
                } else {
239
                    $table->data[] = array($function->name, $description, $requiredcaps);
240
                }
241
            }
242
 
243
            $html = html_writer::table($table);
244
        } else {
245
            $html = get_string('nofunctions', 'webservice') . html_writer::empty_tag('br');
246
        }
247
 
248
        //display add function operation (except for build-in service)
249
        if (empty($service->component)) {
250
 
251
            if (!empty($anydeprecated)) {
252
                debugging('This service uses deprecated functions, replace them by the proposed ones and update your client/s.', DEBUG_DEVELOPER);
253
            }
254
            $addurl = new moodle_url('/' . $CFG->admin . '/webservice/service_functions.php',
255
                            array('sesskey' => sesskey(), 'id' => $service->id, 'action' => 'add'));
256
            $html .= html_writer::tag('a', get_string('addfunctions', 'webservice'), array('href' => $addurl));
257
        }
258
 
259
        return $html;
260
    }
261
 
262
    /**
263
     * Display Reset token confirmation box
264
     *
265
     * @param stdClass $token token to reset
266
     * @return string html
267
     */
268
    public function user_reset_token_confirmation($token) {
269
        $managetokenurl = '/user/managetoken.php';
270
        $optionsyes = ['tokenid' => $token->id, 'action' => 'resetwstoken', 'confirm' => 1];
271
        $formcontinue = new single_button(new moodle_url($managetokenurl, $optionsyes), get_string('reset'));
272
        $formcancel = new single_button(new moodle_url($managetokenurl), get_string('cancel'), 'get');
273
        $html = $this->output->confirm(get_string('resettokenconfirm', 'webservice',
274
                                (object) array('user' => $token->firstname . " " .
275
                                    $token->lastname, 'service' => $token->name)),
276
                        $formcontinue, $formcancel);
277
        return $html;
278
    }
279
 
280
    /**
281
     * Display user tokens with buttons to reset them
282
     *
283
     * @param stdClass $tokens user tokens
284
     * @param int $userid user id
285
     * @param bool $documentation if true display a link to the API documentation
286
     * @return string html code
287
     */
288
    public function user_webservice_tokens_box($tokens, $userid, $documentation = false) {
289
        global $CFG, $DB;
290
 
291
        // display strings
292
        $stroperation = get_string('operation', 'webservice');
293
        $strtoken = get_string('tokenname', 'webservice');
294
        $strservice = get_string('service', 'webservice');
295
        $strcreator = get_string('tokencreator', 'webservice');
296
        $strvaliduntil = get_string('validuntil', 'webservice');
297
        $strlastaccess = get_string('lastaccess');
298
 
299
        $return = $this->output->heading(get_string('securitykeys', 'webservice'), 3, 'main', true);
300
        $return .= $this->output->box_start('generalbox webservicestokenui');
301
 
302
        $return .= get_string('keyshelp', 'webservice');
303
 
304
        $table = new html_table();
305
        $table->head = array($strtoken, $strservice, $strvaliduntil, $strlastaccess, $strcreator, $stroperation);
306
        $table->align = array('left', 'left', 'left', 'center', 'center', 'left', 'center');
307
        $table->width = '100%';
308
        $table->data = array();
309
 
310
        if ($documentation) {
311
            $table->head[] = get_string('doc', 'webservice');
312
            $table->align[] = 'center';
313
        }
314
 
315
        if (!empty($tokens)) {
316
            foreach ($tokens as $token) {
317
 
318
                if ($token->creatorid == $userid) {
319
                    $reset = html_writer::link(new moodle_url('/user/managetoken.php', [
320
                        'action' => 'resetwstoken',
321
                        'tokenid' => $token->id,
322
                    ]), get_string('reset'));
323
                    $creator = $token->firstname . " " . $token->lastname;
324
                } else {
325
                    //retrieve administrator name
326
                    $admincreator = $DB->get_record('user', array('id'=>$token->creatorid));
327
                    $creator = $admincreator->firstname . " " . $admincreator->lastname;
328
                    $reset = '';
329
                }
330
 
331
                $userprofilurl = new moodle_url('/user/view.php?id=' . $token->creatorid);
332
                $creatoratag = html_writer::start_tag('a', array('href' => $userprofilurl));
333
                $creatoratag .= $creator;
334
                $creatoratag .= html_writer::end_tag('a');
335
 
336
                $validuntil = '';
337
                if (!empty($token->validuntil)) {
338
                    $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
339
                }
340
 
341
                $lastaccess = '';
342
                if (!empty($token->lastaccess)) {
343
                    $lastaccess = userdate($token->lastaccess, get_string('strftimedatetime', 'langconfig'));
344
                }
345
 
346
                $servicename = $token->servicename;
347
                if (!$token->enabled) { // That is the (1 token-1ws) related ws is not enabled.
348
                    $servicename = '<span class="dimmed_text">'.$token->servicename.'</span>';
349
                }
350
                $row = array($token->tokenname, $servicename, $validuntil, $lastaccess, $creatoratag, $reset);
351
 
352
                if ($documentation) {
353
                    $doclink = new moodle_url('/webservice/wsdoc.php',
354
                            array('id' => $token->id));
355
                    $row[] = html_writer::tag('a', get_string('doc', 'webservice'),
356
                            array('href' => $doclink));
357
                }
358
 
359
                $table->data[] = $row;
360
            }
361
            $return .= html_writer::table($table);
362
        } else {
363
            $return .= get_string('notoken', 'webservice');
364
        }
365
 
366
        $return .= $this->output->box_end();
367
        return $return;
368
    }
369
 
370
    /**
371
     * Return documentation for a ws description object
372
     * ws description object can be 'external_multiple_structure', 'external_single_structure'
373
     * or 'external_value'
374
     *
375
     * Example of documentation for core_group_create_groups function:
376
     * list of (
377
     *     object {
378
     *         courseid int //id of course
379
     *         name string //multilang compatible name, course unique
380
     *         description string //group description text
381
     *         enrolmentkey string //group enrol secret phrase
382
     *     }
383
     * )
384
     *
385
     * @param stdClass $params a part of parameter/return description
386
     * @return string the html to display
387
     */
388
    public function detailed_description_html($params) {
389
        // retrieve the description of the description object
390
        $paramdesc = "";
391
        if (!empty($params->desc)) {
392
            $paramdesc .= html_writer::start_tag('span', array('style' => "color:#2A33A6"));
393
            if ($params->required == VALUE_REQUIRED) {
394
                $required = '';
395
            }
396
            if ($params->required == VALUE_DEFAULT) {
397
                if ($params->default === null) {
398
                    $params->default = "null";
399
                }
400
                $required = html_writer::start_tag('b', array()) .
401
                        get_string('default', 'webservice', print_r($params->default, true))
402
                        . html_writer::end_tag('b');
403
            }
404
            if ($params->required == VALUE_OPTIONAL) {
405
                $required = html_writer::start_tag('b', array()) .
406
                        get_string('optional', 'webservice') . html_writer::end_tag('b');
407
            }
408
            $paramdesc .= " " . $required . " ";
409
            $paramdesc .= html_writer::start_tag('i', array());
410
            $paramdesc .= "//";
411
 
412
            $paramdesc .= s($params->desc);
413
 
414
            $paramdesc .= html_writer::end_tag('i');
415
 
416
            $paramdesc .= html_writer::end_tag('span');
417
            $paramdesc .= html_writer::empty_tag('br', array());
418
        }
419
 
420
        // description object is a list
421
        if ($params instanceof external_multiple_structure) {
422
            return $paramdesc . "list of ( " . html_writer::empty_tag('br', array())
423
            . $this->detailed_description_html($params->content) . ")";
424
        } else if ($params instanceof external_single_structure) {
425
            // description object is an object
426
            $singlestructuredesc = $paramdesc . "object {" . html_writer::empty_tag('br', array());
427
            foreach ($params->keys as $attributname => $attribut) {
428
                $singlestructuredesc .= html_writer::start_tag('b', array());
429
                $singlestructuredesc .= $attributname;
430
                $singlestructuredesc .= html_writer::end_tag('b');
431
                $singlestructuredesc .= " " .
432
                        $this->detailed_description_html($params->keys[$attributname]);
433
            }
434
            $singlestructuredesc .= "} ";
435
            $singlestructuredesc .= html_writer::empty_tag('br', array());
436
            return $singlestructuredesc;
437
        } else {
438
            // description object is a primary type (string, integer)
439
            switch ($params->type) {
440
                case PARAM_BOOL: // 0 or 1 only for now
441
                case PARAM_INT:
442
                    $type = 'int';
443
                    break;
444
                case PARAM_FLOAT;
445
                    $type = 'double';
446
                    break;
447
                default:
448
                    $type = 'string';
449
            }
450
            return $type . " " . $paramdesc;
451
        }
452
    }
453
 
454
    /**
455
     * Return a description object in indented xml format (for REST response)
456
     * It is indented to be output within <pre> tags
457
     *
458
     * @param external_description $returndescription the description structure of the web service function returned value
459
     * @param string $indentation Indentation in the generated HTML code; should contain only spaces.
460
     * @return string the html to diplay
461
     */
462
    public function description_in_indented_xml_format($returndescription, $indentation = "") {
463
        $indentation = $indentation . "    ";
464
        $brakeline = <<<EOF
465
 
466
 
467
EOF;
468
        // description object is a list
469
        if ($returndescription instanceof external_multiple_structure) {
470
            $return = $indentation . "<MULTIPLE>" . $brakeline;
471
            $return .= $this->description_in_indented_xml_format($returndescription->content,
472
                            $indentation);
473
            $return .= $indentation . "</MULTIPLE>" . $brakeline;
474
            return $return;
475
        } else if ($returndescription instanceof external_single_structure) {
476
            // description object is an object
477
            $singlestructuredesc = $indentation . "<SINGLE>" . $brakeline;
478
            $keyindentation = $indentation . "    ";
479
            foreach ($returndescription->keys as $attributname => $attribut) {
480
                $singlestructuredesc .= $keyindentation . "<KEY name=\"" . $attributname . "\">"
481
                        . $brakeline .
482
                        $this->description_in_indented_xml_format(
483
                                $returndescription->keys[$attributname], $keyindentation) .
484
                        $keyindentation . "</KEY>" . $brakeline;
485
            }
486
            $singlestructuredesc .= $indentation . "</SINGLE>" . $brakeline;
487
            return $singlestructuredesc;
488
        } else {
489
            // description object is a primary type (string, integer)
490
            switch ($returndescription->type) {
491
                case PARAM_BOOL: // 0 or 1 only for now
492
                case PARAM_INT:
493
                    $type = 'int';
494
                    break;
495
                case PARAM_FLOAT;
496
                    $type = 'double';
497
                    break;
498
                default:
499
                    $type = 'string';
500
            }
501
            return $indentation . "<VALUE>" . $type . "</VALUE>" . $brakeline;
502
        }
503
    }
504
 
505
    /**
506
     * Create indented XML-RPC  param description
507
     *
508
     * @todo MDL-76078 - Incorrect inter-communication, core cannot have plugin dependencies like this.
509
     *
510
     * @param external_description $paramdescription the description structure of the web service function parameters
511
     * @param string $indentation Indentation in the generated HTML code; should contain only spaces.
512
     * @return string the html to diplay
513
     */
514
    public function xmlrpc_param_description_html($paramdescription, $indentation = "") {
515
        $indentation = $indentation . "    ";
516
        $brakeline = <<<EOF
517
 
518
 
519
EOF;
520
        // description object is a list
521
        if ($paramdescription instanceof external_multiple_structure) {
522
            $return = $brakeline . $indentation . "Array ";
523
            $indentation = $indentation . "    ";
524
            $return .= $brakeline . $indentation . "(";
525
            $return .= $brakeline . $indentation . "[0] =>";
526
            $return .= $this->xmlrpc_param_description_html($paramdescription->content, $indentation);
527
            $return .= $brakeline . $indentation . ")";
528
            return $return;
529
        } else if ($paramdescription instanceof external_single_structure) {
530
            // description object is an object
531
            $singlestructuredesc = $brakeline . $indentation . "Array ";
532
            $keyindentation = $indentation . "    ";
533
            $singlestructuredesc .= $brakeline . $keyindentation . "(";
534
            foreach ($paramdescription->keys as $attributname => $attribut) {
535
                $singlestructuredesc .= $brakeline . $keyindentation . "[" . $attributname . "] =>" .
536
                        $this->xmlrpc_param_description_html(
537
                                $paramdescription->keys[$attributname], $keyindentation) .
538
                        $keyindentation;
539
            }
540
            $singlestructuredesc .= $brakeline . $keyindentation . ")";
541
            return $singlestructuredesc;
542
        } else {
543
            // description object is a primary type (string, integer)
544
            switch ($paramdescription->type) {
545
                case PARAM_BOOL: // 0 or 1 only for now
546
                case PARAM_INT:
547
                    $type = 'int';
548
                    break;
549
                case PARAM_FLOAT;
550
                    $type = 'double';
551
                    break;
552
                default:
553
                    $type = 'string';
554
            }
555
            return " " . $type;
556
        }
557
    }
558
 
559
    /**
560
     * Return the html of a coloured box with content
561
     *
562
     * @param string $title - the title of the box
563
     * @param string $content - the content to displayed
564
     * @param string $rgb - the background color of the box
565
     * @return string HTML code
566
     */
567
    public function colored_box_with_pre_tag($title, $content, $rgb = 'FEEBE5') {
568
        $coloredbox = html_writer::start_tag('div', array());
569
        $coloredbox .= html_writer::start_tag('div',
570
                        array('style' => "border:solid 1px #DEDEDE;background:#" . $rgb
571
                            . ";color:#222222;padding:4px;"));
572
        $coloredbox .= html_writer::start_tag('pre', array());
573
        $coloredbox .= html_writer::start_tag('b', array());
574
        $coloredbox .= $title;
575
        $coloredbox .= html_writer::end_tag('b', array());
576
        $coloredbox .= html_writer::empty_tag('br', array());
577
        $coloredbox .= "\n" . $content . "\n";
578
        $coloredbox .= html_writer::end_tag('pre', array());
579
        $coloredbox .= html_writer::end_tag('div', array());
580
        $coloredbox .= html_writer::end_tag('div', array());
581
        return $coloredbox;
582
    }
583
 
584
    /**
585
     * Return indented REST param description
586
     *
587
     * @todo MDL-76078 - Incorrect inter-communication, core cannot have plugin dependencies like this.
588
     *
589
     * @param external_description $paramdescription the description structure of the web service function parameters
590
     * @param string $paramstring parameter
591
     * @return string the html to diplay
592
     */
593
    public function rest_param_description_html($paramdescription, $paramstring) {
594
        $brakeline = <<<EOF
595
 
596
 
597
EOF;
598
        // description object is a list
599
        if ($paramdescription instanceof external_multiple_structure) {
600
            $paramstring = $paramstring . '[0]';
601
            $return = $this->rest_param_description_html($paramdescription->content, $paramstring);
602
            return $return;
603
        } else if ($paramdescription instanceof external_single_structure) {
604
            // description object is an object
605
            $singlestructuredesc = "";
606
            $initialparamstring = $paramstring;
607
            foreach ($paramdescription->keys as $attributname => $attribut) {
608
                $paramstring = $initialparamstring . '[' . $attributname . ']';
609
                $singlestructuredesc .= $this->rest_param_description_html(
610
                                $paramdescription->keys[$attributname], $paramstring);
611
            }
612
            return $singlestructuredesc;
613
        } else {
614
            // description object is a primary type (string, integer)
615
            $paramstring = $paramstring . '=';
616
            switch ($paramdescription->type) {
617
                case PARAM_BOOL: // 0 or 1 only for now
618
                case PARAM_INT:
619
                    $type = 'int';
620
                    break;
621
                case PARAM_FLOAT;
622
                    $type = 'double';
623
                    break;
624
                default:
625
                    $type = 'string';
626
            }
627
            return $paramstring . " " . $type . $brakeline;
628
        }
629
    }
630
 
631
    /**
632
     * Displays all the documentation
633
     *
634
     * @todo MDL-76078 - Incorrect inter-communication, core cannot have plugin dependencies like this.
635
     *
636
     * @param array $functions external_description of all the web service functions
637
     * @param boolean $printableformat true if we want to display the documentation in a printable format
638
     * @param array $activatedprotocol the currently enabled protocol
639
     * @param array $authparams url parameters (it contains 'tokenid' and sometimes 'print')
640
     * @param string $parenturl url of the calling page - needed for the print button url:
641
     *               '/admin/documentation.php' or '/webservice/wsdoc.php' (default)
642
     * @return string the html to diplay
643
     */
644
    public function documentation_html($functions, $printableformat, $activatedprotocol,
645
            $authparams, $parenturl = '/webservice/wsdoc.php') {
646
 
647
        $documentationhtml = $this->output->heading(get_string('wsdocapi', 'webservice'));
648
 
649
        $br = html_writer::empty_tag('br', array());
650
        $brakeline = <<<EOF
651
 
652
 
653
EOF;
654
        // Some general information
655
        $docinfo = new stdClass();
656
        $docurl = new moodle_url('http://docs.moodle.org/dev/Creating_a_web_service_client');
657
        $docinfo->doclink = html_writer::tag('a',
658
                        get_string('wsclientdoc', 'webservice'), array('href' => $docurl));
659
        $documentationhtml .= get_string('wsdocumentationintro', 'webservice', $docinfo);
660
        $documentationhtml .= $br . $br;
661
 
662
 
663
        // Print button
664
        $authparams['print'] = true;
665
        $url = new moodle_url($parenturl, $authparams); // Required
666
        $documentationhtml .= $this->output->single_button($url, get_string('print', 'webservice'));
667
        $documentationhtml .= $br;
668
 
669
 
670
        // each functions will be displayed into a collapsible region
671
        //(opened if printableformat = true)
672
        foreach ($functions as $functionname => $description) {
673
 
674
            $tags = '';
675
            if (!empty($description->deprecated)) {
676
                $tags .= ' ' . html_writer::span(get_string('deprecated', 'core_webservice'), 'badge bg-warning text-dark');
677
            }
678
 
679
            if (empty($printableformat)) {
680
                $documentationhtml .= print_collapsible_region_start('',
681
                                'aera_' . $functionname,
682
                                html_writer::start_tag('strong', array())
683
                                . $functionname . html_writer::end_tag('strong') . $tags,
684
                                false,
685
                                !$printableformat,
686
                                true);
687
            } else {
688
                $documentationhtml .= html_writer::tag('strong', $functionname) . $tags;
689
                $documentationhtml .= $br;
690
            }
691
 
692
            // function global description
693
            $documentationhtml .= $br;
694
            $documentationhtml .= html_writer::start_tag('div',
695
                            array('style' => 'border:solid 1px #DEDEDE;background:#E2E0E0;
696
                        color:#222222;padding:4px;'));
697
            $documentationhtml .= s($description->description);
698
            $documentationhtml .= html_writer::end_tag('div');
699
            $documentationhtml .= $br . $br;
700
 
701
            // function arguments documentation
702
            $documentationhtml .= html_writer::start_tag('span', array('style' => 'color:#EA33A6'));
703
            $documentationhtml .= get_string('arguments', 'webservice');
704
            $documentationhtml .= html_writer::end_tag('span');
705
            $documentationhtml .= $br;
706
            foreach ($description->parameters_desc->keys as $paramname => $paramdesc) {
707
                // a argument documentation
11 efrain 708
                $documentationhtml .= html_writer::start_tag('div', ['style' => 'font-size:80%']);
1 efrain 709
 
710
                if ($paramdesc->required == VALUE_REQUIRED) {
711
                    $required = get_string('required', 'webservice');
712
                }
713
                if ($paramdesc->required == VALUE_DEFAULT) {
714
                    if ($paramdesc->default === null) {
715
                        $default = "null";
716
                    } else {
717
                        $default = print_r($paramdesc->default, true);
718
                    }
719
                    $required = get_string('default', 'webservice', $default);
720
                }
721
                if ($paramdesc->required == VALUE_OPTIONAL) {
722
                    $required = get_string('optional', 'webservice');
723
                }
724
 
725
                $documentationhtml .= html_writer::start_tag('b', array());
726
                $documentationhtml .= $paramname;
727
                $documentationhtml .= html_writer::end_tag('b');
728
                $documentationhtml .= " (" . $required . ")"; // argument is required or optional ?
729
                $documentationhtml .= $br;
730
                $documentationhtml .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
731
                        . s($paramdesc->desc); // Argument description.
732
                $documentationhtml .= $br . $br;
733
                // general structure of the argument
734
                $documentationhtml .= $this->colored_box_with_pre_tag(
735
                                get_string('generalstructure', 'webservice'),
736
                                $this->detailed_description_html($paramdesc),
737
                                'FFF1BC');
738
                // xml-rpc structure of the argument in PHP format
739
                if (!empty($activatedprotocol['xmlrpc'])) {
740
                    $documentationhtml .= $this->colored_box_with_pre_tag(
741
                                    get_string('phpparam', 'webservice'),
742
                                    htmlentities('[' . $paramname . '] =>'
743
                                            . $this->xmlrpc_param_description_html($paramdesc), ENT_COMPAT),
744
                                    'DFEEE7');
745
                }
746
                // POST format for the REST protocol for the argument
747
                if (!empty($activatedprotocol['rest'])) {
748
                    $documentationhtml .= $this->colored_box_with_pre_tag(
749
                                    get_string('restparam', 'webservice'),
750
                                    htmlentities($this->rest_param_description_html(
751
                                                    $paramdesc, $paramname), ENT_COMPAT),
752
                                    'FEEBE5');
753
                }
11 efrain 754
                $documentationhtml .= html_writer::end_tag('div');
1 efrain 755
            }
756
            $documentationhtml .= $br . $br;
757
 
758
 
759
            // function response documentation
760
            $documentationhtml .= html_writer::start_tag('span', array('style' => 'color:#EA33A6'));
761
            $documentationhtml .= get_string('response', 'webservice');
762
            $documentationhtml .= html_writer::end_tag('span');
763
            $documentationhtml .= $br;
764
            // function response description
11 efrain 765
            $documentationhtml .= html_writer::start_tag('div', ['style' => 'font-size:80%']);
1 efrain 766
            if (!empty($description->returns_desc->desc)) {
767
                $documentationhtml .= $description->returns_desc->desc;
768
                $documentationhtml .= $br . $br;
769
            }
770
            if (!empty($description->returns_desc)) {
771
                // general structure of the response
772
                $documentationhtml .= $this->colored_box_with_pre_tag(
773
                                get_string('generalstructure', 'webservice'),
774
                                $this->detailed_description_html($description->returns_desc),
775
                                'FFF1BC');
776
                // xml-rpc structure of the response in PHP format
777
                if (!empty($activatedprotocol['xmlrpc'])) {
778
                    $documentationhtml .= $this->colored_box_with_pre_tag(
779
                                    get_string('phpresponse', 'webservice'),
780
                                    htmlentities($this->xmlrpc_param_description_html(
781
                                                    $description->returns_desc), ENT_COMPAT),
782
                                    'DFEEE7');
783
                }
784
                // XML response for the REST protocol
785
                if (!empty($activatedprotocol['rest'])) {
786
                    $restresponse = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
787
                            . $brakeline . "<RESPONSE>" . $brakeline;
788
                    $restresponse .= $this->description_in_indented_xml_format(
789
                                    $description->returns_desc);
790
                    $restresponse .="</RESPONSE>" . $brakeline;
791
                    $documentationhtml .= $this->colored_box_with_pre_tag(
792
                                    get_string('restcode', 'webservice'),
793
                                    htmlentities($restresponse, ENT_COMPAT),
794
                                    'FEEBE5');
795
                }
796
            }
11 efrain 797
            $documentationhtml .= html_writer::end_tag('div');
1 efrain 798
            $documentationhtml .= $br . $br;
799
 
800
            // function errors documentation for REST protocol
801
            if (!empty($activatedprotocol['rest'])) {
802
                $documentationhtml .= html_writer::start_tag('span', array('style' => 'color:#EA33A6'));
803
                $documentationhtml .= get_string('errorcodes', 'webservice');
804
                $documentationhtml .= html_writer::end_tag('span');
805
                $documentationhtml .= $br . $br;
11 efrain 806
                $documentationhtml .= html_writer::start_tag('div', ['style' => 'font-size:80%']);
1 efrain 807
                $errormessage = get_string('invalidparameter', 'debug');
808
                $restexceptiontext = <<<EOF
809
<?xml version="1.0" encoding="UTF-8"?>
810
<EXCEPTION class="invalid_parameter_exception">
811
    <MESSAGE>{$errormessage}</MESSAGE>
812
    <DEBUGINFO></DEBUGINFO>
813
</EXCEPTION>
814
EOF;
815
                $documentationhtml .= $this->colored_box_with_pre_tag(
816
                                get_string('restexception', 'webservice'),
817
                                htmlentities($restexceptiontext, ENT_COMPAT),
818
                                'FEEBE5');
819
 
11 efrain 820
                $documentationhtml .= html_writer::end_tag('div');
1 efrain 821
            }
822
            $documentationhtml .= $br . $br;
823
 
824
            // Login required info.
825
            $documentationhtml .= html_writer::start_tag('span', array('style' => 'color:#EA33A6'));
826
            $documentationhtml .= get_string('loginrequired', 'webservice') . $br;
827
            $documentationhtml .= html_writer::end_tag('span');
828
            $documentationhtml .= $description->loginrequired ? get_string('yes') : get_string('no');
829
            $documentationhtml .= $br . $br;
830
 
831
            // Ajax info.
832
            $documentationhtml .= html_writer::start_tag('span', array('style' => 'color:#EA33A6'));
833
            $documentationhtml .= get_string('callablefromajax', 'webservice') . $br;
834
            $documentationhtml .= html_writer::end_tag('span');
835
            $documentationhtml .= $description->allowed_from_ajax ? get_string('yes') : get_string('no');
836
            $documentationhtml .= $br . $br;
837
 
838
            if (empty($printableformat)) {
839
                $documentationhtml .= print_collapsible_region_end(true);
840
            }
841
        }
842
 
843
        return $documentationhtml;
844
    }
845
 
846
}