}
    serendipity_login(false);
}
if (isset($_SESSION['serendipityAuthorid'])) {
    serendipity_load_configuration($_SESSION['serendipityAuthorid']);
    $serendipity['lang'] = serendipity_getPostAuthSessionLanguage();
}
// Try to fix some path settings. It seems common users have this setting wrong
// when s9y is installed into the root directory, especially 0.7.1 upgrade users.
if (empty($serendipity['serendipityHTTPPath'])) {
    $serendipity['serendipityHTTPPath'] = '/';
}
/* Changing this is NOT recommended, rewrite rules does not take them into account - yet */
serendipity_initPermalinks();
// Apply constants/definitions from custom permalinks
serendipity_permalinkPatterns();
/*
 *   Load main language file again, because now we have the preferred language
 */
include S9Y_INCLUDE_PATH . 'include/lang.inc.php';
/*
 * Reset charset definition now that final language is known
 */
$serendipity['charsets'] = array('UTF-8/' => 'UTF-8', '' => CHARSET_NATIVE);
/*
 *   Set current locale, if any has been defined
 */
if (defined('DATE_LOCALES')) {
    $locales = explode(',', DATE_LOCALES);
    foreach ($locales as $locale) {
        $locale = trim($locale);
/**
 * Create the files needed by Serendipity [htaccess/serendipity_config_local.inc.php]
 *
 * @access public
 * @param   string      Path to the serendipity directory
 * @return  true
 */
function serendipity_installFiles($serendipity_core = '')
{
    global $serendipity;
    // This variable is transmitted from serendipity_admin_installer. If an empty variable is used,
    // this means that serendipity_installFiles() was called from the auto-updater facility.
    if (empty($serendipity_core)) {
        $serendipity_core = $serendipity['serendipityPath'];
    }
    $htaccess = @file_get_contents($serendipity_core . '.htaccess');
    // Let this function be callable outside installation and let it use existing settings.
    $import = array('rewrite', 'serendipityHTTPPath', 'indexFile');
    foreach ($import as $key) {
        if (empty($_POST[$key]) && isset($serendipity[$key])) {
            ${$key} = $serendipity[$key];
        } else {
            ${$key} = $_POST[$key];
        }
    }
    if (php_sapi_name() == 'cgi' || php_sapi_name() == 'cgi-fcgi') {
        $htaccess_cgi = '_cgi';
    } else {
        $htaccess_cgi = '';
    }
    /* If this file exists, a previous install failed painfully. We must consider the safer alternative now */
    if (file_exists($serendipity_core . '.installer_detection_failsafe')) {
        $htaccess_cgi = '_cgi';
        @unlink($serendipity_core . '.htaccess');
    }
    /* Detect comptability with php_value directives */
    if ($htaccess_cgi == '') {
        $response = '';
        $serendipity_root = dirname($_SERVER['PHP_SELF']) . '/';
        $serendipity_host = preg_replace('@^([^:]+):?.*$@', '\\1', $_SERVER['HTTP_HOST']);
        $old_htaccess = @file_get_contents($serendipity_core . '.htaccess');
        $fp = @fopen($serendipity_core . '.htaccess', 'w');
        if ($fp) {
            fwrite($fp, 'php_value register_globals off' . "\n" . 'php_value session.use_trans_sid 0');
            fclose($fp);
            $safeFP = @fopen($serendipity_core . '.installer_detection_failsafe', 'w');
            fclose($safeFP);
            $sock = fsockopen($serendipity_host, $_SERVER['SERVER_PORT'], $errorno, $errorstring, 10);
            if ($sock) {
                fputs($sock, "GET {$serendipityHTTPPath} HTTP/1.0\r\n");
                fputs($sock, "Host: {$serendipity_host}\r\n");
                fputs($sock, "User-Agent: Serendipity/{$serendipity['version']}\r\n");
                fputs($sock, "Connection: close\r\n\r\n");
                while (!feof($sock) && strlen($response) < 4096) {
                    $response .= fgets($sock, 400);
                }
                fclose($sock);
            }
            # If we get HTTP 500 Internal Server Error, we have to use the .cgi template
            if (preg_match('@^HTTP/\\d\\.\\d 500@', $response)) {
                $htaccess_cgi = '_cgi';
            }
            if (!empty($old_htaccess)) {
                $fp = @fopen($serendipity_core . '.htaccess', 'w');
                fwrite($fp, $old_htaccess);
                fclose($fp);
            } else {
                @unlink($serendipity_core . '.htaccess');
            }
            @unlink($serendipity_core . '.installer_detection_failsafe');
        }
    }
    if ($rewrite == 'rewrite') {
        $template = 'htaccess' . $htaccess_cgi . '_rewrite.tpl';
    } elseif ($rewrite == 'errordocs') {
        $template = 'htaccess' . $htaccess_cgi . '_errordocs.tpl';
    } else {
        $template = 'htaccess' . $htaccess_cgi . '_normal.tpl';
    }
    if (!($a = file(S9Y_INCLUDE_PATH . 'include/tpl/' . $template, 1))) {
        $errs[] = ERROR_TEMPLATE_FILE;
    }
    // When we write this file we cannot rely on the constants defined
    // earlier, as they do not yet contain the updated contents from the
    // new config. Thus we re-define those. We do still use constants
    // for backwards/code compatibility.
    $PAT = serendipity_permalinkPatterns(true);
    $content = str_replace(array('{PREFIX}', '{indexFile}', '{PAT_UNSUBSCRIBE}', '{PATH_UNSUBSCRIBE}', '{PAT_ARCHIVES}', '{PATH_ARCHIVES}', '{PAT_FEEDS}', '{PATH_FEEDS}', '{PAT_FEED}', '{PAT_ADMIN}', '{PATH_ADMIN}', '{PAT_ARCHIVE}', '{PATH_ARCHIVE}', '{PAT_PLUGIN}', '{PATH_PLUGIN}', '{PAT_DELETE}', '{PATH_DELETE}', '{PAT_APPROVE}', '{PATH_APPROVE}', '{PAT_SEARCH}', '{PATH_SEARCH}', '{PAT_COMMENTS}', '{PATH_COMMENTS}', '{PAT_CSS}', '{PAT_PERMALINK}', '{PAT_PERMALINK_AUTHORS}', '{PAT_PERMALINK_FEEDCATEGORIES}', '{PAT_PERMALINK_CATEGORIES}', '{PAT_PERMALINK_FEEDAUTHORS}'), array($serendipityHTTPPath, $indexFile, trim($PAT['UNSUBSCRIBE'], '@/i'), $serendipity['permalinkUnsubscribePath'], trim($PAT['ARCHIVES'], '@/i'), $serendipity['permalinkArchivesPath'], trim($PAT['FEEDS'], '@/i'), $serendipity['permalinkFeedsPath'], trim(PAT_FEED, '@/i'), trim($PAT['ADMIN'], '@/i'), $serendipity['permalinkAdminPath'], trim($PAT['ARCHIVE'], '@/i'), $serendipity['permalinkArchivePath'], trim($PAT['PLUGIN'], '@/i'), $serendipity['permalinkPluginPath'], trim($PAT['DELETE'], '@/i'), $serendipity['permalinkDeletePath'], trim($PAT['APPROVE'], '@/i'), $serendipity['permalinkApprovePath'], trim($PAT['SEARCH'], '@/i'), $serendipity['permalinkSearchPath'], trim($PAT['COMMENTS'], '@/i'), $serendipity['permalinkCommentsPath'], trim(PAT_CSS, '@/i'), trim($PAT['PERMALINK'], '@/i'), trim($PAT['PERMALINK_AUTHORS'], '@/i'), trim($PAT['PERMALINK_FEEDCATEGORIES'], '@/i'), trim($PAT['PERMALINK_CATEGORIES'], '@/i'), trim($PAT['PERMALINK_FEEDAUTHORS'], '@/i')), implode('', $a));
    $fp = @fopen($serendipity_core . '.htaccess', 'w');
    if (!$fp) {
        $errs[] = sprintf(FILE_WRITE_ERROR, $serendipity_core . '.htaccess') . ' ' . FILE_CREATE_YOURSELF;
        $errs[] = sprintf(COPY_CODE_BELOW, $serendipity_core . '.htaccess', 'serendipity', htmlspecialchars($content));
        return $errs;
    } else {
        // Check if an old htaccess file existed and try to preserve its contents. Otherwise completely wipe the file.
        if ($htaccess != '' && preg_match('@^(.*)#\\s+BEGIN\\s+s9y.*#\\s+END\\s+s9y(.*)$@isU', $htaccess, $match)) {
            // Code outside from s9y-code was found.
            fwrite($fp, $match[1] . $content . $match[2]);
        } else {
            fwrite($fp, $content);
        }
        fclose($fp);
        return true;
    }
}