comments
[plcapi.git] / src / Request.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\Charset;
6 use PhpXmlRpc\Helper\Http;
7 use PhpXmlRpc\Helper\Logger;
8 use PhpXmlRpc\Helper\XMLParser;
9
10 /**
11  * This class provides the representation of a request to an XML-RPC server.
12  * A client sends a PhpXmlrpc\Request to a server, and receives back an PhpXmlrpc\Response.
13  */
14 class Request
15 {
16     /// @todo: do these need to be public?
17     public $payload;
18     /** @internal */
19     public $methodname;
20     /** @internal */
21     public $params = array();
22     public $debug = 0;
23     public $content_type = 'text/xml';
24
25     // holds data while parsing the response. NB: Not a full Response object
26     protected $httpResponse = array();
27
28     /**
29      * @param string $methodName the name of the method to invoke
30      * @param Value[] $params array of parameters to be passed to the method (NB: Value objects, not plain php values)
31      */
32     public function __construct($methodName, $params = array())
33     {
34         $this->methodname = $methodName;
35         foreach ($params as $param) {
36             $this->addParam($param);
37         }
38     }
39
40     /**
41      * @internal this function will become protected in the future
42      * @param string $charsetEncoding
43      * @return string
44      */
45     public function xml_header($charsetEncoding = '')
46     {
47         if ($charsetEncoding != '') {
48             return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\" ?" . ">\n<methodCall>\n";
49         } else {
50             return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
51         }
52     }
53
54     /**
55      * @internal this function will become protected in the future
56      * @return string
57      */
58     public function xml_footer()
59     {
60         return '</methodCall>';
61     }
62
63     /**
64      * @internal this function will become protected in the future
65      * @param string $charsetEncoding
66      */
67     public function createPayload($charsetEncoding = '')
68     {
69         if ($charsetEncoding != '') {
70             $this->content_type = 'text/xml; charset=' . $charsetEncoding;
71         } else {
72             $this->content_type = 'text/xml';
73         }
74         $this->payload = $this->xml_header($charsetEncoding);
75         $this->payload .= '<methodName>' . Charset::instance()->encodeEntities(
76             $this->methodname, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</methodName>\n";
77         $this->payload .= "<params>\n";
78         foreach ($this->params as $p) {
79             $this->payload .= "<param>\n" . $p->serialize($charsetEncoding) .
80                 "</param>\n";
81         }
82         $this->payload .= "</params>\n";
83         $this->payload .= $this->xml_footer();
84     }
85
86     /**
87      * Gets/sets the xmlrpc method to be invoked.
88      *
89      * @param string $methodName the method to be set (leave empty not to set it)
90      *
91      * @return string the method that will be invoked
92      */
93     public function method($methodName = '')
94     {
95         if ($methodName != '') {
96             $this->methodname = $methodName;
97         }
98
99         return $this->methodname;
100     }
101
102     /**
103      * Returns xml representation of the message. XML prologue included.
104      *
105      * @param string $charsetEncoding
106      *
107      * @return string the xml representation of the message, xml prologue included
108      */
109     public function serialize($charsetEncoding = '')
110     {
111         $this->createPayload($charsetEncoding);
112
113         return $this->payload;
114     }
115
116     /**
117      * Add a parameter to the list of parameters to be used upon method invocation.
118      *
119      * Checks that $params is actually a Value object and not a plain php value.
120      *
121      * @param Value $param
122      *
123      * @return boolean false on failure
124      */
125     public function addParam($param)
126     {
127         // check: do not add to self params which are not xmlrpc values
128         if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
129             $this->params[] = $param;
130
131             return true;
132         } else {
133             return false;
134         }
135     }
136
137     /**
138      * Returns the nth parameter in the request. The index zero-based.
139      *
140      * @param integer $i the index of the parameter to fetch (zero based)
141      *
142      * @return Value the i-th parameter
143      */
144     public function getParam($i)
145     {
146         return $this->params[$i];
147     }
148
149     /**
150      * Returns the number of parameters in the message.
151      *
152      * @return integer the number of parameters currently set
153      */
154     public function getNumParams()
155     {
156         return count($this->params);
157     }
158
159     /**
160      * Given an open file handle, read all data available and parse it as an xmlrpc response.
161      *
162      * NB: the file handle is not closed by this function.
163      * NNB: might have trouble in rare cases to work on network streams, as we check for a read of 0 bytes instead of
164      *      feof($fp). But since checking for feof(null) returns false, we would risk an infinite loop in that case,
165      *      because we cannot trust the caller to give us a valid pointer to an open file...
166      *
167      * @param resource $fp stream pointer
168      * @param bool $headersProcessed
169      * @param string $returnType
170      *
171      * @return Response
172      */
173     public function parseResponseFile($fp, $headersProcessed = false, $returnType = 'xmlrpcvals')
174     {
175         $ipd = '';
176         while ($data = fread($fp, 32768)) {
177             $ipd .= $data;
178         }
179         return $this->parseResponse($ipd, $headersProcessed, $returnType);
180     }
181
182     /**
183      * Parse the xmlrpc response contained in the string $data and return a Response object.
184      *
185      * When $this->debug has been set to a value greater than 0, will echo debug messages to screen while decoding.
186      *
187      * @param string $data the xmlrpc response, possibly including http headers
188      * @param bool $headersProcessed when true prevents parsing HTTP headers for interpretation of content-encoding and
189      *                               consequent decoding
190      * @param string $returnType decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or
191      *                           'phpvals'
192      *
193      * @return Response
194      *
195      * @todo parsing Responses is not really the responsibility of the Request class. Maybe of the Client...
196      */
197     public function parseResponse($data = '', $headersProcessed = false, $returnType = 'xmlrpcvals')
198     {
199         if ($this->debug) {
200             Logger::instance()->debugMessage("---GOT---\n$data\n---END---");
201         }
202
203         $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array());
204
205         if ($data == '') {
206             Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': no response received from server.');
207             return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
208         }
209
210         // parse the HTTP headers of the response, if present, and separate them from data
211         if (substr($data, 0, 4) == 'HTTP') {
212             $httpParser = new Http();
213             try {
214                 $this->httpResponse = $httpParser->parseResponseHeaders($data, $headersProcessed, $this->debug);
215             } catch(\Exception $e) {
216                 $r = new Response(0, $e->getCode(), $e->getMessage());
217                 // failed processing of HTTP response headers
218                 // save into response obj the full payload received, for debugging
219                 $r->raw_data = $data;
220
221                 return $r;
222             }
223         }
224
225         // be tolerant of extra whitespace in response body
226         $data = trim($data);
227
228         /// @todo return an error msg if $data == '' ?
229
230         // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
231         // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
232         $pos = strrpos($data, '</methodResponse>');
233         if ($pos !== false) {
234             $data = substr($data, 0, $pos + 17);
235         }
236
237         // try to 'guestimate' the character encoding of the received response
238         $respEncoding = XMLParser::guessEncoding(@$this->httpResponse['headers']['content-type'], $data);
239
240         if ($this->debug) {
241             $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
242             if ($start) {
243                 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
244                 $end = strpos($data, '-->', $start);
245                 $comments = substr($data, $start, $end - $start);
246                 Logger::instance()->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" .
247                     str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", $respEncoding);
248             }
249         }
250
251         // if user wants back raw xml, give it to her
252         if ($returnType == 'xml') {
253             $r = new Response($data, 0, '', 'xml');
254             $r->hdrs = $this->httpResponse['headers'];
255             $r->_cookies = $this->httpResponse['cookies'];
256             $r->raw_data = $this->httpResponse['raw_data'];
257
258             return $r;
259         }
260
261         if ($respEncoding != '') {
262
263             // Since parsing will fail if charset is not specified in the xml prologue,
264             // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
265             // The following code might be better for mb_string enabled installs, but makes the lib about 200% slower...
266             //if (!is_valid_charset($respEncoding, array('UTF-8')))
267             if (!in_array($respEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
268                 if ($respEncoding == 'ISO-8859-1') {
269                     $data = utf8_encode($data);
270                 } else {
271
272                     if (extension_loaded('mbstring')) {
273                         $data = mb_convert_encoding($data, 'UTF-8', $respEncoding);
274                     } else {
275                         Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $respEncoding);
276                     }
277                 }
278             }
279         }
280
281         // PHP internally might use ISO-8859-1, so we have to tell the xml parser to give us back data in the expected charset.
282         // What if internal encoding is not in one of the 3 allowed? We use the broadest one, ie. utf8
283         // This allows to send data which is native in various charset, by extending xmlrpc_encode_entities() and
284         // setting xmlrpc_internalencoding
285         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
286             /// @todo emit a warning
287             $options = array(XML_OPTION_TARGET_ENCODING => 'UTF-8');
288         } else {
289             $options = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
290         }
291
292         $xmlRpcParser = new XMLParser($options);
293         $xmlRpcParser->parse($data, $returnType, XMLParser::ACCEPT_RESPONSE);
294
295         // first error check: xml not well formed
296         if ($xmlRpcParser->_xh['isf'] > 2) {
297
298             // BC break: in the past for some cases we used the error message: 'XML error at line 1, check URL'
299
300             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
301                 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
302
303             if ($this->debug) {
304                 print $xmlRpcParser->_xh['isf_reason'];
305             }
306         }
307         // second error check: xml well formed but not xml-rpc compliant
308         elseif ($xmlRpcParser->_xh['isf'] == 2) {
309             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
310                 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
311
312             if ($this->debug) {
313                 /// @todo echo something for user?
314             }
315         }
316         // third error check: parsing of the response has somehow gone boink.
317         /// @todo shall we omit this check, since we trust the parsing code?
318         elseif ($returnType == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
319             // something odd has happened
320             // and it's time to generate a client side error
321             // indicating something odd went on
322             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
323                 PhpXmlRpc::$xmlrpcstr['invalid_return']);
324         } else {
325             if ($this->debug > 1) {
326                 Logger::instance()->debugMessage(
327                     "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---"
328                 );
329             }
330
331             $v = $xmlRpcParser->_xh['value'];
332
333             if ($xmlRpcParser->_xh['isf']) {
334                 /// @todo we should test here if server sent an int and a string, and/or coerce them into such...
335                 if ($returnType == 'xmlrpcvals') {
336                     $errNo_v = $v['faultCode'];
337                     $errStr_v = $v['faultString'];
338                     $errNo = $errNo_v->scalarval();
339                     $errStr = $errStr_v->scalarval();
340                 } else {
341                     $errNo = $v['faultCode'];
342                     $errStr = $v['faultString'];
343                 }
344
345                 if ($errNo == 0) {
346                     // FAULT returned, errno needs to reflect that
347                     $errNo = -1;
348                 }
349
350                 $r = new Response(0, $errNo, $errStr);
351             } else {
352                 $r = new Response($v, 0, '', $returnType);
353             }
354         }
355
356         $r->hdrs = $this->httpResponse['headers'];
357         $r->_cookies = $this->httpResponse['cookies'];
358         $r->raw_data = $this->httpResponse['raw_data'];
359
360         return $r;
361     }
362
363     /**
364      * Kept the old name even if Request class was renamed, for compatibility.
365      *
366      * @return string
367      */
368     public function kindOf()
369     {
370         return 'msg';
371     }
372
373     /**
374      * Enables/disables the echoing to screen of the xmlrpc responses received.
375      *
376      * @param integer $level values 0, 1, 2 are supported
377      */
378     public function setDebug($level)
379     {
380         $this->debug = $level;
381     }
382 }