Add "json" option
[shpub.git] / src / shpub / Request.php
1 <?php
2 namespace shpub;
3
4 class Request
5 {
6     public $req;
7     public $cfg;
8
9     protected $sendAsJson = false;
10     protected $uploadsInfo = [];
11     protected $dedicatedBody = false;
12
13     protected $properties = [];
14     protected $type = null;
15     protected $action = null;
16     protected $url = null;
17
18     public function __construct($host, $cfg)
19     {
20         $this->cfg = $cfg;
21         $this->req = new MyHttpRequest2($host->endpoints->micropub, 'POST');
22         $this->req->setHeader('User-Agent: shpub');
23         if (version_compare(PHP_VERSION, '5.6.0', '<')) {
24             //correct ssl validation on php 5.5 is a pain, so disable
25             $this->req->setConfig('ssl_verify_host', false);
26             $this->req->setConfig('ssl_verify_peer', false);
27         }
28         $this->req->setHeader('Content-type', 'application/x-www-form-urlencoded');
29         $this->req->setHeader('authorization', 'Bearer ' . $host->token);
30     }
31
32     public function send($body = null)
33     {
34         if ($this->sendAsJson) {
35             //application/json
36             if ($body !== null) {
37                 throw new \Exception('body already defined');
38             }
39             $this->req->setHeader('Content-Type: application/json');
40             $data = [];
41             if ($this->action !== null) {
42                 $data['action'] = $this->action;
43             }
44             if ($this->url !== null) {
45                 $data['url'] = $this->url;
46             }
47             if ($this->type !== null) {
48                 $data['type'] = 'h-' . $this->type;
49             }
50             if (count($this->properties)) {
51                 $data['properties'] = $this->properties;
52             }
53             $body = json_encode($data);
54         } else {
55             //form-encoded
56             if ($this->type !== null) {
57                 $this->req->addPostParameter('h', $this->type);
58             }
59             if ($this->action !== null) {
60                 $this->req->addPostParameter('action', $this->action);
61             }
62             if ($this->url !== null) {
63                 $this->req->addPostParameter('url', $this->url);
64             }
65             foreach ($this->properties as $propkey => $propval) {
66                 if (isset($propval['html'])) {
67                     //workaround for content[html]
68                     $propkey = $propkey . '[html]';
69                     $propval = $propval['html'];
70                 } else if (count($propval) == 1) {
71                     $propval = reset($propval);
72                 }
73                 $this->req->addPostParameter($propkey, $propval);
74             }
75         }
76
77         if ($body !== null) {
78             $this->dedicatedBody = true;
79             $this->req->setBody($body);
80         }
81         if ($this->cfg->debug) {
82             $this->printCurl();
83         }
84         $res = $this->req->send();
85
86         if (intval($res->getStatus() / 100) != 2) {
87             Log::err(
88                 'Server returned an error status code ' . $res->getStatus()
89             );
90             Log::err($res->getBody());
91             exit(11);
92         }
93         return $res;
94     }
95
96     public function setAction($action)
97     {
98         $this->action = $action;
99     }
100
101     public function setType($type)
102     {
103         $this->type = $type;
104     }
105
106     public function setUrl($url)
107     {
108         $this->url = $url;
109     }
110
111     /**
112      * @param string                $fieldName name of file-upload field
113      * @param string|resource|array $filename  full name of local file,
114      *               pointer to open file or an array of files
115      */
116     public function addUpload($fieldName, $filename)
117     {
118         if ($this->sendAsJson) {
119             throw new \Exception('File uploads do not work with JSON');
120         }
121         $this->uploadsInfo[$fieldName] = $filename;
122         return $this->req->addUpload($fieldName, $filename);
123     }
124
125     /**
126      * Adds a micropub property to the request.
127      *
128      * @param string       $key    Parameter name
129      * @param string|array $values One or multiple values
130      */
131     public function addProperty($key, $values)
132     {
133         $this->properties[$key] = (array) $values;
134     }
135
136     protected function printCurl()
137     {
138         $command = 'curl';
139         if ($this->req->getMethod() != 'GET') {
140             $command .= ' -X ' . $this->req->getMethod();
141         }
142         foreach ($this->req->getHeaders() as $key => $val) {
143             $caseKey = implode('-', array_map('ucfirst', explode('-', $key)));
144             $command .= ' -H ' . escapeshellarg($caseKey . ': ' . $val);
145         }
146
147         $postParams = $this->req->getPostParams();
148
149         if (count($this->uploadsInfo) == 0) {
150             foreach ($postParams as $k => $v) {
151                 if (!is_array($v)) {
152                     $command .= ' -d ' . escapeshellarg($k . '=' . $v);
153                 } else {
154                     foreach ($v as $ak => $av) {
155                         $command .= ' -d ' . escapeshellarg(
156                             $k . '[' . $ak . ']=' . $av
157                         );
158                     }
159                 }
160             }
161         } else {
162             foreach ($postParams as $k => $v) {
163                 $command .= ' -F ' . escapeshellarg($k . '=' . $v);
164             }
165             foreach ($this->uploadsInfo as $fieldName => $filename) {
166                 if (!is_array($filename)) {
167                     $command .= ' -F ' . escapeshellarg(
168                         $fieldName . '=@' . $filename
169                     );
170                 } else {
171                     foreach ($filename as $k => $realFilename) {
172                         $command .= ' -F ' . escapeshellarg(
173                             $fieldName . '[' . $k . ']=@' . $realFilename
174                         );
175                     }
176                 }
177             }
178         }
179
180         if ($this->dedicatedBody) {
181             $command .= ' --data ' . escapeshellarg($this->req->getBody());
182         }
183
184         $command .= ' ' . escapeshellarg((string) $this->req->getUrl());
185
186         Log::msg($command);
187     }
188
189     public function setSendAsJson($json)
190     {
191         $this->sendAsJson = $json;
192     }
193 }