/**
* Init all variables and load the settings from the database.
* Check the requests and prepare the templates to load.
*/
function PortaMx($doinit = false)
{
    global $context, $modSettings, $boardurl, $scripturl, $user_info, $maintenance, $language, $pmxCacheFunc, $sc, $cookiename, $txt;
    // we can exit on this...
    if (defined('PortaMx') || isset($_REQUEST['action']) && $_REQUEST['action'] == 'dlattach' && empty($doinit)) {
        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'dlattach' && !empty($user_info['possibly_robot'])) {
            redirectexit();
        } else {
            return;
        }
    }
    define('PortaMx', 1);
    // no sign up for robots please !!
    if (!empty($user_info['possibly_robot']) && !empty($_REQUEST['action']) && $_REQUEST['action'] == 'signup') {
        redirectexit();
    }
    if (empty($user_info['possibly_robot'])) {
        // portal enable/disable request ?
        if ((isset($_REQUEST['pmxportal']) || isset($_REQUEST['pmxsef'])) && allowedTo('admin_forum')) {
            $mode = 'pmx' . (isset($_REQUEST['pmxportal']) ? 'portal' : 'sef');
            updateSettings(array($mode . '_disabled' => $_REQUEST[$mode] == 'off' ? '1' : '0'));
            redirectexit();
        }
        // clear PortaMx cache request ?
        if (isset($_GET['action']) && isset($_GET['area']) && (in_array($_GET['action'], array('admin', 'portamx')) && $_GET['area'] == 'pmx_cache')) {
            if (isset($_GET[$_SESSION['session_var']]) && $_GET[$_SESSION['session_var']] == $sc) {
                $pmxCacheFunc['clean']();
                $_SESSION['pmx_cache_cleared'] = true;
            }
            if (isset($_SESSION['pmx_last_request'])) {
                redirectexit($_SESSION['pmx_last_request']);
            }
        } elseif (pmx_checkECL_Cookie() && strpos($_SERVER['REQUEST_URL'], 'viewsmfile') === false) {
            $_SESSION['pmx_last_request'] = $_SERVER['REQUEST_URL'];
        }
        $lang = $pmxCacheFunc['get']($user_info['ip'] . '-lang');
        if (!pmx_checkECL_Cookie()) {
            if ($lang === null) {
                // get browser language
                $browserlang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']) : '';
                if (preg_match_all('~en\\b|de\\b~i', $browserlang, $temp) > 0) {
                    $avail = array_keys(PortaMx_getLanguages());
                    if (in_array('de', $temp[0])) {
                        if (in_array('german', $avail)) {
                            $lang = 'german';
                        } elseif (in_array('german-utf8', $avail)) {
                            $lang = 'german-utf8';
                        }
                    } else {
                        $lang = $language;
                    }
                    $_POST['language'] = $lang;
                    $_POST['redir'] = pmx_http_build_query($_GET);
                }
            } else {
                $context['pmx']['currlang'] = $context['user']['language'] = $user_info['language'] = $language = $lang;
            }
            // need to releoad base language
            loadLanguage('index+Modifications');
        } else {
            if ($lang !== null) {
                $_POST['language'] = $lang;
                $_POST['redir'] = pmx_http_build_query($_GET);
            }
        }
        // check if a language change requested
        if (!empty($_POST['language'])) {
            $pmxCacheFunc['clean']();
            $context['pmx']['currlang'] = $context['user']['language'] = $user_info['language'] = $language = $_POST['language'];
            if (pmx_checkECL_Cookie()) {
                // Make it permanent for members.
                if (!empty($user_info['id'])) {
                    updateMemberData($user_info['id'], array('lngfile' => $user_info['language']));
                } else {
                    $_SESSION['language'] = $user_info['language'];
                }
            } else {
                $pmxCacheFunc['put']($user_info['ip'] . '-lang', $language, 360, false);
                $_POST['redir'] = pmx_http_build_query($_GET);
            }
            if (isset($_POST['redir'])) {
                redirectexit($_POST['redir']);
            }
        }
    }
    if (empty($modSettings['pmx_eclmodal']) && !pmx_checkECL_Cookie() && (!empty($_REQUEST['action']) && $_REQUEST['action'] != 'xml' || !empty($_REQUEST['page']) || !empty($_REQUEST['cat']) || !empty($_REQUEST['art']))) {
        if (empty($user_info['possibly_robot']) && !empty($_REQUEST['action']) && $_REQUEST['action'] == 'login') {
            setupMenuContext();
            pmx_ECL_Error($_REQUEST['action']);
        } else {
            redirectexit();
        }
    }
    // redirect on illegal request
    if (!empty($_REQUEST['pmxportal']) || !empty($_REQUEST['pmxsef']) || !empty($_REQUEST['pmxerror']) && !empty($_REQUEST['action'])) {
        redirectexit('pmxerror=unknown');
    }
    // check if a permanent theme change requested
    if (isset($_REQUEST['theme']) && isset($_REQUEST['pmxrd'])) {
        PortaMx_ChangeTheme($_REQUEST['theme'], $_REQUEST['pmxrd']);
    }
    // load all settings
    PortaMx_getSettings();
    // shoutbox POST request?
    if (!empty($_POST['pmx_shout']) && !empty($_POST['shoutbox_id'])) {
        PortaMx_GetShoutbox($_POST['shoutbox_id']);
        if (pmx_checkECL_Cookie()) {
            $_SESSION['pmx_shoutreload'] = true;
        }
        exit;
    }
    // exit on follow actions
    $rqaction = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
    if (isset($_REQUEST['xml']) || in_array($rqaction, array('jseditor', 'jsoption', '.xml', 'xmlhttp', 'verificationcode', 'printpage'))) {
        return;
    }
    // login with redirect .. correct SEF url
    if ($rqaction == 'login' && !empty($_SESSION['old_url']) && function_exists('pmxsef_query')) {
        $_SESSION['old_url'] = $scripturl . pmx_http_build_query(pmxsef_query(rawurldecode(ltrim(str_replace($boardurl, '', $_SESSION['old_url']), '/'))));
    }
    // check if a pmxscriptdebug/pmxspidertest requested
    $tmp = isset($_GET['pmxscriptdebug']) ? 'pmxscriptdebug' : (isset($_GET['pmxspidertest']) ? 'pmxspidertest' : '');
    if (!empty($tmp) && in_array($_GET[$tmp], array('on', 'off'))) {
        if (allowPmx('pmx_admin')) {
            if ($tmp == 'pmxscriptdebug') {
                pmx_setcookie($tmp, $_GET[$tmp] == 'on' ? '1' : '');
                unset($_GET[$tmp]);
                redirectexit(pmx_http_build_query($_GET));
            } elseif ($tmp == 'pmxspidertest' && $_GET[$tmp] == 'on' && !empty($modSettings['pmx_ecl'])) {
                $logCook = pmx_getcookie($cookiename);
                pmx_setcookie($tmp, $logCook);
                pmx_setcookie($cookiename, '');
                pmx_setcookie('pmx_eclauth', '');
                pmx_setcookie('PHPSESSID', '');
                unset($logCook);
                redirectexit();
            }
        } elseif ($tmp == 'pmxspidertest' && $_GET[$tmp] == 'off' && pmx_getcookie('pmxspidertest')) {
            $udata = pmx_getcookie($tmp);
            if (isset($udata) && is_array($dtmp = unserialize($udata)) && count($dtmp == 4)) {
                pmx_setECL_Cookie();
                pmx_setcookie($cookiename, $udata, $dtmp[2]);
                unset($dtmp);
                unset($udata);
            }
            pmx_setcookie('pmxspidertest', '');
            redirectexit();
        }
    }
    // load common javascript
    loadJavascriptFile(PortaMx_loadCompressed('PortaMx.js'), array('external' => true));
    addInlineJavascript('
	var pmx_restore_top = ' . intval(!empty($context['pmx']['settings']['restoretop'])) . ';');
    if ($doinit || !empty($modSettings['pmxportal_disabled'])) {
        loadLanguage($context['pmx_templatedir'] . 'PortaMx');
        loadCSSFile(PortaMx_loadCompressed('portamx.css'), array('external' => true));
        return;
    }
    // on Admin or Moderate load admin language, css and javascript
    if (($rqaction == 'admin' || $rqaction == 'portamx') && isset($_REQUEST['area']) && in_array($_REQUEST['area'], explode(',', $context['pmx']['areas']))) {
        loadJavascriptFile(PortaMx_loadCompressed('PortaMxAdmin.js'), array('external' => true));
        loadCSSFile(PortaMx_loadCompressed('portamx_admin.css'), array('external' => true));
        loadLanguage($context['pmx_templatedir'] . 'Admin');
        addInlineJavascript("\n\t" . 'BlockActive=\'' . $txt['pmx_status_activ'] . ' - ' . $txt['pmx_status_change'] . '\';' . "\n\t" . 'BlockInactive=\'' . $txt['pmx_status_inactiv'] . ' - ' . $txt['pmx_status_change'] . '\';');
    }
    // Error request?
    if (!empty($_REQUEST['pmxerror'])) {
        return PmxError();
    }
    // check Error request, Forum request
    $context['pmx']['forumReq'] = !empty($_REQUEST['action']) || !empty($context['current_board']) || !empty($context['current_topic']);
    if (empty($context['pmx']['forumReq']) && !empty($context['pmx']['settings']['other_actions'])) {
        $reqtyp = Pmx_StrToArray($context['pmx']['settings']['other_actions']);
        foreach ($reqtyp as $rtyp) {
            @(list($rtyp, $rval) = Pmx_StrToArray($rtyp, '='));
            $context['pmx']['forumReq'] = $context['pmx']['forumReq'] || isset($_REQUEST[$rtyp]) && (is_null($rval) || $_REQUEST[$rtyp] == $rval);
        }
    }
    // check Page, category, article request
    $pmxRequestTypes = array('spage', 'art', 'cat', 'child');
    $context['pmx']['pageReq'] = array();
    foreach ($pmxRequestTypes as $type) {
        if (empty($_REQUEST['action']) && !empty($_REQUEST[$type])) {
            $context['pmx']['pageReq'][$type] = PortaMx_makeSafe($_REQUEST[$type]);
        }
    }
    // no request on forum or pages and no frontpage .. go to forum
    if (empty($context['pmx']['forumReq']) && empty($context['pmx']['pageReq']) && $context['pmx']['settings']['frontpage'] == 'none') {
        $_REQUEST['action'] = $_GET['action'] = 'community';
        $context['pmx']['forumReq'] = true;
    }
    // Disable HighSlide on action?
    if (isset($_REQUEST['action']) && isset($context['pmx']['settings']['noHS_onaction'])) {
        $noHighSlide = isset($context['pmx']['settings']['noHS_onaction']) ? Pmx_StrToArray($context['pmx']['settings']['noHS_onaction']) : array();
        if (in_array($_REQUEST['action'], $noHighSlide)) {
            $context['pmx']['settings']['disableHS'] = 1;
        }
    }
    // Admin panel/block hidding ?
    $hideRequest = array_intersect($context['pmx']['extracmd'], array_keys($_REQUEST));
    if (!empty($hideRequest) && allowPmx('pmx_admin')) {
        @(list($hideRequest) = array_values($hideRequest));
        $mode = substr($hideRequest, 5);
        $hidetyp = substr($hideRequest, 0, 5);
        $offparts = empty($modSettings['pmx_' . $hidetyp . 'off']) ? array() : Pmx_StrToArray($modSettings['pmx_' . $hidetyp . 'off']);
        if ($mode == 'off') {
            if ($hidetyp == 'panel') {
                $offparts = array_intersect($_REQUEST[$hideRequest] == 'all' ? $context['pmx']['block_sides'] : array_merge($offparts, Pmx_StrToArray($_REQUEST[$hideRequest])), $context['pmx']['block_sides']);
            } else {
                $offparts = array_merge($offparts, Pmx_StrToIntArray($_REQUEST[$hideRequest]));
            }
        } else {
            if ($hidetyp == 'panel') {
                $offparts = array_intersect($_REQUEST[$hideRequest] == 'all' ? array() : array_diff($offparts, Pmx_StrToArray($_REQUEST[$hideRequest])), $context['pmx']['block_sides']);
            } else {
                $offparts = $_REQUEST[$hideRequest] == 'all' ? array() : array_diff($offparts, Pmx_StrToIntArray($_REQUEST[$hideRequest]));
            }
        }
        updateSettings(array('pmx_' . $hidetyp . 'off' => implode(',', $offparts)));
        unset($_GET[$hideRequest]);
        redirectexit(pmx_http_build_query($_GET));
    }
    // check all the actions and more...
    if (empty($context['pmx']['forumReq'])) {
        // if a redirect request, exit
        $requrl = strpos($_SERVER['REQUEST_URL'], substr($scripturl, 0, strrpos($scripturl, '/'))) === false ? $_SERVER['REQUEST_URL'] : $scripturl;
        if (substr($requrl, 0, strrpos($requrl, '/')) != substr($scripturl, 0, strrpos($scripturl, '/'))) {
            return;
        }
        // we use the frontpage ?
        $useFront = $context['pmx']['settings']['frontpage'] == 'none' && empty($context['pmx']['pageReq']) ? '' : 'frontpage';
        // get all block on active panels they can view
        $context['pmx']['viewblocks'] = getPanelsToShow($useFront);
        // frontpage and/or Page blocks exist ?
        if (!empty($maintenance) && $context['pmx']['settings']['frontpage'] != 'none' || empty($useFront) || !empty($context['pmx']['show_pagespanel']) || !empty($context['pmx']['show_frontpanel']) && $context['pmx']['settings']['frontpage'] != 'none') {
            // setup headers
            PortaMx_headers('frontpage');
            $context['robot_no_index'] = empty($context['pmx']['settings']['indexfront']);
            if ($context['pmx']['settings']['frontpage'] == 'fullsize') {
                loadTemplate($context['pmx_templatedir'] . 'Frontpage');
                $context['template_layers'] = array('fronthtml', 'portamx');
                call_integration_hook('integrate_load_theme');
            } else {
                loadTemplate($context['pmx_templatedir'] . 'Mainindex');
                $context['template_layers'][] = 'portamx';
            }
            if (!empty($context['pmx']['pageReq']) || empty($context['pmx']['forumReq']) && $context['pmx']['settings']['frontpage'] != 'none') {
                loadTemplate($context['pmx_templatedir'] . 'PortaMx');
            }
        } else {
            // page req error?
            if (!empty($context['pmx']['pageReq']) && empty($context['pmx']['show_pagespanel'])) {
                redirectexit('pmxerror=page');
            }
            // else go to forum
            $_REQUEST['action'] = $_GET['action'] = !empty($maintenance) && empty($user_info['is_admin']) ? '' : 'community';
            $context['pmx']['forumReq'] = true;
            $context['pmx']['viewblocks'] = null;
        }
    }
    if (!empty($context['pmx']['forumReq'])) {
        // get the action
        $action = isset($_REQUEST['action']) ? $_REQUEST['action'] == 'collapse' ? 'community' : $_REQUEST['action'] : (isset($_REQUEST['board']) ? 'boards' : (isset($_REQUEST['topic']) ? 'topics' : ''));
        // get all block on active panels they can view
        $context['pmx']['viewblocks'] = getPanelsToShow($action);
        // setup headers
        PortaMx_headers($action);
        // load the "Main" template on pages, cats or arts
        if (!empty($context['pmx']['pageReq'])) {
            loadTemplate($context['pmx_templatedir'] . 'PortaMx');
        }
        loadTemplate($context['pmx_templatedir'] . 'Mainindex');
        $context['template_layers'][] = 'portamx';
    }
    // Load the Frame template
    loadTemplate($context['pmx_templatedir'] . 'Frames');
    // supress these links if ECL not accepted
    if (!empty($rqaction) && !pmx_checkECL_Cookie() && isset($modSettings['pmx_eclmodalaction']) && in_array($rqaction, Pmx_StrToArray($modSettings['pmx_eclmodalaction']))) {
        pmx_ECL_Error('request');
    }
    // Create the linktree
    return pmx_MakeLinktree();
}
/**
* Read POST data with a specific key
* used for Blocks Pageindex
**/
function pmx_GetPostKey($postKey, &$result)
{
    if (!empty($_POST[$postKey])) {
        if (function_exists('pmxsef_query')) {
            $_POST[$postKey] = pmxsef_query(str_replace('//', '/', $_POST[$postKey]));
        } else {
            $tmp = $data = array();
            $_POST[$postKey] = explode(';', $_POST[$postKey]);
            while (list($key, $val) = each($_POST[$postKey])) {
                $tmp = explode('=', $val);
                $data[$tmp[0]] = isset($tmp[1]) ? $tmp[1] : '';
            }
            $_POST[$postKey] = $data;
        }
        $result = array_merge($result, $_POST[$postKey]);
        if (isset($result['pgkey'])) {
            unset($result['pgkey']);
        }
        return $result;
    }
}
function pmxsef_convertSEF()
{
    global $boardurl, $modSettings, $scripturl, $PortaMxSEF, $pmxCacheFunc;
    define('PortaMxSEF', 1);
    if (!empty($modSettings['pmxportal_disabled']) || !empty($modSettings['pmxsef_disabled'])) {
        return;
    }
    if (($PortaMxSEF = $pmxCacheFunc['get']('sef_settings', false)) === null) {
        $PortaMxSEF = array('actions' => array_unique(array_merge(explode(',', $modSettings['pmxsef_actions']), array('theme'))), 'aliasactions' => unserialize($modSettings['pmxsef_aliasactions']), 'ignoreactions' => array_unique(array_merge(array('admin', 'portamx', 'openidreturn', 'quickmod', 'verificationcode'), explode(',', $modSettings['pmxsef_ignoreactions']))), 'ignorerequests' => unserialize($modSettings['pmxsef_ignorerequests']), 'stripchars' => array_diff(explode(',', $modSettings['pmxsef_stripchars']), array(trim($modSettings['pmxsef_spacechar']))), 'singletoken' => array_unique(explode(',', $modSettings['pmxsef_singletoken'])), 'spacechar' => trim($modSettings['pmxsef_spacechar']), 'lowercase' => $modSettings['pmxsef_lowercase'], 'codepages' => $modSettings['pmxsef_codepages'], 'autosave' => $modSettings['pmxsef_autosave'], 'ssefspace' => trim($modSettings['pmxsef_ssefspace']), 'pmxextra' => array('all' => array('paneloff', 'panelon', 'blockoff', 'blockon', 'show'), 'save' => array('rply', 'new', 'cont'), 'view' => array('sa', 'cfr')));
        $PortaMxSEF['allactions'] = array_filter(array_unique(array_merge($PortaMxSEF['actions'], $PortaMxSEF['ignoreactions'], array_keys($PortaMxSEF['aliasactions']))));
        $pmxCacheFunc['put']('sef_settings', $PortaMxSEF, 86400);
    }
    // Make sure we know the URL of the current request.
    parse_str(preg_replace('~&(\\w+)(?=&|$)~', '&$1=', strtr($_SERVER['QUERY_STRING'], array(';?' => '&', '/;' => '/', ';' => '&', '%00' => '', "" => ''))), $_GET);
    $scripturl = $boardurl . '/index.php';
    if (empty($_SERVER['REQUEST_URI'])) {
        $_SERVER['REQUEST_URL'] = $scripturl . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '');
    } elseif (preg_match('~^([^/]+//[^/]+)~', $scripturl, $match) == 1) {
        $_SERVER['REQUEST_URL'] = $match[1] . $_SERVER['REQUEST_URI'];
    } else {
        $_SERVER['REQUEST_URL'] = $_SERVER['REQUEST_URI'];
    }
    // security .. illegal querys
    $_SERVER['REQUEST_URL'] = str_replace('../', '', $_SERVER['REQUEST_URL']);
    $urlParts = parse_url($boardurl);
    if (preg_match_all('~(http|https|ftp|sftp)(\\:\\/\\/)|' . preg_quote($urlParts['host']) . '~i', $_SERVER['QUERY_STRING'], $match) > 0) {
        pmxsef_redir_perm($scripturl);
    }
    if (SMF == 'SSI') {
        return;
    }
    // replace a simple domain.tld/? to /index.php?
    if (strpos($_SERVER['REQUEST_URL'], 'index.php') === false && strpos($_SERVER['REQUEST_URL'], $boardurl . '/?') !== false) {
        $_SERVER['REQUEST_URL'] = str_replace($boardurl . '/?', $scripturl . '?', $_SERVER['REQUEST_URL']);
    }
    // fix advanced search params
    if (strpos($_SERVER['REQUEST_URL'], '/;search=') !== false) {
        pmxsef_redir_perm(str_replace(array('/;', '='), '/', $_SERVER['REQUEST_URL']));
    }
    if (strpos($_SERVER['REQUEST_URL'], '/?language=') !== false) {
        pmxsef_redir_perm(str_replace(array('/?', '='), '/', $_SERVER['REQUEST_URL']));
    }
    // exit on defined requests, redirect other
    if (strpos($_SERVER['REQUEST_URL'], $scripturl) !== false) {
        if (isset($_GET['xml']) || !empty($_GET['action']) && ($_GET['action'] == '.xml' || in_array($_GET['action'], $PortaMxSEF['ignoreactions']))) {
            // clear the cache if a board modified
            if (strpos($_SERVER['REQUEST_URL'], 'sa=board2') !== false && isset($_POST['boardid'])) {
                $pmxCacheFunc['clear']('pmxsef_boardlist', false);
            }
            return;
        } elseif (!empty($_GET) && ($tmp = array_intersect(array_keys($_GET), array_keys($PortaMxSEF['ignorerequests']))) && count($tmp) == 1 && ($tmp = current($tmp)) && $_GET[$tmp] == $PortaMxSEF['ignorerequests'][$tmp]) {
            return;
        }
        pmxsef_redir_perm($_SERVER['REQUEST_URL']);
    }
    // Parse the url
    if (!empty($_GET['q'])) {
        $_GET = pmxsef_query(rawurldecode(ltrim(str_replace($boardurl, '', $_SERVER['REQUEST_URL']), '/')));
        $_SERVER['QUERY_STRING'] = pmxsef_build_query($_GET['q'], '', ';');
        if (isset($_GET['q'])) {
            unset($_GET['q']);
        }
        // check if the topic subject changed
        if (isset($_GET['action']) && $_GET['action'] == 'post2' && isset($_GET['msg'])) {
            pmxsef_CheckTopic($_GET['msg']);
        }
    }
}