forked from nateobray/IPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequest.php
69 lines (55 loc) · 2.35 KB
/
Request.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
namespace obray\ipp;
class Request implements \obray\ipp\interfaces\RequestInterface
{
/**
* send
*
* This method applies request headers, formulates the request and then
* parses the response into a response payload.
*
* @param string $encodedPayload This is the actual payload of the request
*
* @return \obray\ipp\transport\IPPPayload
*/
static public function send(string $printerURI, string $encodedPayload, string $user=null, string $password=null, array $curlOptions=[]): \obray\ipp\transport\IPPPayload
{
// interpret ipp request into http request
$results = parse_url($printerURI);
$postURL = $printerURI;
if(empty($results['path'])) $results['path'] = '';
if($results['scheme'] == 'ipp'){
$postURL = 'http://' . $results['host'] . ':' . ($results['port'] ?? '631'). $results['path'];
}
// setup headers
$headers = array(
0 => "Content-Type: application/ipp",
1 => "Content-Length: " . strlen($encodedPayload),
2 => "Connection: close"
);
if(!empty($user) && !empty($password)){
$headers[] = "Authorization: Basic " . base64_encode($user.':'.$password);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$postURL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedPayload);
forEach($curlOptions as $curlOption){
if(!isset($curlOption['key']) || !isset($curlOption['value'])) continue;
curl_setopt($ch, $curlOption['key'], $curlOption['value']);
}
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
if(curl_errno($ch)) throw new \Exception(curl_error($ch));
$info = curl_getinfo($ch);
curl_close($ch);
if($info['http_code'] == 401) throw new \obray\ipp\exceptions\AuthenticationError();
if($info['http_code'] != 200) throw new \obray\ipp\exceptions\HTTPError($info['http_code']);
// Further processing ...
$responsePayload = new \obray\ipp\transport\IPPPayload();
$responsePayload->decode($server_output);
return $responsePayload;
}
}