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

Last change on this file was 795, checked in by anonymous, 11 months ago

Update cache durations

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