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) {
20 $this->SiteId
= $siteId;
21 $this->Token
= $token;
22 $this->Endpoint
= $endpoint;
26 public function sendRequest($path, $method="GET", $vars=array()){
28 echo "Path: {$path}\n";
31 foreach($vars AS $key=>$value)
32 $encoded .= "$key=".urlencode($value)."&";
33 $encoded = substr($encoded, 0, -1);
37 // Construct full url.
38 $url = "{$this->Endpoint}/$path";
42 // If GET and vars, append them.
44 $url .= (FALSE === strpos($path, '?')?
"?":"&").$encoded;
46 // Initialize a new curl object.
47 $curl = curl_init($url);
48 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, false);
49 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST
, false);
50 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, TRUE);
51 switch(strtoupper($method)) {
53 curl_setopt($curl, CURLOPT_HTTPGET
, TRUE);
56 curl_setopt($curl, CURLOPT_POST
, TRUE);
57 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
60 // curl_setopt($curl, CURLOPT_PUT, TRUE);
61 curl_setopt($curl, CURLOPT_POSTFIELDS
, $encoded);
62 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "PUT");
63 file_put_contents($tmpfile = tempnam("/tmp", "put_"),
65 curl_setopt($curl, CURLOPT_INFILE
, $fp = fopen($tmpfile,
67 curl_setopt($curl, CURLOPT_INFILESIZE
,
71 curl_setopt($curl, CURLOPT_CUSTOMREQUEST
, "DELETE");
74 throw(new Exception("Unknown method $method"));
79 curl_setopt($curl, CURLOPT_USERPWD
,
80 $pwd = "{$this->SiteId}:{$this->Token}");
82 // Do the request. If FALSE, then an exception occurred.
83 if(FALSE === ($result = curl_exec($curl)))
85 "Curl failed with error " . curl_error($curl)));
88 $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
96 return new RestResponse($url, $result, $responseCode);
103 public $ResponseText;
109 public $ErrorMessage;
111 public function __construct($url, $text, $status) {
112 preg_match('/([^?]+)\??(.*)/', $url, $matches);
113 $this->Url
= $matches[1];
114 $this->QueryString
= $matches[2];
115 $this->ResponseText
= $text;
116 $this->HttpStatus
= $status;
117 if($this->HttpStatus
!= 204)
118 $this->ResponseXml
= @simplexml_load_string
($text);
120 if($this->IsError
= ($status >= 400))
121 $this->ErrorMessage
=
122 (string)$this->ResponseXml
->RestException
->Message
;