r3010 - maintenance->trunk sync of changesets 3008~3009
[racktables] / inc / init.php
1 <?php
2 /*
3 *
4 * This file performs RackTables initialisation. After you include it
5 * from 1st-level page, don't forget to call fixContext(). This is done
6 * to enable override of of pageno and tabno variables. pageno and tabno
7 * together participate in forming security context by generating
8 * related autotags.
9 *
10 */
11
12 // "Note that when using ISAPI with IIS, the value will be 'off' if the
13 // request was not made through the HTTPS protocol."
14 $root = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off') ? 'http://' : 'https://';
15 $root .= isset ($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].($_SERVER['SERVER_PORT']=='80'?'':$_SERVER['SERVER_PORT']));
16 // "Since PHP 4.3.0, you will often get a slash or a dot back from
17 // dirname() in situations where the older functionality would have given
18 // you the empty string."
19 // "On Windows, both slash (/) and backslash (\) are used as directory
20 // separator character."
21 $root .= strtr (dirname ($_SERVER['PHP_SELF']), '\\', '/');
22 if (substr ($root, -1) != '/')
23 $root .= '/';
24
25 // This is the first thing we need to do.
26 require_once 'inc/exceptions.php';
27 require_once 'inc/config.php';
28
29 // What we need first is database and interface functions.
30 require_once 'inc/functions.php';
31 require_once 'inc/database.php';
32 // Always have default values for these options, so if a user didn't
33 // care to set, something would be working anyway.
34 $user_auth_src = 'database';
35 $require_local_account = TRUE;
36
37 function showError ($info = '', $location = 'N/A')
38 {
39 if (preg_match ('/\.php$/', $location))
40 $location = basename ($location);
41 elseif ($location != 'N/A')
42 $location = $location . '()';
43 echo "<div class=msg_error>An error has occured in [${location}]. ";
44 if (!strlen ($info))
45 echo 'No additional information is available.';
46 else
47 echo "Additional information:<br><p>\n<pre>\n${info}\n</pre></p>";
48 echo "Go back or try starting from <a href='".makeHref()."'>index page</a>.<br></div>\n";
49 }
50
51 if (file_exists ('inc/secret.php'))
52 require_once 'inc/secret.php';
53 else
54 {
55 showError
56 (
57 "Database connection parameters are read from inc/secret.php file, " .
58 "which cannot be found.\nYou probably need to complete the installation " .
59 "procedure by following <a href='${root}install.php'>this link</a>.",
60 __FILE__
61 );
62 exit (1);
63 }
64
65 // Now try to connect...
66 try
67 {
68 $dbxlink = new PDO ($pdo_dsn, $db_username, $db_password);
69 }
70 catch (PDOException $e)
71 {
72 showError ("Database connection failed:\n\n" . $e->getMessage(), __FILE__);
73 exit (1);
74 }
75
76 $dbxlink->exec ("set names 'utf8'");
77
78 if (get_magic_quotes_gpc())
79 foreach ($_REQUEST as $key => $value)
80 if (gettype ($value) == 'string')
81 $_REQUEST[$key] = stripslashes ($value);
82
83 if (!set_magic_quotes_runtime (0))
84 {
85 showError ('Failed to turn magic quotes off', __FILE__);
86 exit (1);
87 }
88
89 // Escape any globals before we ever try to use them, but keep a copy of originals.
90 $sic = array();
91 foreach ($_REQUEST as $key => $value)
92 {
93 $sic[$key] = dos2unix ($value);
94 if (gettype ($value) == 'string')
95 $_REQUEST[$key] = escapeString (dos2unix ($value));
96 }
97
98 if (isset ($_SERVER['PHP_AUTH_USER']))
99 $_SERVER['PHP_AUTH_USER'] = escapeString ($_SERVER['PHP_AUTH_USER']);
100 if (isset ($_SERVER['REMOTE_USER']))
101 $_SERVER['REMOTE_USER'] = escapeString ($_SERVER['REMOTE_USER']);
102
103 $dbver = getDatabaseVersion();
104 if ($dbver != CODE_VERSION)
105 {
106 echo '<p align=justify>This Racktables installation seems to be ' .
107 'just upgraded to version ' . CODE_VERSION . ', while the '.
108 'database version is ' . $dbver . '. No user will be ' .
109 'either authenticated or shown any page until the upgrade is ' .
110 "finished. Follow <a href='${root}upgrade.php'>this link</a> and " .
111 'authenticate as administrator to finish the upgrade.</p>';
112 exit (1);
113 }
114
115 if (!mb_internal_encoding ('UTF-8') or !mb_regex_encoding ('UTF-8'))
116 {
117 showError ('Failed setting multibyte string encoding to UTF-8', __FILE__);
118 exit (1);
119 }
120 $configCache = loadConfigCache();
121 if (!count ($configCache))
122 {
123 showError ('Failed to load configuration from the database.', __FILE__);
124 exit (1);
125 }
126
127 require_once 'inc/code.php'; // for getRackCode()
128 $rackCodeCache = loadScript ('RackCodeCache');
129 if ($rackCodeCache == NULL or !strlen ($rackCodeCache))
130 {
131 $rackCode = getRackCode (loadScript ('RackCode'));
132 saveScript ('RackCodeCache', base64_encode (serialize ($rackCode)));
133 }
134 else
135 {
136 $rackCode = unserialize (base64_decode ($rackCodeCache));
137 if ($rackCode === FALSE) // invalid cache
138 {
139 saveScript ('RackCodeCache', '');
140 $rackCode = getRackCode (loadScript ('RackCode'));
141 }
142 }
143
144 // Depending on the 'result' value the 'load' carries either the
145 // parse tree or error message.
146 if ($rackCode['result'] != 'ACK')
147 {
148 // FIXME: display a message with an option to reset RackCode text
149 showError ('Could not load the RackCode due to error: ' . $rackCode['load'], __FILE__);
150 exit (1);
151 }
152 $rackCode = $rackCode['load'];
153 // Only call buildPredicateTable() once and save the result, because it will remain
154 // constant during one execution for constraints processing.
155 $pTable = buildPredicateTable ($rackCode);
156 // Constraints parse trees aren't cached in the database, so the least to keep
157 // things running is to maintain application cache for them.
158 $parseCache = array();
159 $entityCache = array();
160 // used by getExplicitTagsOnly()
161 $tagRelCache = array();
162
163 $taglist = getTagList();
164 $tagtree = treeFromList ($taglist);
165 sortTree ($tagtree, 'taginfoCmp');
166
167 require_once 'inc/auth.php';
168 $auto_tags = array();
169 // Initial chain for the current user.
170 $user_given_tags = array();
171
172 if (!isset ($script_mode) or $script_mode !== TRUE)
173 {
174 // A successful call to authenticate() always generates autotags and somethimes
175 // even given/implicit tags. It also sets remote_username and remote_displayname.
176 authenticate();
177 // Authentication passed.
178 // Note that we don't perform autorization here, so each 1st level page
179 // has to do it in its way, e.g. by calling authorize() after fixContext().
180 session_start();
181 }
182 else
183 {
184 // Some functions require remote_username to be set to something to act correctly,
185 // even though they don't use the value itself.
186 $admin_account = spotEntity ('user', 1);
187 $remote_username = $admin_account['user_name'];
188 unset ($admin_account);
189 }
190
191 $pageno = (isset ($_REQUEST['page'])) ? $_REQUEST['page'] : 'index';
192 // Special handling of tab number to substitute the "last" index where applicable.
193 // Always show explicitly requested tab, substitute the last used name in case
194 // it is awailable, fall back to the default one.
195
196 if (isset ($_REQUEST['tab']))
197 $tabno = $_REQUEST['tab'];
198 elseif (basename($_SERVER['PHP_SELF']) == 'index.php' and getConfigVar ('SHOW_LAST_TAB') == 'yes' and isset ($_SESSION['RTLT'][$pageno]))
199 {
200 $tabno = $_SESSION['RTLT'][$pageno];
201 $url = "${root}?page=$pageno&tab=$tabno";
202 foreach ($_GET as $name=>$value)
203 {
204 if ($name == 'page' or $name == 'tab') continue;
205 if (gettype($value) == 'array')
206 foreach($value as $v)
207 $url .= '&'.urlencode($name.'[]').'='.urlencode($v);
208 else
209 $url .= '&'.urlencode($name).'='.urlencode($value);
210 }
211 header('Location: '.$url);
212 exit();
213 }
214 else
215 $tabno = 'default';
216
217 $op = (isset ($_REQUEST['op'])) ? $_REQUEST['op'] : '';
218
219 require_once 'inc/navigation.php';
220 require_once 'inc/triggers.php';
221 require_once 'inc/gateways.php';
222 if (file_exists ('inc/local.php'))
223 require_once 'inc/local.php';
224
225 // These will be filled in by fixContext()
226 $expl_tags = array();
227 $impl_tags = array();
228 // Initial chain for the current target.
229 $target_given_tags = array();
230
231 ?>