-
Notifications
You must be signed in to change notification settings - Fork 26
/
http2pic.class.php
339 lines (277 loc) · 8.52 KB
/
http2pic.class.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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<?php
/**
* http2pic by Christian Haschek (https://haschek.solutions)
*
* For more info and up2date version of this file visit https://github.com/chrisiaut/http2pic
* -------------
*
* @category Website rendering API
* @author Christian Haschek <christian@haschek.at>
* @copyright 2015 by HASCHEK SOLUTIONS
* @link https://http2pic.haschek.at
*/
//
// Stuff you can edit
//
// if true, will save all cmd queries
define(DEBUG,false);
define(MAXTIMEOUT,30);
define(ONFAILIMAGE, __DIR__.'/img/pagefailed.jpg');
define(ONDOMAINFAILIMAGE, __DIR__.'/img/domainfailed.jpg');
//rendering engine: wkhtmltoimage or phantomjs
define(RENDERINGENGINE,'wkhtmltoimage');
//location of wkhtmltoimage
define(WKHTMLTOIMAGEPATH,'/usr/sbin/wkhtmltoimage');
//location of phantomJS
define(PHANTOMJSPATH,__DIR__.'/phantomjs');
//where shoud we store cached images
define(CACHEDIR,__DIR__.'/cache/');
//
// Only edit from here if you know what you are doing
//
class http2pic
{
private $params = array();
function __construct($params)
{
//try to create the cache folder if not exists
if (!is_dir(CACHEDIR)) {
mkdir(CACHEDIR);
}
$this->params = $params;
return $this->paramsPrepare();
}
/**
* Prepare and validate params
**/
function paramsPrepare()
{
//validate file type of rendered image
switch($this->params['type'])
{
case 'png': $this->params['type'] = 'png'; break;
case 'jpg': $this->params['type'] = 'jpg'; break;
default: $this->params['type'] = 'png';
}
//validate timeout
if (!$this->params['timeout'] || !is_numeric($this->params['timeout']) || ($this->params['timeout'] > MAXTIMEOUT || $this->params['timeout'] < 1))
$this->params['timeout'] = 10;
//validate viewport
if ($this->params['viewport'])
{
$a = explode('x', $this->params['viewport']);
$w = $a[0];
$h = $a[1];
if (is_numeric($w))
$this->params['vp_w'] = $w;
if (is_numeric($h))
$this->params['vp_h'] = $h;
}
//validate resize width
if($this->params['resizewidth'])
{
if(!is_numeric($this->params['resizewidth']) || $this->params['resizewidth']<1 || $this->params['resizewidth']>8000)
unset($this->params['resizewidth']);
}
if(!$this->params['onfail'])
$this->params['onfail'] = ONFAILIMAGE;
else
$this->params['onfail'] = rawurldecode($this->params['onfail']);
if(!$this->params['ondomainfail'])
$this->params['ondomainfail'] = ONDOMAINFAILIMAGE;
else
$this->params['ondomainfail'] = rawurldecode($this->params['ondomainfail']);
//validate URL and check if exists
if ($this->isBase64($this->params['url']))
$this->params['url'] = base64_decode($url);
else
$this->params['url'] = rawurldecode($_GET['url']);
//if the url is not valid or not responding, show onfail image and leave
if(!$this->isURLValid($this->params['url']) || !(($reachableResult = $this->isURLReachable($this->params['url'])) == 0))
{
header('Content-Type: image/jpeg');
header('Content-Disposition: inline; filename="http2png.jpg"');
switch ($reachableResult) {
case 1:
header('HTTP/1.0 404 File Not Found');
$result = imagecreatefromjpeg($this->params['onfail']);
break;
case 2:
header('HTTP/1.0 404 Server Not Found');
$result = imagecreatefromjpeg($this->params['ondomainfail']);
break;
}
imagejpeg($result, NULL, 100);
return false;
}
//prepare file name
$this->params['cache'] = $this->trimToAlphaNumeric($this->params['cache']);
$hash = $this->params['cache'].'-'.preg_replace("/[^A-Za-z0-9 ]/", '', $this->params['url']).'.'.$this->params['type'];
if (!$this->params['cache'])
$hash = md5(time().rand(1,2000)).$hash;
$this->params['file'] = CACHEDIR.$hash;
$this->render();
return true;
}
function render()
{
//if phantomjs is selected and installed
if(RENDERINGENGINE=='phantomjs' && file_exists(PHANTOMJSPATH))
return $this->renderPagePHANTOMJS();
//no? well ok how about WKHTMLToImage?
else if(RENDERINGENGINE=='wkhtmltoimage' && file_exists(WKHTMLTOIMAGEPATH))
return $this->renderPageWKHTMLTOIMAGE();
//you're fucked
else
throw new Exception('No valid rendering engine found');
}
/**
* Render using PhantomJS
**/
function renderPagePHANTOMJS()
{
$cmd = 'timeout '.$this->params['timeout'].' '.PHANTOMJSPATH;
$cmd.= ' --ignore-ssl-errors=yes --ssl-protocol=any '.__DIR__.'/phantom.js ';
$cmd.= ($this->params['url']);
$cmd.= ','.($this->params['file']);
$cmd.= ','.$this->params['vp_w'];
$cmd.= ','.$this->params['vp_h'];
$cmd.= ','.$this->params['js'];
$cmd = escapeshellcmd($cmd);
shell_exec($cmd);
$this->params['cmd'] = $cmd;
$this->postRender();
if(DEBUG)
{
$fp = fopen('debug.log', 'a');
fwrite($fp, $cmd."\n");
fclose($fp);
}
return $cmd;
}
/**
* Render using WKHTMLToImage
**/
function renderPageWKHTMLTOIMAGE()
{
//escapeshellarg
//timeout
$cmd = 'timeout '.$this->params['timeout'].' '.WKHTMLTOIMAGEPATH;
//viewport vp_w und vp_h
if($this->params['vp_w'])
$cmd.=' --width '.$this->params['vp_w'];
if($this->params['vp_h'])
$cmd.=' --height '.$this->params['vp_h'];
//js or no js
if($this->params['js']=='no')
$cmd.=' -n';
//png or jpg (default)
if($this->params['type']=='png')
$cmd.=' -f png';
//add url to cmd
$cmd.=' \''.addslashes($this->params['url']).'\'';
//add storage path to cmd
$cmd.=' '.escapeshellarg($this->params['file']);
$cmd = escapeshellcmd($cmd);
shell_exec($cmd);
$this->params['cmd'] = $cmd;
$this->postRender();
if(DEBUG)
{
$fp = fopen('debug.log', 'a');
fwrite($fp, $cmd."\n");
fclose($fp);
}
return $cmd;
}
/**
* Called after a render took place.
* This method will print the image to the user, then
* resizes or deletes it
*/
function postRender()
{
// resize if necessary
if($this->params['resizewidth'])
$this->resizeImage($this->params['file']);
//print image to user
if ($this->params['type'] === 'png') {
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="'.$this->trimToAlphaNumeric($this->params['url']).'.png"');
$result = imagecreatefrompng($this->params['file']);
imagepng($result, NULL, 9);
}
else {
header('Content-Type: image/jpeg');
header('Content-Disposition: inline; filename="'.$this->trimToAlphaNumeric($this->params['url']).'.jpg"');
$result = imagecreatefromjpeg($this->params['file']);
imagejpeg($result, NULL, 100);
}
//if no cache value specified: delete the image
if(!$this->params['cache']) unlink($this->params['file']);
}
function resizeImage($file)
{
list($width_orig, $height_orig) = getimagesize($file);
if ($width_orig != $this->params['resizewidth'])
{
$ratio_orig = $width_orig/$height_orig;
$height = $this->params['resizewidth']/$ratio_orig;
// resample
$image_p = imagecreatetruecolor($this->params['resizewidth'], $height);
if ($this->params['type'] === 'png')
$image = imagecreatefrompng($file);
else
$image = imagecreatefromjpeg($file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $this->params['resizewidth'], $height, $width_orig, $height_orig);
if ($this->params['type'] === 'png')
imagepng($image_p, $file, 9);
else
imagejpeg($image_p, $file, 100);
}
}
function isURLValid($url)
{
if(!$this->startsWith($url,'http://') && !$this->startsWith($url,'https://') && !$this->startsWith($url,'ftp://'))
return false;
return filter_var($url, FILTER_VALIDATE_URL);
}
function startsWith($haystack,$needle)
{
$length = strlen($needle);
return (substr($haystack,0,$length) === $needle);
}
/**
* https://stackoverflow.com/questions/7684771/how-check-if-file-exists-from-the-url
*/
function isURLReachable($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(curl_exec($ch) != false){
//We were able to connect to a webserver, what did it return?
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code < 400) //status code updated so redirects will also work
$status = 0;
else
$status = 1;
curl_close($ch);
return $status;
} else {
//We were not able to connect to any webserver so we didn't get a status code
//to compare against. There must be a problem with the domain that was supplied.
curl_close($ch);
return 2;
}
}
function trimToAlphaNumeric($string)
{
return preg_replace("/[^A-Za-z0-9 ]/", '', $string);
}
function isBase64($data)
{
if (base64_encode(base64_decode($data, true)) === $data)
return true;
return false;
}
}