ac82a382c1d8baa33220913ae357c86b6f240b22
[phorkie.git] / src / stub-phar.php
1 <?php
2 /**
3  * Phar stub file for phorkie. Handles startup of the .phar file.
4  *
5  * PHP version 5
6  *
7  * @category  Tools
8  * @package   Phorkie
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://phorkie.sf.net/
13  */
14 if (!in_array('phar', stream_get_wrappers()) || !class_exists('Phar', false)) {
15     echo "Phar extension not avaiable\n";
16     exit(255);
17 }
18
19 $web = 'www/index.php';
20 //FIXME
21 $cli = 'scripts/index.php';
22
23 /**
24  * Rewrite the HTTP request path to an internal file.
25  * Maps "" and "/" to "www/index.php".
26  *
27  * @param string $path Path from the browser, relative to the .phar
28  *
29  * @return string Internal path.
30  */
31 function rewritePath($path)
32 {
33     if ($path == '') {
34         //we need a / to get the relative links on index.php work
35         if (!isset($_SERVER['REQUEST_SCHEME'])) {
36             $_SERVER['REQUEST_SCHEME'] = 'http';
37         }
38         $url = $_SERVER['REQUEST_SCHEME'] . '://'
39             . $_SERVER['HTTP_HOST']
40             . preg_replace('/[?#].*$/', '', $_SERVER['REQUEST_URI'])
41             . '/';
42         header('Location: ' . $url);
43         exit(0);
44     } else if ($path == '/') {
45         return 'www/index.php';
46     }
47
48     $path = rewriteWithHtaccess($path);
49
50     if (substr($path, -4) == '.css' || substr($path, -3) == '.js') {
51         header('Expires: ' . date('r', time() + 86400 * 7));
52     }
53     return 'www' . $path;
54 }
55
56 function rewriteWithHtaccess($path)
57 {
58     //remove the trailing slash /
59     $cpath = substr($path, 1);
60     $bFoundMatch = false;
61     $map = include(__DIR__ . '/../src/gen-rewritemap.php');
62     foreach ($map as $pattern => $replace) {
63         if (preg_match($pattern, $cpath, $matches)) {
64             $bFoundMatch = true;
65             break;
66         }
67     }
68     if (!$bFoundMatch) {
69         return $path;
70     }
71     $newcpath = preg_replace($pattern, $replace, $cpath);
72     if (strpos($newcpath, '?') === false) {
73         return '/' . $newcpath;
74     }
75     list($cfile, $getParams) = explode('?', $newcpath, 2);
76     if ($getParams != '') {
77         parse_str($getParams, $_GET);
78     }
79     return '/' . $cfile;
80 }
81
82 //Phar::interceptFileFuncs();
83 set_include_path(
84     'phar://' . __FILE__
85     . PATH_SEPARATOR . 'phar://' . __FILE__ . '/lib/'
86 );
87 Phar::webPhar(null, $web, null, array(), 'rewritePath');
88
89 //TODO: implement CLI script runner
90 echo "phorkie can only be used in the browser\n";
91 exit(1);
92 __HALT_COMPILER();
93 ?>