Merge branch 'MDL-29435' of git://github.com/mouneyrac/moodle
[moodle.git] / webservice / soap / locallib.php
1 <?php
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/>.
18 /**
19  * SOAP web service implementation classes and methods.
20  *
21  * @package   webservice
22  * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
23  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 require_once("$CFG->dirroot/webservice/lib.php");
27 require_once 'Zend/Soap/Server.php';
29 /**
30  * The Zend XMLRPC server but with a fault that returns debuginfo
31  */
32 class moodle_zend_soap_server extends Zend_Soap_Server {
34     /**
35      * Generate a server fault
36      *
37      * Note that the arguments are reverse to those of SoapFault.
38      *
39      * Moodle note: the difference with the Zend server is that we throw a SoapFault exception
40      * with the debuginfo integrated to the exception message when DEBUG >= NORMAL
41      *
42      * If an exception is passed as the first argument, its message and code
43      * will be used to create the fault object if it has been registered via
44      * {@Link registerFaultException()}.
45      *
46      * @link   http://www.w3.org/TR/soap12-part1/#faultcodes
47      * @param  string|Exception $fault
48      * @param  string $code SOAP Fault Codes
49      * @return SoapFault
50      */
51     public function fault($fault = null, $code = "Receiver")
52     {
53         //intercept any exceptions with debug info and transform it in Moodle exception
54         if ($fault instanceof Exception) {
55             //add the debuginfo to the exception message if debuginfo must be returned
56             if (debugging() and isset($fault->debuginfo)) {
57                 $fault = new SoapFault('Receiver', $fault->getMessage() . ' | DEBUG INFO: ' . $fault->debuginfo);
58             }
59         }
61         return parent::fault($fault, $code);
62     }
63 }
65 /**
66  * SOAP service server implementation.
67  * @author Petr Skoda (skodak)
68  */
69 class webservice_soap_server extends webservice_zend_server {
70     /**
71      * Contructor
72      * @param bool $simple use simple authentication
73      */
74     public function __construct($authmethod) {
75          // must not cache wsdl - the list of functions is created on the fly
76         ini_set('soap.wsdl_cache_enabled', '0');
77         require_once 'Zend/Soap/Server.php';
78         require_once 'Zend/Soap/AutoDiscover.php';
80         if (optional_param('wsdl', 0, PARAM_BOOL)) {
81             parent::__construct($authmethod, 'Zend_Soap_AutoDiscover');
82         } else {
83             parent::__construct($authmethod, 'moodle_zend_soap_server');
84         }
85         $this->wsname = 'soap';
86     }
88     /**
89      * Set up zend service class
90      * @return void
91      */
92     protected function init_zend_server() {
93         global $CFG;
95         parent::init_zend_server();
97         if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
98             $username = optional_param('wsusername', '', PARAM_RAW);
99             $password = optional_param('wspassword', '', PARAM_RAW);
100             // aparently some clients and zend soap server does not work well with "&" in urls :-(
101             //TODO: the zend error has been fixed in the last Zend SOAP version, check that is fixed and remove obsolete code
102             $url = $CFG->wwwroot.'/webservice/soap/simpleserver.php/'.urlencode($username).'/'.urlencode($password);
103             // the Zend server is using this uri directly in xml - weird :-(
104             $this->zend_server->setUri(htmlentities($url));
105         } else {
106             $wstoken = optional_param('wstoken', '', PARAM_RAW);
107             $url = $CFG->wwwroot.'/webservice/soap/server.php?wstoken='.urlencode($wstoken);
108             // the Zend server is using this uri directly in xml - weird :-(
109             $this->zend_server->setUri(htmlentities($url));
110         }
112         if (!optional_param('wsdl', 0, PARAM_BOOL)) {
113             $this->zend_server->setReturnResponse(true);
114             //TODO: the error handling in Zend Soap server is useless, XML-RPC is much, much better :-(
115             $this->zend_server->registerFaultException('moodle_exception');
116             $this->zend_server->registerFaultException('webservice_parameter_exception'); //deprecated since Moodle 2.2 - kept for backward compatibility
117             $this->zend_server->registerFaultException('invalid_parameter_exception');
118             $this->zend_server->registerFaultException('invalid_response_exception');
119             //when DEBUG >= NORMAL then the thrown exceptions are "casted" into a PHP SoapFault expception
120             //in order to diplay the $debuginfo (see moodle_zend_soap_server class - MDL-29435)
121             if (debugging()) {
122                 $this->zend_server->registerFaultException('SoapFault');
123             }
124         }
125     }
127     /**
128      * This method parses the $_REQUEST superglobal and looks for
129      * the following information:
130      *  1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
131      *
132      * @return void
133      */
134     protected function parse_request() {
135         parent::parse_request();
137         if (!$this->username or !$this->password) {
138             //note: this is the workaround for the trouble with & in soap urls
139             $authdata = get_file_argument();
140             $authdata = explode('/', trim($authdata, '/'));
141             if (count($authdata) == 2) {
142                 list($this->username, $this->password) = $authdata;
143             }
144         }
145     }
147     /**
148      * Send the error information to the WS client
149      * formatted as XML document.
150      * @param exception $ex
151      * @return void
152      */
153     protected function send_error($ex=null) {
154         // Zend Soap server fault handling is incomplete compared to XML-RPC :-(
155         // we can not use: echo $this->zend_server->fault($ex);
156         //TODO: send some better response in XML
157         if ($ex) {
158             $info = $ex->getMessage();
159             if (debugging() and isset($ex->debuginfo)) {
160                 $info .= ' - '.$ex->debuginfo;
161             }
162         } else {
163             $info = 'Unknown error';
164         }
166         $xml = '<?xml version="1.0" encoding="UTF-8"?>
167 <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
168 <SOAP-ENV:Body><SOAP-ENV:Fault>
169 <faultcode>MOODLE:error</faultcode>
170 <faultstring>'.$info.'</faultstring>
171 </SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>';
173         $this->send_headers();
174         header('Content-Type: application/xml; charset=utf-8');
175         header('Content-Disposition: inline; filename="response.xml"');
177         echo $xml;
178     }
180     protected function generate_simple_struct_class(external_single_structure $structdesc) {
181         global $USER;
182         // let's use unique class name, there might be problem in unit tests
183         $classname = 'webservices_struct_class_000000';
184         while(class_exists($classname)) {
185             $classname++;
186         }
188         $fields = array();
189         foreach ($structdesc->keys as $name => $fieldsdesc) {
190             $type = $this->get_phpdoc_type($fieldsdesc);
191             $fields[] = '    /** @var '.$type." */\n" .
192                         '    public $'.$name.';';
193         }
195         $code = '
196 /**
197  * Virtual struct class for web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
198  */
199 class '.$classname.' {
200 '.implode("\n", $fields).'
202 ';
203         eval($code);
204         return $classname;
205     }
208 /**
209  * SOAP test client class
210  */
211 class webservice_soap_test_client implements webservice_test_client_interface {
212     /**
213      * Execute test client WS request
214      * @param string $serverurl
215      * @param string $function
216      * @param array $params
217      * @return mixed
218      */
219     public function simpletest($serverurl, $function, $params) {
220         //zend expects 0 based array with numeric indexes
221         $params = array_values($params);
222         require_once 'Zend/Soap/Client.php';
223         $client = new Zend_Soap_Client($serverurl.'&wsdl=1');
224         return $client->__call($function, $params);
225     }