MDL-30126 rest client should be updated fo json support
[moodle.git] / webservice / rest / lib.php
CommitLineData
75681c41 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Moodle REST client class
20 * TODO: XML to PHP
21 */
22class webservice_rest_client {
23
db7c80d9 24 /** @var moodle_url the REST server url */
75681c41 25 private $serverurl;
db7c80d9 26
75681c41 27 private $token;
db7c80d9 28 private $format;
75681c41 29
30 /**
31 * Constructor
32 * @param string $serverurl a Moodle URL
33 * @param string $token
34 */
db7c80d9
JM
35 public function __construct($serverurl, $token, $format = 'xml') {
36 $this->serverurl = new moodle_url($serverurl);
75681c41 37 $this->token = $token;
db7c80d9 38 $this->format = $format;
75681c41 39 }
40
41 /**
42 * Set the token used to do the REST call
43 * @param string $token
44 */
45 public function set_token($token) {
46 $this->token = $token;
47 }
48
49 /**
50 * Execute client WS request with token authentication
51 * @param string $functionname
52 * @param array $params
53 * @return mixed
54 */
55 public function call($functionname, $params) {
56 global $DB, $CFG;
57
db7c80d9
JM
58 if ($this->format == 'json') {
59 $formatparam = '&moodlewsrestformat=json';
60 $this->serverurl->param('moodlewsrestformat','json');
61 } else {
62 $formatparam = ''; //to keep retro compability with old server that only support xml (they don't expect this param)
63 }
64
65 $this->serverurl->param('wstoken',$this->token);
66 $this->serverurl->param('wsfunction',$functionname); //you could also use params().
67
68 $result = download_file_content($this->serverurl->out(false), null, $params);
75681c41 69
70 //TODO : transform the XML result into PHP values - MDL-22965
db7c80d9
JM
71 if ($this->format == 'json') {
72 $result = json_decode($result);
73 }
75681c41 74
75 return $result;
76 }
77
78}