Move off sourceforge
[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      https://cweiske.de/phorkie.htm
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'
51         || substr($path, -3) == '.js'
52         || substr($path, 0, 9) == '/phorkie/'
53     ) {
54         header('Expires: ' . date('r', time() + 86400 * 7));
55     }
56     return 'www' . $path;
57 }
58
59 function rewriteWithHtaccess($path)
60 {
61     //remove the leading slash /
62     $cpath = substr($path, 1);
63     $bFoundMatch = false;
64     $map = include('phar://' . __FILE__ . '/src/gen-rewritemap.php');
65     foreach ($map as $pattern => $replace) {
66         if (preg_match($pattern, $cpath, $matches)) {
67             $bFoundMatch = true;
68             break;
69         }
70     }
71     if (!$bFoundMatch) {
72         return $path;
73     }
74     $newcpath = preg_replace($pattern, $replace, $cpath);
75     if (strpos($newcpath, '?') === false) {
76         return '/' . $newcpath;
77     }
78     list($cfile, $getParams) = explode('?', $newcpath, 2);
79     if ($getParams != '') {
80         parse_str($getParams, $_GET);
81     }
82     return '/' . $cfile;
83 }
84
85 //Phar::interceptFileFuncs();
86 set_include_path(
87     'phar://' . __FILE__
88     . PATH_SEPARATOR . 'phar://' . __FILE__ . '/lib/'
89 );
90 Phar::webPhar(null, $web, null, array(), 'rewritePath');
91
92 //TODO: implement CLI script runner
93 echo "phorkie can only be used in the browser\n";
94 exit(1);
95 __HALT_COMPILER();
96 ?>