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")) {
10 die("Curl extension is required");
20 public function __construct($siteId, $token, $endpoint)
22 $this->SiteId
= $siteId;
23 $this->Token
= $token;
24 $this->Endpoint
= $endpoint;
27 public function sendRequest($path, $method = "POST", $vars = array())
30 echo "Path: {$path}\n";
33 foreach ($vars as $key => $value) {
34 $encoded .= "$key=".urlencode($value)."&";
37 $encoded = substr($encoded, 0, -1);
42 $url = "{$this->Endpoint}/$path";
46 // if GET and vars, append them
47 if ($method == "GET") {
48 $url .= (false === strpos($path, '?')?
"?":"&").$encoded;
51 // initialize a new curl object
52 $curl = curl_init($url);
53 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, false);
54 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST
, false);
55 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, true);
56 switch (strtoupper($method)) {
58 curl_setopt($curl, CURLOPT_HTTPGET
, true);
61 curl_setopt($curl, CURLOPT_POST
, true);
62 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
65 // curl_setopt($curl, CURLOPT_PUT, TRUE);
66 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
67 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "PUT");
69 $tmpfile = tempnam("/tmp", "put_"),
72 curl_setopt($curl, CURLOPT_INFILE
, $fp = fopen(
83 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "DELETE");
86 throw(new Exception("Unknown method $method"));
94 $pwd = "{$this->SiteId}:{$this->Token}"
97 // do the request. If FALSE, then an exception occurred
98 if (false === ($result = curl_exec($curl))) {
100 "Curl failed with error " . curl_error($curl)
105 $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
112 if (strlen($tmpfile)) {
116 return new RestResponse($url, $result, $responseCode);
123 public $ResponseText;
129 public $ErrorMessage;
131 public function __construct($url, $text, $status)
133 preg_match('/([^?]+)\??(.*)/', $url, $matches);
134 $this->Url
= $matches[1];
135 $this->QueryString
= $matches[2];
136 $this->ResponseText
= $text;
137 $this->HttpStatus
= $status;
138 if ($this->HttpStatus
!= 204) {
139 $this->ResponseXml
= @simplexml_load_string
($text);
142 if ($this->IsError
= ($status >= 400)) {
143 $this->ErrorMessage
=
144 (string)$this->ResponseXml
->RestException
->Message
;