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")) {
11 "Curl extension is required"
15 class LabExchangeClient
22 public function __construct($siteId, $token, $endpoint)
24 $this->SiteId
= $siteId;
25 $this->Token
= $token;
26 $this->Endpoint
= $endpoint;
29 public function sendRequest($path, $method = "GET", $vars = array())
32 echo "Path: {$path}\n";
35 foreach ($vars as $key => $value) {
36 $encoded .= "$key=".urlencode($value)."&";
39 $encoded = substr($encoded, 0, -1);
43 // Construct full url.
44 $url = "{$this->Endpoint}/$path";
48 // If GET and vars, append them.
49 if ($method == "GET") {
50 $url .= (false === strpos($path, '?')?
"?":"&").$encoded;
53 // Initialize a new curl object.
54 $curl = curl_init($url);
55 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, false);
56 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST
, false);
57 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, true);
58 switch (strtoupper($method)) {
60 curl_setopt($curl, CURLOPT_HTTPGET
, true);
63 curl_setopt($curl, CURLOPT_POST
, true);
64 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
67 // curl_setopt($curl, CURLOPT_PUT, TRUE);
68 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
69 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "PUT");
71 $tmpfile = tempnam("/tmp", "put_"),
74 curl_setopt($curl, CURLOPT_INFILE
, $fp = fopen(
85 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "DELETE");
88 throw(new Exception("Unknown method $method"));
96 $pwd = "{$this->SiteId}:{$this->Token}"
99 // Do the request. If FALSE, then an exception occurred.
100 if (false === ($result = curl_exec($curl))) {
102 "Curl failed with error " . curl_error($curl)
107 $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
114 if (strlen($tmpfile)) {
118 return new RestResponse($url, $result, $responseCode);
125 public $ResponseText;
131 public $ErrorMessage;
133 public function __construct($url, $text, $status)
135 preg_match('/([^?]+)\??(.*)/', $url, $matches);
136 $this->Url
= $matches[1];
137 $this->QueryString
= $matches[2];
138 $this->ResponseText
= $text;
139 $this->HttpStatus
= $status;
140 if ($this->HttpStatus
!= 204) {
141 $this->ResponseXml
= @simplexml_load_string
($text);
144 if ($this->IsError
= ($status >= 400)) {
145 $this->ErrorMessage
=
146 (string)$this->ResponseXml
->RestException
->Message
;