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"));
13 class LabExchangeClient
{
19 public function __construct($siteId, $token, $endpoint)
21 $this->SiteId
= $siteId;
22 $this->Token
= $token;
23 $this->Endpoint
= $endpoint;
27 public function sendRequest($path, $method="GET", $vars=array())
30 echo "Path: {$path}\n";
33 foreach($vars as $key=>$value)
34 $encoded .= "$key=".urlencode($value)."&";
35 $encoded = substr($encoded, 0, -1);
39 // Construct full url.
40 $url = "{$this->Endpoint}/$path";
44 // If GET and vars, append them.
46 $url .= (false === strpos($path, '?')?
"?":"&").$encoded;
48 // Initialize a new curl object.
49 $curl = curl_init($url);
50 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, false);
51 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST
, false);
52 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, true);
53 switch(strtoupper($method)) {
55 curl_setopt($curl, CURLOPT_HTTPGET
, true);
58 curl_setopt($curl, CURLOPT_POST
, true);
59 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
62 // curl_setopt($curl, CURLOPT_PUT, TRUE);
63 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
64 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "PUT");
65 file_put_contents($tmpfile = tempnam("/tmp", "put_"),
67 curl_setopt($curl, CURLOPT_INFILE
, $fp = fopen($tmpfile,
69 curl_setopt($curl, CURLOPT_INFILESIZE
,
73 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "DELETE");
76 throw(new Exception("Unknown method $method"));
81 curl_setopt($curl, CURLOPT_USERPWD
,
82 $pwd = "{$this->SiteId}:{$this->Token}");
84 // Do the request. If FALSE, then an exception occurred.
85 if(false === ($result = curl_exec($curl)))
87 "Curl failed with error " . curl_error($curl)));
90 $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
98 return new RestResponse($url, $result, $responseCode);
105 public $ResponseText;
111 public $ErrorMessage;
113 public function __construct($url, $text, $status)
115 preg_match('/([^?]+)\??(.*)/', $url, $matches);
116 $this->Url
= $matches[1];
117 $this->QueryString
= $matches[2];
118 $this->ResponseText
= $text;
119 $this->HttpStatus
= $status;
120 if($this->HttpStatus
!= 204)
121 $this->ResponseXml
= @simplexml_load_string
($text);
123 if($this->IsError
= ($status >= 400))
124 $this->ErrorMessage
=
125 (string)$this->ResponseXml
->RestException
->Message
;