forked from typpo/quickchart-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickChart.php
More file actions
296 lines (251 loc) · 9.19 KB
/
Copy pathQuickChart.php
File metadata and controls
296 lines (251 loc) · 9.19 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
<?php
class QuickChart {
public $protocol;
public $host;
public $port;
public $path;
public $config;
public $width;
public $height;
public $devicePixelRatio;
public $format;
public $backgroundColor;
public $apiKey;
public $version;
public $authUsername;
public $authPassword;
public $bearerToken;
public $connectTimeout;
public $timeout;
private $_cachedConfigStr = null;
private $_curlShare = null;
const USER_AGENT = 'quickchart-php (1.0.0)';
function __construct($options = array()) {
$this->protocol = isset($options['protocol']) ? $options['protocol'] : 'https';
$this->host = isset($options['host']) ? $options['host'] : 'quickchart.io';
$this->port = isset($options['port']) ? $options['port'] : 443;
$this->path = isset($options['path']) ? $options['path'] : false;
$this->width = isset($options['width']) ? $options['width'] : 500;
$this->height = isset($options['height']) ? $options['height'] : 300;
$this->devicePixelRatio = isset($options['devicePixelRatio']) ? $options['devicePixelRatio'] : 1.0;
$this->format = isset($options['format']) ? $options['format'] : 'png';
$this->backgroundColor = isset($options['backgroundColor']) ? $options['backgroundColor'] : 'transparent';
$this->apiKey = isset($options['apiKey']) ? $options['apiKey'] : null;
$this->version = isset($options['version']) ? $options['version'] : null;
$this->authUsername = isset($options['authUsername']) ? $options['authUsername'] : null;
$this->authPassword = isset($options['authPassword']) ? $options['authPassword'] : null;
$this->bearerToken = isset($options['bearerToken']) ? $options['bearerToken'] : null;
$this->connectTimeout = isset($options['connectTimeout']) ? (int)$options['connectTimeout'] : 10;
$this->timeout = isset($options['timeout']) ? (int)$options['timeout'] : 30;
$this->_curlShare = curl_share_init();
curl_share_setopt($this->_curlShare, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
curl_share_setopt($this->_curlShare, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
}
function __destruct() {
if ($this->_curlShare !== null) {
// curl_share_close() is a no-op since PHP 8.0 and deprecated in PHP 8.5
if (PHP_MAJOR_VERSION < 8) {
curl_share_close($this->_curlShare);
}
$this->_curlShare = null;
}
}
function setConfig($chartjsConfig) {
$this->config = $chartjsConfig;
$this->_cachedConfigStr = null;
}
function setWidth($width) {
$this->width = $width;
}
function setHeight($height) {
$this->height = $height;
}
function setDevicePixelRatio($devicePixelRatio) {
$this->devicePixelRatio = $devicePixelRatio;
}
function setFormat($format) {
$this->format = $format;
}
function setBackgroundColor($backgroundColor) {
$this->backgroundColor = $backgroundColor;
}
function setApiKey($apiKey) {
$this->apiKey = $apiKey;
}
function setVersion($version) {
$this->version = $version;
}
function setBasicAuth($username, $password) {
$this->authUsername = $username;
$this->authPassword = $password;
// Clear bearer token when using basic auth
$this->bearerToken = null;
}
function setBearerToken($token) {
$this->bearerToken = $token;
// Clear basic auth when using bearer token
$this->authUsername = null;
$this->authPassword = null;
}
function clearAuth() {
$this->authUsername = null;
$this->authPassword = null;
$this->bearerToken = null;
}
function setConnectTimeout($seconds) {
$this->connectTimeout = (int)$seconds;
}
function setTimeout($seconds) {
$this->timeout = (int)$seconds;
}
function getConfigStr() {
if (is_array($this->config)) {
if ($this->_cachedConfigStr === null) {
$this->_cachedConfigStr = json_encode($this->config);
}
return $this->_cachedConfigStr;
}
return $this->config;
}
protected function buildAuthHeaders($additionalHeaders = array()) {
$headers = $additionalHeaders;
if ($this->bearerToken) {
$headers[] = 'Authorization: Bearer ' . $this->bearerToken;
} elseif ($this->authUsername && $this->authPassword) {
$credentials = base64_encode($this->authUsername . ':' . $this->authPassword);
$headers[] = 'Authorization: Basic ' . $credentials;
}
return $headers;
}
function getUrl() {
$url = sprintf(
'%s/chart?ref=qc-php&c=%s&w=%d&h=%d&devicePixelRatio=%s&format=%s&bkg=%s',
$this->getRootEndpoint(),
urlencode($this->getConfigStr()),
$this->width,
$this->height,
number_format($this->devicePixelRatio, 1),
urlencode($this->format),
urlencode($this->backgroundColor)
);
if ($this->apiKey) {
$url .= '&key=' . urlencode($this->apiKey);
}
if ($this->version) {
$url .= '&v=' . urlencode($this->version);
}
return $url;
}
function getShortUrl() {
if ($this->host != 'quickchart.io') {
throw new Exception('Short URLs must use quickchart.io host');
}
$ch = curl_init($this->getRootEndpoint() . '/chart/create');
curl_setopt($ch, CURLOPT_SHARE, $this->_curlShare);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$postData = array(
'backgroundColor' => $this->backgroundColor,
'width' => $this->width,
'height' => $this->height,
'devicePixelRatio' => number_format($this->devicePixelRatio, 1),
'format' => $this->format,
'chart' => $this->getConfigStr(),
);
if ($this->apiKey) {
$postData['key'] = $this->apiKey;
}
if ($this->version) {
$postData['version'] = $this->version;
}
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_ENCODING, '');
if (defined('CURL_HTTP_VERSION_2_0')) {
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
}
$headers = $this->buildAuthHeaders(array(
'Content-Type: application/json',
'User-Agent: ' . QuickChart::USER_AGENT,
));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($result === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception("Curl error: $error");
}
curl_close($ch);
if ($httpStatusCode < 200 || $httpStatusCode >= 300) {
throw new Exception("QuickChart API returned error with status code $httpStatusCode");
}
// Note: do not dereference json_decode directly for 5.3 compatibility.
$ret = json_decode($result, true);
if (!isset($ret['url'])) {
throw new Exception('QuickChart API response did not include a URL');
}
return $ret['url'];
}
function toBinary() {
$ch = curl_init($this->getRootEndpoint() . '/chart');
curl_setopt($ch, CURLOPT_SHARE, $this->_curlShare);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$postData = array(
'backgroundColor' => $this->backgroundColor,
'devicePixelRatio' => $this->devicePixelRatio,
'width' => $this->width,
'height' => $this->height,
'format' => $this->format,
'chart' => $this->getConfigStr(),
);
if ($this->apiKey) {
$postData['key'] = $this->apiKey;
}
if ($this->version) {
$postData['version'] = $this->version;
}
$responseHeaders = [];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_ENCODING, '');
if (defined('CURL_HTTP_VERSION_2_0')) {
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
}
$headers = $this->buildAuthHeaders(array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header) use (&$responseHeaders) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) { // ignore invalid headers
return $len;
}
$responseHeaders[strtolower(trim($header[0]))][] = trim($header[1]);
return $len;
});
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($result === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception("Curl error: $error");
}
curl_close($ch);
if ($httpStatusCode >= 200 && $httpStatusCode < 300) {
return $result;
}
$errorHeader = isset($responseHeaders['x-quickchart-error'][0]) ? $responseHeaders['x-quickchart-error'][0] : null;
if ($errorHeader) {
throw new Exception("QuickChart API returned error with status code $httpStatusCode: $errorHeader");
}
throw new Exception("QuickChart API returned error with status code $httpStatusCode");
}
function toFile($path) {
$data = $this->toBinary();
file_put_contents($path, $data);
}
protected function getRootEndpoint() {
return $this->protocol . '://' . $this->host . ( $this->port ? ':' . $this->port : '' ) . ( $this->path ? $this->path : '' ) ;
}
}