2 // Copyright (C) 2010 Maviq <info@maviq.com>
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License
6 // as published by the Free Software Foundation; either version 2
7 // of the License, or (at your option) any later version.
9 if(!extension_loaded("curl")) die("Curl extension is required");
17 public function __construct($siteId, $token, $endpoint) {
18 $this->SiteId
= $siteId;
19 $this->Token
= $token;
20 $this->Endpoint
= $endpoint;
24 public function sendRequest($path, $method="POST", $vars=array()){
26 echo "Path: {$path}\n";
29 foreach($vars AS $key=>$value)
30 $encoded .= "$key=".urlencode($value)."&";
31 $encoded = substr($encoded, 0, -1);
36 $url = "{$this->Endpoint}/$path";
40 // if GET and vars, append them
42 $url .= (FALSE === strpos($path, '?')?
"?":"&").$encoded;
44 // initialize a new curl object
45 $curl = curl_init($url);
46 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, false);
47 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST
, false);
48 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, TRUE);
49 switch(strtoupper($method)) {
51 curl_setopt($curl, CURLOPT_HTTPGET
, TRUE);
54 curl_setopt($curl, CURLOPT_POST
, TRUE);
55 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
58 // curl_setopt($curl, CURLOPT_PUT, TRUE);
59 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
60 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "PUT");
61 file_put_contents($tmpfile = tempnam("/tmp", "put_"),
63 curl_setopt($curl, CURLOPT_INFILE
, $fp = fopen($tmpfile,
65 curl_setopt($curl, CURLOPT_INFILESIZE
,
69 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "DELETE");
72 throw(new Exception("Unknown method $method"));
77 curl_setopt($curl, CURLOPT_USERPWD
,
78 $pwd = "{$this->SiteId}:{$this->Token}");
80 // do the request. If FALSE, then an exception occurred
81 if(FALSE === ($result = curl_exec($curl)))
83 "Curl failed with error " . curl_error($curl)));
86 $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
94 return new RestResponse($url, $result, $responseCode);
101 public $ResponseText;
107 public $ErrorMessage;
109 public function __construct($url, $text, $status) {
110 preg_match('/([^?]+)\??(.*)/', $url, $matches);
111 $this->Url
= $matches[1];
112 $this->QueryString
= $matches[2];
113 $this->ResponseText
= $text;
114 $this->HttpStatus
= $status;
115 if($this->HttpStatus
!= 204)
116 $this->ResponseXml
= @simplexml_load_string
($text);
118 if($this->IsError
= ($status >= 400))
119 $this->ErrorMessage
=
120 (string)$this->ResponseXml
->RestException
->Message
;