Word-Case headers; too many applications break without it
[shpub.git] / src / shpub / Request.php
1 <?php
2 namespace shpub;
3
4 class Request
5 {
6     public $req;
7     public $cfg;
8
9     public function __construct($host, $cfg)
10     {
11         $this->cfg = $cfg;
12         $this->req = new \HTTP_Request2($host->endpoints->micropub, 'POST');
13         $this->req->setHeader('User-Agent: shpub');
14         if (version_compare(PHP_VERSION, '5.6.0', '<')) {
15             //correct ssl validation on php 5.5 is a pain, so disable
16             $this->req->setConfig('ssl_verify_host', false);
17             $this->req->setConfig('ssl_verify_peer', false);
18         }
19         $this->req->setHeader('Content-type', 'application/x-www-form-urlencoded');
20         $this->req->setHeader('authorization', 'Bearer ' . $host->token);
21     }
22
23     public function send($body)
24     {
25         $this->req->setBody($body);
26         if ($this->cfg->debug) {
27             $this->printCurl();
28         }
29         $res = $this->req->send();
30
31         if (intval($res->getStatus() / 100) != 2) {
32             Log::err(
33                 'Server returned an error status code ' . $res->getStatus()
34             );
35             Log::err($res->getBody());
36             exit(11);
37         }
38         return $res;
39     }
40
41     protected function printCurl()
42     {
43         $command = 'curl';
44         if ($this->req->getMethod() != 'GET') {
45             $command .= ' -X ' . $this->req->getMethod();
46         }
47         foreach ($this->req->getHeaders() as $key => $val) {
48             $caseKey = implode('-', array_map('ucfirst', explode('-', $key)));
49             $command .= ' -H ' . escapeshellarg($caseKey . ': ' . $val);
50         }
51         $command .= ' --data ' . escapeshellarg($this->req->getBody());
52         $command .= ' ' . escapeshellarg((string) $this->req->getUrl());
53
54         echo $command . "\n";
55     }
56 }