root/trunk/wikka.php

Revision 1842, 24.8 KB (checked in by BrianKoontz, 18 months ago)

Implemented CSRF tokens in all POST forms. Refs #1098.

Line 
1<?php
2/**
3 * The Wikka mainscript.
4 *
5 * This file is called each time a request is made from the browser.
6 * Most of the core methods used by the engine are located in the Wakka class.
7 * @see Wakka
8 * This file was originally written by Hendrik Mans for WakkaWiki
9 * and released under the terms of the modified BSD license
10 * @see /docs/WakkaWiki.LICENSE
11 *
12 * @package Wikka
13 * @subpackage Core
14 * @version $Id$
15 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
16 * @see /docs/Wikka.LICENSE
17 * @filesource
18 *
19 * @author      {@link http://www.mornography.de/ Hendrik Mans}
20 * @author      {@link http://wikkawiki.org/JsnX Jason Tourtelotte}
21 * @author      {@link http://wikkawiki.org/JavaWoman Marjolein Katsma}
22 * @author      {@link http://wikkawiki.org/NilsLindenberg Nils Lindenberg}
23 * @author      {@link http://wikkawiki.org/DotMG Mahefa Randimbisoa}
24 * @author      {@link http://wikkawiki.org/DarTar Dario Taraborelli}
25 * @author      {@link http://wikkawiki.org/BrianKoontz Brian Koontz}
26 * @author      {@link http://wikkawiki.org/TormodHaugen Tormod Haugen}
27 *
28 * @copyright Copyright 2002-2003, Hendrik Mans <hendrik@mans.de>
29 * @copyright Copyright 2004-2005, Jason Tourtelotte <wikka-admin@jsnx.com>
30 * @copyright Copyright 2006-2010, {@link http://wikkawiki.org/CreditsPage Wikka Development Team}
31 *
32 * @todo use templating class for page generation;
33 * @todo add phpdoc documentation for configuration array elements;
34 */
35
36// ---------------------- DEBUGGING AND ERROR REPORTING -----------------------
37if(version_compare(phpversion(),'5.3','<'))
38        error_reporting(E_ALL);
39else
40        error_reporting(E_ALL & !E_DEPRECATED);
41// ---------------------- END DEBUGGING AND ERROR REPORTING -------------------
42
43// ---------------------------- VERSIONING ------------------------------------
44/**#@+
45 * Defines current Wikka version.
46 */
47include_once('version.php');
48
49// ----------------------------- BASIC CONSTANTS -------------------------------
50/**#@+
51 * Simple constant. May be made a configurable value.
52 */
53/**
54 * Defines the default cookie name.
55 */
56if (!defined('BASIC_COOKIE_NAME')) define('BASIC_COOKIE_NAME', 'Wikkawiki');
57/**
58 * Length to use for generated part of id attribute.
59 */
60define('ID_LENGTH',10);                 // @@@ maybe make length configurable
61/**
62 * Character used for multi-path lists
63 */
64if(!defined('PATH_DIVIDER')) define('PATH_DIVIDER', ',');
65/**#@-*/
66/**#@+
67 * Minimum version requirement.
68 */
69if (!defined('MINIMUM_PHP_VERSION'))    define('MINIMUM_PHP_VERSION', '5.0');
70if (!defined('MINIMUM_MYSQL_VERSION'))  define('MINIMUM_MYSQL_VERSION', '4.1');
71/**#@-*/
72// ----------------------------- END BASIC CONSTANTS ---------------------------
73
74// ------------ CRITICAL ERROR MESSAGES USED BEFORE LANG FILE LOADED -----------
75// Do not move these declaration to lang files.
76if(!defined('ERROR_WRONG_PHP_VERSION')) define('ERROR_WRONG_PHP_VERSION', 'Wikka requires PHP %s or higher!');  // %s - version number
77if(!defined('ERROR_MYSQL_SUPPORT_MISSING')) define('ERROR_MYSQL_SUPPORT_MISSING', 'PHP can\'t find MySQL support but Wikka requires MySQL. Please check the output of <tt>phpinfo()</tt> in a php document for MySQL support: it needs to be compiled into PHP, the module itself needs to be present in the expected location, <strong>and</strong> php.ini needs to have it enabled.<br />Also note that you cannot have <tt>mysqli</tt> and <tt>mysql</tt> support both enabled at the same time.<br />Please double-check all of these things, restart your webserver after any fixes, and then try again!');
78if(!defined('ERROR_WAKKA_LIBRARY_MISSING')) define('ERROR_WAKKA_LIBRARY_MISSING','The necessary file "libs/Wakka.class.php" could not be found. To run Wikka, please make sure the file exists and is placed in the right directory!');
79// --------END: CRITICAL ERROR MESSAGES USED BEFORE LANG FILE LOADED -----------
80
81// ----------------------------- SANITY CHECKS ---------------------------------
82
83// More intelligent version check, more intelligently placed ;)
84if (!function_exists('version_compare') ||
85        version_compare(phpversion(),MINIMUM_PHP_VERSION,'<')   // < PHP minimum version??
86   )
87{
88        $php_version_error = sprintf(ERROR_WRONG_PHP_VERSION,MINIMUM_PHP_VERSION);
89        die($php_version_error);                # fatalerror    !!! default error in English
90}
91// MySQL needs to be installed and available
92// @@@ message could be refined by detecting detect OS (mention module name) and maybe server name
93if (!function_exists('mysql_connect'))
94{
95        die(ERROR_MYSQL_SUPPORT_MISSING);
96}
97
98/**
99 * Include main library if it exists.
100 * @see libs/Wakka.class.php
101 */
102if (file_exists('libs/Wakka.class.php'))
103{
104        require_once('libs/Compatibility.lib.php');
105        require_once('libs/Wakka.class.php');
106}
107else
108{
109        die(ERROR_WAKKA_LIBRARY_MISSING);
110}
111
112// ----------------------------- END SANITY CHECKS ----------------------------
113
114ob_start();
115global $tstart;
116$tstart = getmicrotime();
117ini_set('magic_quotes_runtime', 0);
118if (get_magic_quotes_gpc())
119{
120        magicQuotesWorkaround($_POST);
121        magicQuotesWorkaround($_GET);
122        magicQuotesWorkaround($_COOKIE);
123}
124
125/**
126 * Default configuration.
127 */
128// attempt to derive base URL fragments and whether rewrite mode is enabled (#438)
129$t_domain       = $_SERVER['SERVER_NAME'];
130$t_scheme = ((isset($_SERVER['HTTPS'])) && !empty($_SERVER['HTTPS']) && 'off' != $_SERVER['HTTPS']) ? 'https://' : 'http://';
131$t_port = ':'.$_SERVER['SERVER_PORT'];
132if ((('http://' == $t_scheme) && (':80' == $t_port)) || (('https://' == $t_scheme) && (':443' == $t_port)))
133{
134        $t_port = '';
135}
136$t_request      = $_SERVER['REQUEST_URI'];
137// append slash if $t_request does not end with either a slash or the string .php
138if (!preg_match('@(\\.php|/)$@i', $t_request))
139{
140//      $t_request .= '/';
141}
142
143if (preg_match('@\.php$@', $t_request) && !preg_match('@wikka\.php$@', $t_request))
144{
145        // handle "overridden" redirect from index.php
146        $t_request = preg_replace('@/[^.]+\.php@', '/wikka.php', $t_request);   // handle "overridden" redirect from index.php
147}
148
149if ( !preg_match('@wakka=@',$_SERVER['REQUEST_URI']) && isset($_SERVER['QUERY_STRING']) && preg_match('@wakka=@',$_SERVER['QUERY_STRING']))
150{
151        // looks like we got a rewritten request via .htaccess
152        // remove 'wikka.php' and request (page name) from 'request' part: should not be part of base_url!
153        $query_part = preg_replace('@wakka=@', '', $_SERVER['QUERY_STRING']);
154        $t_request  = preg_replace('@'.preg_quote('wikka.php').'@', '', $t_request);
155        $t_request  = preg_replace('@'.preg_quote($query_part).'@', '', $t_request);
156        $t_query = '';
157        $t_rewrite_mode = 1;
158}
159else
160{
161        // no rewritten request apparent
162        $t_query = '?wakka=';
163        $t_rewrite_mode = 0;
164}
165
166// ---------------------- DEFINE URL DOMAIN / PATH -----------------------------
167/**#@+*
168 * URL or URL component, derived just once for later usage.
169 */
170// first derive domain, path and base_url, as well as cookie path just once
171// so they are ready for later use.
172// detect actual scheme (might be https!)       @@@ TEST
173// please recopy modif into setup/test/test-mod-rewrite.php
174$scheme = ((isset($_SERVER['HTTPS'])) && !empty($_SERVER['HTTPS']) && 'off' != $_SERVER['HTTPS']) ? 'https://' : 'http://';
175$server_port = ':'.$_SERVER['SERVER_PORT'];
176if ((('http://' == $scheme) && (':80' == $server_port)) || (('https://' == $scheme) && (':443' == $server_port)))
177{
178        $server_port = '';
179}
180/**
181 * URL fragment consisting of scheme + domain part.
182 * Represents the domain URL where the current instance of Wikka is located.
183 * This variable can be overriden in {@link override.config.php}
184 *
185 * @var string
186 */
187if (!defined('WIKKA_BASE_DOMAIN_URL')) define('WIKKA_BASE_DOMAIN_URL', $scheme.$_SERVER['SERVER_NAME'].$server_port);
188/**
189 * URL fragment consisting of a path component.
190 * Points to the instance of Wikka within {@link WIKKA_BASE_DOMAIN_URL}.
191 *
192 * @var string
193 */
194define('WIKKA_BASE_URL_PATH', preg_replace('/wikka\\.php/', '', $_SERVER['SCRIPT_NAME']));
195/**
196 * Base URL consisting of {@link WIKKA_BASE_DOMAIN_URL} and {@link WIKKA_BASE_URL_PATH} concatenated.
197 * Ready to append a relative path to a "static" file to.
198 *
199 * @var string
200 */
201define('WIKKA_BASE_URL', WIKKA_BASE_DOMAIN_URL.WIKKA_BASE_URL_PATH);
202/**
203 * Path to be used for cookies.
204 * Derived from {@link WIKKA_BASE_URL_PATH}
205 *
206 * @var string
207 */
208define('WIKKA_COOKIE_PATH', ('/' == WIKKA_BASE_URL_PATH) ? '/' : substr(WIKKA_BASE_URL_PATH, 0, -1));
209/**
210 * Default number of hours after which a permanent cookie is to expire: corresponds to 90 days.
211 */
212if (!defined('DEFAULT_COOKIE_EXPIRATION_HOURS')) define('DEFAULT_COOKIE_EXPIRATION_HOURS',90 * 24);
213/**
214 * Path for Wikka libs
215 *
216 * @var string
217 */
218if(!defined('WIKKA_LIBRARY_PATH')) define('WIKKA_LIBRARY_PATH', 'lib');
219
220/**#@-*/
221// ----------------------- END URL DOMAIN / PATH -------------------------------
222
223
224$wakkaDefaultConfig = array(
225        'mysql_host'                            => 'localhost',
226        'mysql_database'                        => 'wikka',
227        'mysql_user'                            => 'wikka',
228        'table_prefix'                          => 'wikka_',
229
230        'root_page'                                     => 'HomePage',
231        'wakka_name'                            => 'MyWikkaSite',
232//      'base_url'                                      => $t_scheme.$t_domain.$t_port.$t_request.$t_query,
233        'rewrite_mode'                          => $t_rewrite_mode,
234        'wiki_suffix'                           => '@wikka',
235        'enable_user_host_lookup'       => '0', #enable (1) or disable (0, default) lookup of user hostname from IP address
236
237        'action_path'                           => 'plugins/actions'.PATH_DIVIDER.'actions',
238        'handler_path'                          => 'plugins/handlers'.PATH_DIVIDER.'handlers',
239        'lang_path'                                     => 'plugins/lang',
240        'gui_editor'                            => '1',
241        'default_comment_display'       => 'threaded',
242        'theme'                                         => 'light',
243
244        // formatter and code highlighting paths
245        'wikka_formatter_path'          => 'plugins/formatters'.PATH_DIVIDER.'formatters',              # (location of Wikka formatter - REQUIRED)
246        'wikka_highlighters_path'       => 'formatters',                # (location of Wikka code highlighters - REQUIRED)
247        'geshi_path'                            => '3rdparty/plugins/geshi',                            # (location of GeSHi package)
248        'geshi_languages_path'          => '3rdparty/plugins/geshi/geshi',              # (location of GeSHi language highlighting files)
249
250        // template
251        'wikka_template_path'           => 'plugins/templates'.PATH_DIVIDER.'templates',                # (location of Wikka template files - REQUIRED)
252        'feedcreator_path'                      => '3rdparty/core/feedcreator',
253        'menu_config_path'                      => 'config', #858
254        'safehtml_path'                         => '3rdparty/core/safehtml',
255        'referrers_purge_time'          => '30',
256        'pages_purge_time'                      => '0',
257        'xml_recent_changes'            => '10',
258        'hide_comments'                         => '0',
259        'require_edit_note'                     => '0',         # edit note optional (0, default), edit note required (1) edit note disabled (2)
260        'anony_delete_own_comments'     => '1',
261        'public_sysinfo'                        => '0',         # enable or disable public display of system information in SysInfo
262        'double_doublequote_html'       => 'safe',
263        'sql_debugging'                         => '0',
264        'admin_users'                           => '',
265        'admin_email'                           => '',
266        'upload_path'                           => 'uploads',
267        'mime_types'                            => 'mime_types.txt',
268
269        // code hilighting with GeSHi
270        'geshi_header'                          => 'div',       # 'div' (default) or 'pre' to surround code block
271        'geshi_line_numbers'            => '1',         # disable line numbers (0), or enable normal (1) or fancy line numbers (2)
272        'geshi_tab_width'                       => '4',         # set tab width
273        'grabcode_button'                       => '1',         # allow code block downloading
274
275        'wikiping_server'                       => '',
276
277        'default_write_acl'                     => '+',
278        'default_read_acl'                      => '*',
279        'default_comment_read_acl'              => '*',
280        'default_comment_post_acl'              => '+',
281        'allow_user_registration'       => '1',
282        'enable_version_check'      => '1',
283        'version_check_interval'        => '1h',
284        'default_lang'                          => 'en',
285        'spamlog_path'                          => './spamlog.txt.php',
286        'badwords_path'                         => './badwords.txt.php',
287        'spam_logging'                          => '0',
288        'content_filtering'                     => '0',
289        'max_new_document_urls'         => '15',
290        'max_new_comment_urls'          => '6',
291        'max_new_feedback_urls'         => '6',
292        'utf8_compat_search'            => '0'
293        );
294
295// load config
296$wakkaConfig = array();
297if (file_exists('wakka.config.php')) rename('wakka.config.php', 'wikka.config.php"');   // upgrade from Wakka
298#if (!$configfile = GetEnv("WAKKA_CONFIG")) $configfile = "wikka.config.php";
299if (defined('WAKKA_CONFIG'))    // use a define instead of GetEnv [SEC]
300{
301        $configfile = WAKKA_CONFIG;
302}
303else
304{
305        $configfile = 'wikka.config.php';
306}
307if (file_exists($configfile)) include($configfile);
308$wakkaConfigLocation = $configfile;
309
310// remove obsolete config settings (should come before merge!)
311//TODO move these checks to a directive file to be used by the installer/upgrader, #97
312if (isset($wakkaConfig['header_action']))
313{
314        unset($wakkaConfig['header_action']); //since 1.1.6.4
315}
316if (isset($wakkaConfig['footer_action'])) //since 1.1.6.4
317{
318        unset($wakkaConfig['footer_action']);
319}
320
321// Remove old stylesheet, #6
322if(isset($wakkaConfig['stylesheet']))
323{
324        unset($wakkaConfig['stylesheet']); // since 1.2
325}
326
327// Add plugin paths if they do not already exist
328if(isset($wakkaConfig['action_path']) && preg_match('/plugins\/actions/', $wakkaConfig['action_path']) <= 0)
329        $wakkaConfig['action_path'] = "plugins/actions," .  $wakkaConfig['action_path'];
330if(isset($wakkaConfig['handler_path']) && preg_match('/plugins\/handlers/', $wakkaConfig['handler_path']) <= 0)
331        $wakkaConfig['handler_path'] = "plugins/handlers," .  $wakkaConfig['handler_path'];
332if(isset($wakkaConfig['wikka_template_path']) && preg_match('/plugins\/templates/', $wakkaConfig['wikka_template_path']) <= 0)
333        $wakkaConfig['wikka_template_path'] = "plugins/templates," .  $wakkaConfig['wikka_template_path'];
334if(isset($wakkaConfig['wikka_formatter_path']) && preg_match('/plugins\/formatters/', $wakkaConfig['wikka_formatter_path']) <= 0)
335        $wakkaConfig['wikka_formatter_path'] = "plugins/formatters," .  $wakkaConfig['wikka_formatter_path'];
336if(isset($wakkaConfig['lang_path']) && preg_match('/plugins\/lang/', $wakkaConfig['lang_path']) <= 0)
337        $wakkaConfig['lang_path'] = "plugins/lang," .  $wakkaConfig['lang_path'];
338
339$wakkaConfig = array_merge($wakkaDefaultConfig, $wakkaConfig);  // merge defaults with config from file
340
341// ---------------------------- LANGUAGE DEFAULTS -----------------------------
342
343/**
344  * php-gettext
345  */
346  include_once('localization.php');
347
348/**
349 * Include language file(s) if it/they exist(s).
350 * @see /lang/en.inc.php
351 *
352 * Note that all lang_path entries in wikka.config.php are scanned for
353 * default_lang files in the order specified in lang_path, with the
354 * fallback language pack scanned last to pick up any undefined
355 * strings.
356 *
357 * TODO: Handlers and actions that use their own language packs are
358 * responsible for loading their own translation strings.  This
359 * process should be unified across the application.
360 *
361 */
362$default_lang = $wakkaConfig['default_lang'];
363$fallback_lang = 'en';
364$default_lang_path = 'lang'.DIRECTORY_SEPARATOR.$default_lang;
365$plugin_lang_path = $wakkaConfig['lang_path'].DIRECTORY_SEPARATOR.$default_lang;
366$fallback_lang_path = 'lang'.DIRECTORY_SEPARATOR.$fallback_lang;
367$default_lang_strings = $default_lang_path.DIRECTORY_SEPARATOR.$default_lang.'.inc.php';
368$plugin_lang_strings = $plugin_lang_path.DIRECTORY_SEPARATOR.$default_lang.'.inc.php';
369$fallback_lang_strings = $fallback_lang_path.DIRECTORY_SEPARATOR.$fallback_lang.'.inc.php';
370$lang_packs_found = false;
371if (file_exists($plugin_lang_strings))
372{
373        require_once($plugin_lang_strings);
374        $lang_packs_found = true;
375}
376if (file_exists($default_lang_strings))
377{
378        require_once($default_lang_strings);
379        $lang_packs_found = true;
380}
381if (file_exists($fallback_lang_strings))
382{
383        require_once($fallback_lang_strings);
384        $lang_packs_found = true;
385}
386if(!$lang_packs_found)
387{
388        die('Language file '.$default_lang_strings.' not found! In addition, the default language file '.$fallback_lang_strings.' is missing. Please add the file(s).');
389}
390
391if(!defined('WIKKA_LANG_PATH')) define('WIKKA_LANG_PATH', $default_lang_path);
392// ------------------------- END LANGUAGE DEFAULTS -----------------------------
393
394/**
395 * To activate multisite deployment capabilities, just create an empty file multi.config.php in
396 * your Wikkawiki installation directory. This file can contain an array definition for
397 * $multiConfig.
398 * Relevant keys in the array are a global directory for local settings 'local_config' and
399 * designated directories for different host requests, e.g. you may want http://example.com
400 * and http://www.example.com using the same local config file.
401 * 'http_www_example_com' => 'http.example.com'
402 * 'http_example_com' => 'http.example.com'
403*/
404$multisite_configfile = 'multi.config.php';
405if (file_exists($multisite_configfile))
406{
407        $wakkaGlobalConfig = $wakkaConfig;      // copy config file, #878
408        $multiDefaultConfig = array(
409                'local_config'            => 'wikka.config' # path to local configs
410        );
411        $multiConfig = array();
412
413    include($multisite_configfile);
414
415    $multiConfig = array_merge($multiDefaultConfig, $multiConfig);    // merge default multi config with config from file
416
417    $configkey = str_replace('://','_',$t_scheme).str_replace('.','_',$t_domain);
418    if($t_port != '') $configkey .= '_'.$t_port;
419
420
421/**
422 * Admin can decide to put a specific local config in a more readable and shorter directory.
423 * The $configkey is created as 'protocol_thirdleveldomain_secondleveldomain_topleveldomain'
424 * Subdirectories are not supported at the moment, but should be easy to implement.
425 * If no designated directory is found in multi.config.php, the script uses the $configkey
426 * value and replaces all underscore by dots:
427 * protocol.thirdleveldomain.secondleveldomain.topleveldomain e.g.
428 * http.www.example.com
429*/
430    if (isset($multiConfig[$configkey])) $configpath = $multiConfig[$configkey];
431    else
432    {
433        $requested_host = str_replace('_','.',$configkey);
434        $configpath = $multiConfig['local_config'].DIRECTORY_SEPARATOR.$requested_host;
435        $multiConfig[$configkey] = $requested_host;
436    }
437
438    $local_configfile = $configpath.DIRECTORY_SEPARATOR.'local.config.php';
439/**
440 * As each site may differ in its configuration and capabilities, we should consider using
441 * plugin directories below the $configpath. Effectively, this replaces the 1.1.6.6 plugins
442 * folder. It goes even a little bit further by providing a site specific upload directory.
443*/
444
445    $localDefaultConfig = array(
446        'menu_config_path'                      => $configpath.DIRECTORY_SEPARATOR.'config'.PATH_DIVIDER.'config',
447        'action_path'                           => $configpath.DIRECTORY_SEPARATOR.'actions'.PATH_DIVIDER.'plugins'.DIRECTORY_SEPARATOR.'actions'.PATH_DIVIDER.'actions',
448        'handler_path'                          => $configpath.DIRECTORY_SEPARATOR.'handlers'.PATH_DIVIDER.'plugins'.DIRECTORY_SEPARATOR.'handlers'.PATH_DIVIDER.'handlers',
449        'wikka_formatter_path'          => $configpath.DIRECTORY_SEPARATOR.'formatters'.PATH_DIVIDER.'plugins'.DIRECTORY_SEPARATOR.'formatters'.PATH_DIVIDER.'formatters',        # (location of Wikka formatter - REQUIRED)
450        'wikka_highlighters_path'       => $configpath.DIRECTORY_SEPARATOR.'formatters'.PATH_DIVIDER.'plugins'.DIRECTORY_SEPARATOR.'formatters'.PATH_DIVIDER.'formatters',        # (location of Wikka code highlighters - REQUIRED)
451        'wikka_template_path'           => $configpath.DIRECTORY_SEPARATOR.'templates'.PATH_DIVIDER.'plugins'.DIRECTORY_SEPARATOR.'templates'.PATH_DIVIDER.'templates',        # (location of Wikka template files - REQUIRED)
452        'upload_path'                           => $configpath.DIRECTORY_SEPARATOR.'uploads'
453    );
454    $localConfig = array();
455    if (!file_exists($configpath))
456    {
457        $path_parts = explode(DIRECTORY_SEPARATOR,$configpath);
458        $partialpath = '';
459        foreach($path_parts as $part)
460        {
461            $partialpath .= $part;
462            if (!file_exists($partialpath)) mkdir($partialpath,0755);
463            $partialpath .= DIRECTORY_SEPARATOR;
464        }
465        mkdir($configpath.DIRECTORY_SEPARATOR.'config',0700);
466        mkdir($configpath.DIRECTORY_SEPARATOR.'actions',0700);
467        mkdir($configpath.DIRECTORY_SEPARATOR.'handlers',0700);
468        mkdir($configpath.DIRECTORY_SEPARATOR.'handlers'.DIRECTORY_SEPARATOR.'page',0700);
469        mkdir($configpath.DIRECTORY_SEPARATOR.'formatters',0700);
470        mkdir($configpath.DIRECTORY_SEPARATOR.'templates',0700);
471        mkdir($configpath.DIRECTORY_SEPARATOR.'uploads',0755);
472//        if(file_exists($wakkaConfig['stylesheet'])) copy($wakkaConfig['stylesheet'],$localDefaultConfig['stylesheet']);
473    }
474    else if (file_exists($local_configfile)) include($local_configfile);
475
476    $wakkaGlobalConfig = array_merge($wakkaGlobalConfig, $localDefaultConfig);    // merge global config with default local config
477
478    $wakkaConfigLocation = $local_configfile;
479
480    $wakkaConfig = array_merge($wakkaGlobalConfig, $wakkaConfig);    // merge localized global config with local config from file
481}
482
483/**
484 * Check for locking.
485 */
486if (file_exists('locked'))
487{
488        // read password from lockfile
489        $lines = file("locked");
490        $lockpw = trim($lines[0]);
491
492        // is authentification given?
493        $ask = false;
494        if (isset($_SERVER["PHP_AUTH_USER"])) {
495                if (!(($_SERVER["PHP_AUTH_USER"] == "admin") && ($_SERVER["PHP_AUTH_PW"] == $lockpw))) {
496                        $ask = true;
497                }
498        } else {
499                $ask = true;
500        }
501
502        if ($ask) {
503                header("WWW-Authenticate: Basic realm=\"".$wakkaConfig["wakka_name"]." Install/Upgrade Interface\"");
504                header("HTTP/1.0 401 Unauthorized");
505                print T_("This site is currently being upgraded. Please try again later.");
506                exit;
507        }
508}
509
510/**
511 * Compare versions, start installer if necessary.
512 */
513if (!isset($wakkaConfig['wakka_version'])) $wakkaConfig['wakka_version'] = 0;
514if ($wakkaConfig['wakka_version'] !== WAKKA_VERSION)
515{
516        /**
517         * Start installer.
518         *
519         * Data entered by the user is submitted in $_POST, next action for the
520         * installer (which will receive this data) is passed as a $_GET parameter!
521         */
522        $installAction = 'default';
523        if (isset($_GET['installAction'])) $installAction = trim($_GET['installAction']);       #312
524        if (file_exists('setup'.DIRECTORY_SEPARATOR.'header.php'))
525        include('setup'.DIRECTORY_SEPARATOR.'header.php'); else print '<em class="error">'.ERROR_SETUP_HEADER_MISSING.'</em>'; #89
526        if
527        (file_exists('setup'.DIRECTORY_SEPARATOR.$installAction.'.php'))
528        include('setup'.DIRECTORY_SEPARATOR.$installAction.'.php'); else print '<em class="error">'.ERROR_SETUP_FILE_MISSING.'</em>'; #89
529        if (file_exists('setup'.DIRECTORY_SEPARATOR.'footer.php'))
530        include('setup'.DIRECTORY_SEPARATOR.'footer.php'); else print '<em class="error">'.ERROR_SETUP_FOOTER_MISSING.'</em>'; #89
531        exit;
532}
533
534/**
535 * Start session.
536 */
537$base_url_path = preg_replace('/wikka\.php/', '', $_SERVER['SCRIPT_NAME']);
538$wikka_cookie_path = ('/' == $base_url_path) ? '/' : substr($base_url_path,0,-1);
539session_set_cookie_params(0, $wikka_cookie_path);
540session_name(md5(BASIC_COOKIE_NAME.$wakkaConfig['wiki_suffix']));
541session_start();
542if(!isset($_SESSION['CSRFToken']))
543{
544        $_SESSION['CSRFToken'] = sha1(getmicrotime());
545}
546
547// fetch wakka location
548/**
549 * Fetch wakka location (requested page + parameters)
550 *
551 * @todo files action uses POST, everything else uses GET #312
552 */
553$wakka = $_GET['wakka']; #312
554
555/**
556 * Remove leading slash.
557 */
558$wakka = preg_replace("/^\//", "", $wakka);
559
560/**
561 * Extract pagename and handler from URL
562 *
563 * Note this splits at the FIRST / so $handler may contain one or more slashes;
564 * this is not allowed, and ultimately handled in the Handler() method. [SEC]
565 */
566if (preg_match("#^(.+?)/(.*)$#", $wakka, $matches)) list(, $page, $handler) = $matches;
567else if (preg_match("#^(.*)$#", $wakka, $matches)) list(, $page) = $matches;
568//Fix lowercase mod_rewrite bug: URL rewriting makes pagename lowercase. #135
569if ((strtolower($page) == $page) && (isset($_SERVER['REQUEST_URI']))) #38
570{
571        $pattern = preg_quote($page, '/');
572        if (preg_match("/($pattern)/i", urldecode($_SERVER['REQUEST_URI']), $match_url))
573        {
574                $page = $match_url[1];
575        }
576}
577//$page = preg_replace('/_/', ' ', $page);
578
579/**
580 * Create Wakka object
581 */
582$wakka = instantiate('Wakka',$wakkaConfig);
583
584/**
585 * Check for database access.
586 */
587if (!$wakka->dblink)
588{
589        echo '<em class="error">'.T_("Error: Unable to connect to the database.").'</em>';
590        exit;
591}
592
593/**
594 * Save session ID
595 */
596$user = $wakka->GetUser();
597// Only store sessions for real users!
598if(NULL != $user)
599{
600        $res = $wakka->LoadSingle("SELECT * FROM ".$wakka->config['table_prefix']."sessions WHERE sessionid='".session_id()."' AND userid='".$user['name']."'");
601        if(isset($res))
602        {
603                // Just update the session_start time
604                $wakka->Query("UPDATE ".$wakka->config['table_prefix']."sessions SET session_start=FROM_UNIXTIME(".$wakka->GetMicroTime().") WHERE sessionid='".session_id()."' AND userid='".$user['name']."'");
605        }
606        else
607        {
608                // Create new session record
609                $wakka->Query("INSERT INTO ".$wakka->config['table_prefix']."sessions (sessionid, userid, session_start) VALUES('".session_id()."', '".$user['name']."', FROM_UNIXTIME(".$wakka->GetMicroTime()."))");
610        }
611}
612
613/**
614 * Run the engine.
615 */
616if (!isset($handler)) $handler='';
617$wakka->Run($page, $handler);
618$content =  ob_get_contents();
619/**
620 * Use gzip compression if possible.
621 */
622/*
623if ( isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strstr ($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') && function_exists('gzencode') ) #38
624{
625        // Tell the browser the content is compressed with gzip
626        header ("Content-Encoding: gzip");
627        $page_output = gzencode($content);
628        $page_length = strlen($page_output);
629} else {
630 */
631        $page_output = $content;
632        $page_length = strlen($page_output);
633//}
634
635// header("Cache-Control: pre-check=0");
636header("Cache-Control: no-cache");
637// header("Pragma: ");
638// header("Expires: ");
639
640$etag =  md5($content);
641header('ETag: '.$etag);
642
643header('Content-Length: '.$page_length);
644ob_end_clean();
645
646/**
647 * Output the page.
648 */
649echo $page_output;
650?>
Note: See TracBrowser for help on using the browser.