Fix infinite loop when phancap tries to capture itself capturing itself
[phancap.git] / www / get.php
1 <?php
2 /**
3  * Create a website screenshot API
4  *
5  * PHP version 5
6  *
7  * @category  Tools
8  * @package   Phancap
9  * @author    Christian Weiske <cweiske@cweiske.de>
10  * @copyright 2014 Christian Weiske
11  * @license   http://www.gnu.org/licenses/agpl.html GNU AGPL v3
12  * @link      http://cweiske.de/phancap.htm
13  */
14 namespace phancap;
15
16 header('HTTP/1.0 500 Internal Server Error');
17
18 if (file_exists(__DIR__ . '/../src/phancap/Autoloader.php')) {
19     include_once __DIR__ . '/../src/phancap/Autoloader.php';
20     Autoloader::register();
21 } else {
22     include_once 'phancap/Autoloader.php';
23 }
24
25 $config = new Config();
26 $config->load();
27
28 $options = new Options();
29 try {
30     $options->setConfig($config);
31     $options->parse($_GET);
32 } catch (\InvalidArgumentException $e) {
33     header('HTTP/1.0 400 Bad Request');
34     header('Content-type: text/plain');
35     echo $e->getMessage() . "\n";
36     exit(1);
37 }
38
39 $auth = new Authenticator();
40 try {
41     $auth->authenticate($config);
42 } catch (\Exception $e) {
43     header('HTTP/1.0 401 Unauthorized');
44     header('Content-type: text/plain');
45     echo $e->getMessage() . "\n";
46     exit(1);
47 }
48
49 if (strpos($_SERVER['HTTP_USER_AGENT'], ' cutycapt ') !== false) {
50     //phancap is trying to render a page with an image that
51     // is being fetched from phancap itself, leading to an
52     // infinite loop
53     header('HTTP/1.0 500 Infinite Loop');
54     header('Location: ' . $config->getCurrentUrlDir() . '/infinite.png');
55     exit(3);
56 }
57
58 $rep = new Repository();
59 $rep->setConfig($config);
60 try {
61     $img = $rep->getImage($options);
62     if ($config->redirect) {
63         header('HTTP/1.0 302 Found');
64         header('Expires: ' . date('r', $img->getExpiryDate($options)));
65         header('Location: ' . $img->getUrl());
66     } else {
67         header('Content-type: ' . $img->getMimeType());
68         readfile($img->getPath());
69     }
70 } catch (\Exception $e) {
71     //FIXME: handle 404s and so properly
72     //FIXME: send out error image if images are preferred
73     header('HTTP/1.0 500 Internal Server error');
74     header('Content-type: text/plain');
75     echo $e->getMessage() . "\n";
76     exit(2);
77 }
78 ?>