3 // Copyright (C) 2010 Maviq <info@maviq.com>
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 if (!extension_loaded("curl")) {
11 die("Curl extension is required");
21 public function __construct($siteId, $token, $endpoint)
23 $this->SiteId
= $siteId;
24 $this->Token
= $token;
25 $this->Endpoint
= $endpoint;
28 public function sendRequest($path, $method = "POST", $vars = array())
31 echo "Path: {$path}\n";
34 foreach ($vars as $key => $value) {
35 $encoded .= "$key=" . urlencode($value) . "&";
38 $encoded = substr($encoded, 0, -1);
43 $url = "{$this->Endpoint}/$path";
47 // if GET and vars, append them
48 if ($method == "GET") {
49 $url .= (false === strpos($path, '?') ?
"?" : "&") . $encoded;
52 // initialize a new curl object
53 $curl = curl_init($url);
54 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, false);
55 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST
, false);
56 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, true);
57 switch (strtoupper($method)) {
59 curl_setopt($curl, CURLOPT_HTTPGET
, true);
62 curl_setopt($curl, CURLOPT_POST
, true);
63 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
66 // curl_setopt($curl, CURLOPT_PUT, TRUE);
67 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
68 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "PUT");
70 $tmpfile = tempnam("/tmp", "put_"),
73 curl_setopt($curl, CURLOPT_INFILE
, $fp = fopen(
84 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "DELETE");
87 throw(new Exception("Unknown method $method"));
95 $pwd = "{$this->SiteId}:{$this->Token}"
98 // do the request. If FALSE, then an exception occurred
99 if (false === ($result = curl_exec($curl))) {
101 "Curl failed with error " . curl_error($curl)
106 $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
113 if (strlen($tmpfile)) {
117 return new RestResponse($url, $result, $responseCode);
124 public $ResponseText;
130 public $ErrorMessage;
132 public function __construct($url, $text, $status)
134 preg_match('/([^?]+)\??(.*)/', $url, $matches);
135 $this->Url
= $matches[1];
136 $this->QueryString
= $matches[2];
137 $this->ResponseText
= $text;
138 $this->HttpStatus
= $status;
139 if ($this->HttpStatus
!= 204) {
140 $this->ResponseXml
= @simplexml_load_string
($text);
143 if ($this->IsError
= ($status >= 400)) {
144 $this->ErrorMessage
=
145 (string)$this->ResponseXml
->RestException
->Message
;