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

Last change on this file since 549 was 549, checked in by anonymous, 9 years ago

Backporting minor debugging niceites.

File size: 12.6 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_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->database = $_SERVER['DB_NAME'];
62        $CFG->username = $_SERVER['DB_USER'];
63        $CFG->password = $_SERVER['DB_PASS'];
64    } else {
65        // For CLI scripts that do not get httpd.conf ENV variables we load a
66        // config file with the credentials. This file must be readable only by the
67        // user that is executing the CLI application! NOT apache, unless the CLI is
68        // spawned as a background process from an apache executed script, in which
69        // case that is the only option.
70        include SITE_BASE . '/../config/db_auth.inc.php';
71    }
72
73    if (empty($CFG->database) || empty($CFG->username) || !isset($CFG->password)) { // Allow password to be empty string.
74        logMsg('Database credentials missing.', LOG_WARNING, __FILE__, __LINE__);
75    }
76
77    // Connect to MySQL
78    if ($dbh = mysql_connect('localhost', $CFG->username, $CFG->password)) {
79        // Select database
80        mysql_select_db($CFG->database, $dbh);
81    }
82
83    // Connection errors.
84    if (!$dbh || mysql_error($dbh)) {
85        $mysql_error_msg = $dbh ? 'Codebase MySQL error: (' . mysql_errno($dbh) . ') ' . mysql_error($dbh) : 'Codebase MySQL error: Could not connect to server.';
86        if ($CFG->db_debug) {
87            echo $mysql_error_msg . "\n";
88        } else {
89            echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
90        }
91        logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
92        die;
93    }
94
95    /**
96     * A wrapper for mysql_query. Allows us to set the database link_identifier,
97     * to trap errors and ease debugging.
98     *
99     * @param  string  $query   The SQL query to execute
100     * @param  bool    $debug   If true, prints debugging info
101     * @return resource         Query identifier
102     */
103    function dbQuery($query, $debug=false)
104    {
105        global $CFG, $dbh;
106
107        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
108        if ($CFG->db_always_debug || $debug) {
109            logMsg($debugqry, LOG_DEBUG, __FILE__, __LINE__);
110            echo "<!-- --------------------------------------\n" . $debugqry . "\n-->";
111        }
112
113        // Ensure we have an active connection.
114        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
115        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
116        // Unfortunately we'll have redundant code with the reconnection below.
117        if (!mysql_ping($dbh)) {
118            logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_NOTICE, __FILE__, __LINE__);
119            mysql_close($dbh);
120            if ($dbh = mysql_connect('localhost', $CFG->username, $CFG->password)) {
121                mysql_select_db($CFG->database, $dbh);
122            }
123            if (!$dbh || mysql_error($dbh)) {
124                $mysql_error_msg = $dbh ? 'Codebase MySQL error: (' . mysql_errno($dbh) . ') ' . mysql_error($dbh) : 'Codebase MySQL error: Could not connect to server.';
125                if ($CFG->db_debug) {
126                    echo $mysql_error_msg . "\n";
127                } else {
128                    echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
129                }
130                logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
131                die;
132            }
133        }
134
135        $qid = mysql_query($query, $dbh);
136        if (!$qid || mysql_error($dbh)) {
137            if ($CFG->db_debug) {
138                echo '<br><pre style="color:#630; font:9px monaco,geneva,verdana;">';
139                echo '<strong>ERRONEOUS QUERY:</strong>' . htmlspecialchars($debugqry);
140                echo '<br><strong>THE PROBLEM:</strong><br>' . wordwrap(mysql_error($dbh)) . '</pre>';
141            } else {
142                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
143            }
144            logMsg('Query failed: ' . preg_replace('/[\s]+/', ' ', $debugqry) . ' with MySQL error: (' . mysql_errno($dbh) . ') ' . mysql_error($dbh), LOG_EMERG, __FILE__, __LINE__);
145            if ($CFG->db_die_on_failure) {
146                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
147                die;
148            }
149        }
150        return $qid;
151    }
152
153    $mysql_character_sets = array(
154        'utf-8' => 'utf8',
155        'iso-8859-1' => 'latin1',
156    );
157
158    // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
159    if ('' != $CFG->character_set && isset($mysql_character_sets[strtolower($CFG->character_set)])) {
160        dbQuery("/*!40101 SET NAMES '" . $mysql_character_sets[strtolower($CFG->character_set)] . "' */");
161    } else {
162        logMsg(sprintf('%s is not a known character_set.', $CFG->character_set), LOG_ERR, __FILE__, __LINE__);
163    }
164
165} // End enable MySQL._________________________________________________________
166
167/******************************************************************************
168 * SESSION HANDLER INITIALIZATION, AND STARTUP
169 *****************************************************************************/
170
171
172// Skip sessions for some scripts, like the cron executed scripts.
173if (true === $CFG->enable_session) { //________________________________________
174
175    // Set the session ID to one provided in GET/POST. This is necessary for linking
176    // between domains and keeping the same session.
177    if ($ses = getFormData($CFG->session_name, false)) {
178        session_id($ses);
179    }
180
181    // Session parameters.
182    ini_set('session.use_cookies', $CFG->session_use_cookies);
183    ini_set('session.use_trans_sid', false);
184    ini_set('session.entropy_file', '/dev/urandom');
185    ini_set('session.entropy_length', '512');
186    session_name($CFG->session_name);
187
188    if (true === $CFG->enable_mysql_session_handler && true === $CFG->enable_mysql) {
189        // Database session handling.
190        require_once CODE_BASE . '/lib/MySQLSessionHandler.inc.php';
191        $sess_mysql['dbh']             =& $dbh;            // MySQL link identifyer, if we are already connected to the database
192        $sess_mysql['hostname']        = 'localhost';     // MySQL hostname
193        $sess_mysql['user']            = $CFG->username;  // MySQL username
194        $sess_mysql['password']        = $CFG->password;  // MySQL password
195        $sess_mysql['db']              = $CFG->database;  // Database where to store the sessions
196        $sess_mysql['table']           = 'session_tbl';   // Table where to store the sessions
197        ini_set('session.save_handler', 'user');
198        session_set_save_handler('mysqlSessionOpen', 'mysqlSessionClose', 'mysqlSessionRead', 'mysqlSessionWrite', 'mysqlSessionDestroy', 'mysqlSessionGarbage');
199    }
200
201    // Start the session. Access session data using: $_SESSION['...']
202    session_start();
203
204//     if (isset($_COOKIE[session_name()])) {
205//         logMsg(sprintf('Found session in cookie: %s=%s', session_name(), $_COOKIE[session_name()]), LOG_DEBUG, __FILE__, __LINE__);
206//     }
207//     if (getPost(session_name())) {
208//         logMsg(sprintf('Found session in post: %s=%s', session_name(), getPost(session_name())), LOG_DEBUG, __FILE__, __LINE__);
209//     }
210//     if (getGet(session_name())) {
211//         logMsg(sprintf('Found session in get: %s=%s', session_name(), getGet(session_name())), LOG_DEBUG, __FILE__, __LINE__);
212//     }
213//     logMsg(sprintf('Using session %s=%s', session_name(), session_id()), LOG_DEBUG, __FILE__, __LINE__);
214
215
216    /******************************************************************************
217     * LANGUAGE
218     *****************************************************************************/
219
220    // Set the language.
221    if ($lang = getFormData('lang')) {
222        $_SESSION['_language'] = $lang;
223    } else if (!isset($_SESSION['_language'])) {
224        preg_match('/^([-[:alpha:]]+)/i', getenv('HTTP_ACCEPT_LANGUAGE'), $lang);
225        if (isset($CFG->site_langs[$lang[0]])) {
226            $_SESSION['_language'] = $lang[0];
227        } else {
228            $_SESSION['_language'] = 'en';
229        }
230    }
231
232} // end enable sessions ______________________________________________________
233
234/******************************************************************************
235 * AUTHENTICATION
236 *****************************************************************************/
237
238
239if (!isset($_admin)) {
240    $_admin = new AuthSQL(array(
241        'auth_name'         => 'admin',
242        'user_tbl'          => 'admin_tbl',
243        'user_id_column'    => 'admin_id',
244        'login_url'         => $CFG->admin_url . '/login.php'
245    ));
246}
247
248if (!isset($_user)) {
249    $_user = new AuthSQL(array(
250        'auth_name'         => 'user',
251        'db_table'          => 'user_tbl',
252        'user_id_column'    => 'user_id',
253        'login_tbl'         => 'login_tbl',
254        'login_url'         => $CFG->site_url . '/login.php',
255        'features'          => array('blocking'=>true, 'abuse_detection'=>true),
256    ));
257}
258
259/******************************************************************************
260 * ET CETERA
261 *****************************************************************************/
262
263// Character set. This will also be printed in the html head.
264header('Content-type: text/html; charset=' . $CFG->character_set);
265
266// Set the version of the codebase we're using.
267$codebase_version_file = dirname(__FILE__) . '/../docs/version.txt';
268if (is_readable($codebase_version_file)) {
269    $CFG->codebase_version = trim(file_get_contents($codebase_version_file));
270    header('X-Codebase-Version: ' . $CFG->codebase_version);
271}
272
273// Capture the ultimate referrer. Used? Not yet.
274if (!isset($_SESSION['_ultimate_referrer'])) {
275    $_SESSION['_ultimate_referrer'] = getenv('HTTP_REFERER');
276}
277
278// The include path is set for the templates.
279// We split them between shared and site specific directories.
280$inc_lang = isset($_SESSION['_language']) ? $_SESSION['_language'] : 'en';
281ini_set('include_path',
282    ini_get('include_path') . PATH_SEPARATOR .
283    SITE_BASE . '/_templates/' . $inc_lang . PATH_SEPARATOR .
284    CODE_BASE . '/templates/' . $inc_lang . PATH_SEPARATOR .
285
286    SITE_BASE . '/_templates/en' . PATH_SEPARATOR .
287    CODE_BASE . '/templates/en' . PATH_SEPARATOR .
288
289    SITE_BASE . '/_templates' . PATH_SEPARATOR .
290    CODE_BASE . '/templates'
291);
292
293?>
Note: See TracBrowser for help on using the repository browser.