source: branches/1.1dev/config/boot.inc.php @ 649

Last change on this file since 649 was 608, checked in by anonymous, 7 years ago

Fix undefined index errors

File size: 13.1 KB
Line 
1<?php
2/* boot.inc.php
3 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information. */
4
5
6/* This is the big juicy initialization script that is generic and global to
7 * all sites and scripts (even cron-executed scripts). This file is
8 * included by a site-specific configuration file
9 * which contains initialization and configuration specific to a site. Then
10 * this big-daddy gets loaded, and starts all the trouble. Here we set global
11 * configurations, include files that are used globally, connect to the
12 * database, setup the sessions, and do things that are done for each script
13 * execution, such as checking if the user is logged-in. */
14
15
16// Find the central base file path of this crazy system
17// With some installations of php __FILE__ returns a relative path!
18$_file = preg_match('|^/|', __FILE__) ? __FILE__ : realpath(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . __FILE__);
19define('CODE_BASE', realpath(dirname($_file) . '/..'));
20
21// If the site config file is not included this must be defined here.
22if (!defined('SITE_BASE')) {
23    define('SITE_BASE', '__NO_SITE_BASE__');
24}
25
26/******************************************************************************
27 * INCLUDE GLOBAL LIBRARIES AND CONFIGURATIONS
28 *****************************************************************************/
29
30require_once CODE_BASE . '/lib/Utilities.inc.php';
31require_once CODE_BASE . '/lib/App.inc.php';
32require_once CODE_BASE . '/lib/AuthSQL.inc.php';
33
34require_once CODE_BASE . '/config/security_roster.inc.php';
35
36// Default configurations.
37require_once CODE_BASE . '/config/defaults.inc.php';
38
39// Global configurations overrides site configurations.
40if (file_exists(CODE_BASE . '/../config/global_config.inc.php')) {
41    include CODE_BASE . '/../config/global_config.inc.php';
42}
43
44// Debugging.
45ini_set('display_errors', $CFG->display_errors);
46ini_set('log_errors', '1');
47if (is_dir($CFG->log_directory) && is_writable($CFG->log_directory)) {
48    ini_set('error_log', $CFG->log_directory . '/php_error_log');
49}
50
51/******************************************************************************
52 * DATABASE STUFF
53 *****************************************************************************/
54
55if ($CFG->enable_mysql) { // use mysql database _______________________________
56
57    // MySQL connection parameters.
58    if (!empty($_SERVER['DB_SERVER']) && !empty($_SERVER['DB_NAME']) && !empty($_SERVER['DB_USER']) && !empty($_SERVER['DB_PASS'])) {
59        // We set DB passwords as environment variables in the httpd.conf file,
60        // which is readable only by root.
61        $CFG->dbserver = $_SERVER['DB_SERVER'];
62        $CFG->database = $_SERVER['DB_NAME'];
63        $CFG->username = $_SERVER['DB_USER'];
64        $CFG->password = $_SERVER['DB_PASS'];
65    } else {
66        // For CLI scripts that do not get httpd.conf ENV variables we load a
67        // config file with the credentials. This file must be readable only by the
68        // user that is executing the CLI application! NOT apache, unless the CLI is
69        // spawned as a background process from an apache executed script, in which
70        // case that is the only option.
71        include SITE_BASE . '/../config/db_auth.inc.php';
72    }
73
74    $CFG->dbserver = (!isset($CFG->dbserver) || '' == $CFG->dbserver) ? 'localhost' : $CFG->dbserver;
75
76    if (empty($CFG->database) || empty($CFG->username) || !isset($CFG->password)) { // Allow password to be empty string.
77        logMsg('Database credentials missing.', LOG_WARNING, __FILE__, __LINE__);
78    }
79
80    // Connect to MySQL
81    if ($dbh = mysql_connect($CFG->dbserver, $CFG->username, $CFG->password)) {
82        // Select database
83        mysql_select_db($CFG->database, $dbh);
84    }
85
86    // Connection errors.
87    if (!$dbh || mysql_error($dbh)) {
88        $mysql_error_msg = $dbh ? 'Codebase MySQL error: (' . mysql_errno($dbh) . ') ' . mysql_error($dbh) : 'Codebase MySQL error: Could not connect to server.';
89        if ($CFG->db_debug) {
90            echo $mysql_error_msg . "\n";
91        } else {
92            echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
93        }
94        logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
95        die;
96    }
97
98    /**
99     * A wrapper for mysql_query. Allows us to set the database link_identifier,
100     * to trap errors and ease debugging.
101     *
102     * @param  string  $query   The SQL query to execute
103     * @param  bool    $debug   If true, prints debugging info
104     * @return resource         Query identifier
105     */
106    function dbQuery($query, $debug=false)
107    {
108        global $CFG, $dbh;
109
110        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
111        if ($CFG->db_always_debug || $debug) {
112            logMsg($debugqry, LOG_DEBUG, __FILE__, __LINE__);
113            echo "<!-- --------------------------------------\n" . $debugqry . "\n-->";
114        }
115
116        // Ensure we have an active connection.
117        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
118        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
119        // Unfortunately we'll have redundant code with the reconnection below.
120        if (!mysql_ping($dbh)) {
121            logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_NOTICE, __FILE__, __LINE__);
122            mysql_close($dbh);
123            if ($dbh = mysql_connect('localhost', $CFG->username, $CFG->password)) {
124                mysql_select_db($CFG->database, $dbh);
125            }
126            if (!$dbh || mysql_error($dbh)) {
127                $mysql_error_msg = $dbh ? 'Codebase MySQL error: (' . mysql_errno($dbh) . ') ' . mysql_error($dbh) : 'Codebase MySQL error: Could not connect to server.';
128                if ($CFG->db_debug) {
129                    echo $mysql_error_msg . "\n";
130                } else {
131                    echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
132                }
133                logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
134                die;
135            }
136        }
137
138        $qid = mysql_query($query, $dbh);
139        if (!$qid || mysql_error($dbh)) {
140            if ($CFG->db_debug) {
141                echo '<br><pre style="color:#630; font:9px monaco,geneva,verdana;">';
142                echo '<strong>ERRONEOUS QUERY:</strong>' . htmlspecialchars($debugqry);
143                echo '<br><strong>THE PROBLEM:</strong><br>' . wordwrap(mysql_error($dbh)) . '</pre>';
144            } else {
145                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
146            }
147            logMsg('Query failed: ' . preg_replace('/[\s]+/', ' ', $debugqry) . ' with MySQL error: (' . mysql_errno($dbh) . ') ' . mysql_error($dbh), LOG_EMERG, __FILE__, __LINE__);
148            if ($CFG->db_die_on_failure) {
149                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
150                die;
151            }
152        }
153        return $qid;
154    }
155
156    $mysql_character_sets = array(
157        'utf-8' => 'utf8',
158        'iso-8859-1' => 'latin1',
159    );
160
161    // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
162    if ('' != $CFG->character_set && isset($mysql_character_sets[strtolower($CFG->character_set)])) {
163        dbQuery("/*!40101 SET NAMES '" . $mysql_character_sets[strtolower($CFG->character_set)] . "' */");
164    } else {
165        logMsg(sprintf('%s is not a known character_set.', $CFG->character_set), LOG_ERR, __FILE__, __LINE__);
166    }
167
168} // End enable MySQL._________________________________________________________
169
170/******************************************************************************
171 * SESSION HANDLER INITIALIZATION, AND STARTUP
172 *****************************************************************************/
173
174
175// Skip sessions for some scripts, like the cron executed scripts.
176if (true === $CFG->enable_session) { //________________________________________
177
178    // Set the session ID to one provided in GET/POST. This is necessary for linking
179    // between domains and keeping the same session.
180    if ($ses = getFormData($CFG->session_name, false)) {
181        session_id($ses);
182    }
183
184    // Session parameters.
185    ini_set('session.use_cookies', $CFG->session_use_cookies);
186    ini_set('session.use_trans_sid', false);
187    ini_set('session.entropy_file', '/dev/urandom');
188    ini_set('session.entropy_length', '512');
189    session_name($CFG->session_name);
190
191    if (true === $CFG->enable_mysql_session_handler && true === $CFG->enable_mysql) {
192        // Database session handling.
193        require_once CODE_BASE . '/lib/MySQLSessionHandler.inc.php';
194        $sess_mysql['dbh']             =& $dbh;            // MySQL link identifyer, if we are already connected to the database
195        $sess_mysql['hostname']        = 'localhost';     // MySQL hostname
196        $sess_mysql['user']            = $CFG->username;  // MySQL username
197        $sess_mysql['password']        = $CFG->password;  // MySQL password
198        $sess_mysql['db']              = $CFG->database;  // Database where to store the sessions
199        $sess_mysql['table']           = 'session_tbl';   // Table where to store the sessions
200        ini_set('session.save_handler', 'user');
201        session_set_save_handler('mysqlSessionOpen', 'mysqlSessionClose', 'mysqlSessionRead', 'mysqlSessionWrite', 'mysqlSessionDestroy', 'mysqlSessionGarbage');
202    }
203
204    // Start the session. Access session data using: $_SESSION['...']
205    session_start();
206
207    // Access session data using: $_SESSION['...'].
208    // Initialize here _after_ session has started.
209    if (!isset($_SESSION['_boomerang'])) {
210        $_SESSION['_boomerang'] = array(
211            'url' => array(),
212        );
213    }
214    if (!isset($_SESSION['_messages'])) {
215        $_SESSION['_messages'] = array();
216    }
217
218//     if (isset($_COOKIE[session_name()])) {
219//         logMsg(sprintf('Found session in cookie: %s=%s', session_name(), $_COOKIE[session_name()]), LOG_DEBUG, __FILE__, __LINE__);
220//     }
221//     if (getPost(session_name())) {
222//         logMsg(sprintf('Found session in post: %s=%s', session_name(), getPost(session_name())), LOG_DEBUG, __FILE__, __LINE__);
223//     }
224//     if (getGet(session_name())) {
225//         logMsg(sprintf('Found session in get: %s=%s', session_name(), getGet(session_name())), LOG_DEBUG, __FILE__, __LINE__);
226//     }
227//     logMsg(sprintf('Using session %s=%s', session_name(), session_id()), LOG_DEBUG, __FILE__, __LINE__);
228
229
230    /******************************************************************************
231     * LANGUAGE
232     *****************************************************************************/
233
234    // Set the language.
235    if ($lang = getFormData('lang')) {
236        $_SESSION['_language'] = $lang;
237    } else if (!isset($_SESSION['_language'])) {
238        preg_match('/^([-[:alpha:]]+)/i', getenv('HTTP_ACCEPT_LANGUAGE'), $lang);
239        if (isset($lang[0]) && isset($CFG->site_langs[$lang[0]])) {
240            $_SESSION['_language'] = $lang[0];
241        } else {
242            $_SESSION['_language'] = 'en';
243        }
244    }
245
246} // end enable sessions ______________________________________________________
247
248/******************************************************************************
249 * AUTHENTICATION
250 *****************************************************************************/
251
252
253if (!isset($_admin)) {
254    $_admin = new AuthSQL(array(
255        'auth_name'         => 'admin',
256        'user_tbl'          => 'admin_tbl',
257        'user_id_column'    => 'admin_id',
258        'login_url'         => $CFG->admin_url . '/login.php'
259    ));
260}
261
262if (!isset($_user)) {
263    $_user = new AuthSQL(array(
264        'auth_name'         => 'user',
265        'db_table'          => 'user_tbl',
266        'user_id_column'    => 'user_id',
267        'login_tbl'         => 'login_tbl',
268        'login_url'         => $CFG->site_url . '/login.php',
269        'features'          => array('blocking'=>true, 'abuse_detection'=>true),
270    ));
271}
272
273/******************************************************************************
274 * ET CETERA
275 *****************************************************************************/
276
277// Character set. This will also be printed in the html head.
278header('Content-type: text/html; charset=' . $CFG->character_set);
279
280// Set the version of the codebase we're using.
281$codebase_version_file = dirname(__FILE__) . '/../docs/version.txt';
282if (is_readable($codebase_version_file)) {
283    $CFG->codebase_version = trim(file_get_contents($codebase_version_file));
284    header('X-Codebase-Version: ' . $CFG->codebase_version);
285}
286
287// Capture the ultimate referrer. Used? Not yet.
288if (!isset($_SESSION['_ultimate_referrer'])) {
289    $_SESSION['_ultimate_referrer'] = getenv('HTTP_REFERER');
290}
291
292// The include path is set for the templates.
293// We split them between shared and site specific directories.
294$inc_lang = isset($_SESSION['_language']) ? $_SESSION['_language'] : 'en';
295ini_set('include_path',
296    ini_get('include_path') . PATH_SEPARATOR .
297    SITE_BASE . '/_templates/' . $inc_lang . PATH_SEPARATOR .
298    CODE_BASE . '/templates/' . $inc_lang . PATH_SEPARATOR .
299
300    SITE_BASE . '/_templates/en' . PATH_SEPARATOR .
301    CODE_BASE . '/templates/en' . PATH_SEPARATOR .
302
303    SITE_BASE . '/_templates' . PATH_SEPARATOR .
304    CODE_BASE . '/templates' . PATH_SEPARATOR .
305
306    SITE_BASE . '/../lib'
307);
308
309?>
Note: See TracBrowser for help on using the repository browser.