/**
* check if it is a legal POST session.
* Skip on admin security logon
*/
function PortaMx_checkPOST()
{
    global $context;
    // cleanup POST array
    if (empty($_POST)) {
        return false;
    }
    $_POST = PortaMx_makeSafe($_POST);
    // id admin security logon ?
    if (isset($_POST['admin_pass'])) {
        // yes .. remove the posts
        unset($_POST['admin_pass']);
        if (isset($_POST['admin_hash_pass'])) {
            unset($_POST['admin_hash_pass']);
        }
        if (isset($_POST[$context['session_var']])) {
            unset($_POST[$context['session_var']]);
        }
    }
    return !empty($_POST);
}
/**
* Receive all the posts from the articles manager, check it, then save it.
* Finally the articles are prepared and the template loaded.
*/
function PortaMx_AdminArticles()
{
    global $smcFunc, $pmxCacheFunc, $context, $sourcedir, $scripturl, $modSettings, $user_info, $txt;
    $admMode = isset($_GET['action']) ? $_GET['action'] : '';
    // fix the linktree
    if ($admMode == 'admin') {
        foreach ($context['linktree'] as $key => $data) {
            if (strpos($data['url'], 'pmx_articles') !== false) {
                $context['linktree'] = array_merge(array_slice($context['linktree'], 0, $key), array(array('url' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'name' => $txt['pmx_extension'])), array_slice($context['linktree'], $key, count($context['linktree']) - $key));
                break;
            }
        }
    }
    if (($admMode == 'admin' || $admMode == 'portamx') && isset($_GET['area']) && $_GET['area'] == 'pmx_articles') {
        if (allowPmx('pmx_admin, pmx_articles, pmx_create')) {
            require_once $context['pmx_sourcedir'] . 'AdminSubs.php';
            $context['pmx']['subaction'] = !empty($_POST['sa']) ? $_POST['sa'] : 'overview';
            // From template ?
            if (PortaMx_checkPOST()) {
                // Make sure we have a valid session...
                checkSession('post');
                // get current pageindex
                if (isset($_POST['articlestart'])) {
                    $context['pmx']['articlestart'] = $_POST['articlestart'];
                }
                // actions from overview?
                if ($context['pmx']['subaction'] == 'overview' && empty($_POST['cancel_overview'])) {
                    // from xml on overview?
                    if (isset($_POST['xml'])) {
                        $xmlResult = '';
                    }
                    // filter set ?
                    if (isset($_POST['filter'])) {
                        $_SESSION['PortaMx']['filter'] = $_POST['filter'];
                    }
                    // Row pos updates from overview?
                    if (!empty($_POST['upd_rowpos'])) {
                        list($fromID, $place, $idto) = Pmx_StrToArray($_POST['upd_rowpos']);
                        $request = $smcFunc['db_query']('', '
							SELECT id
							FROM {db_prefix}portamx_articles
							WHERE id ' . ($place == 'before' ? '<' : '>') . ' {int:id}
							LIMIT 1', array('id' => $idto));
                        list($toID) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        $toID = is_null($toID) ? $place == 'before' ? -1 : 0 : $toID;
                        $request = $smcFunc['db_query']('', '
							SELECT MAX(id) +1
							FROM {db_prefix}portamx_articles', array());
                        list($maxID) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        // create the query...
                        if ($toID == -1) {
                            // move from to first
                            $query = array('SET id = 0 WHERE id = ' . $fromID, 'SET id = id + 1 WHERE id >= 1 AND id <= ' . $fromID, 'SET id = 1 WHERE id = 0');
                        } elseif ($toID == 0) {
                            // move from to end
                            $query = array('SET id = ' . $maxID . ' WHERE id = ' . $fromID, 'SET id = id - 1 WHERE id >= ' . $fromID);
                        } elseif ($toID > $fromID) {
                            // to > from - move to after from
                            $query = array('SET id = id + 1 WHERE id >= ' . $toID, 'SET id = ' . $toID . ' WHERE id = ' . $fromID, 'SET id = id - 1 WHERE id >= ' . $fromID);
                        } else {
                            // to < from - move to before from
                            $query = array('SET id = 0 WHERE id = ' . $fromID, 'SET id = id + 1 WHERE id >= ' . $toID . ' AND id <= ' . $fromID, 'SET id = ' . $toID . ' WHERE id = 0');
                        }
                        // execute
                        foreach ($query as $qdata) {
                            $smcFunc['db_query']('', 'UPDATE {db_prefix}portamx_articles ' . $qdata, array());
                        }
                    }
                    // updates from overview popups ?
                    if (!empty($_POST['upd_overview'])) {
                        $updates = array();
                        foreach ($_POST['upd_overview'] as $updkey => $updvalues) {
                            foreach ($updvalues as $id => $values) {
                                if ($updkey == 'title') {
                                    foreach ($values as $key => $val) {
                                        if ($key == 'lang') {
                                            foreach ($val as $langname => $langvalue) {
                                                $updates[$id]['config'][$updkey][$langname] = $langvalue;
                                            }
                                        } else {
                                            $updates[$id]['config'][$updkey . '_' . $key] = $val;
                                        }
                                    }
                                } else {
                                    $updates[$id][$updkey] = $values;
                                }
                            }
                        }
                        // save all updates
                        $idList = array();
                        $catList = array();
                        foreach ($updates as $id => $values) {
                            $idList[] = $id;
                            foreach ($values as $rowname => $data) {
                                $request = $smcFunc['db_query']('', '
									SELECT config, catid, acsgrp
									FROM {db_prefix}portamx_articles
									WHERE id = {int:id}', array('id' => $id));
                                $row = $smcFunc['db_fetch_assoc']($request);
                                $smcFunc['db_free_result']($request);
                                $catList[] = $row['catid'];
                                // update config
                                if ($rowname == 'config') {
                                    $cfg = unserialize($row['config']);
                                    foreach ($data as $ckey => $cval) {
                                        if ($ckey == 'title') {
                                            foreach ($cval as $lang => $val) {
                                                $cfg[$ckey][$lang] = $val;
                                            }
                                        } else {
                                            $cfg[$ckey] = $cval;
                                        }
                                    }
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_articles
										SET config = {string:config}
										WHERE id = {int:id}', array('id' => $id, 'config' => serialize($cfg)));
                                } elseif ($rowname == 'category') {
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_articles
										SET catid = {int:val}
										WHERE id = {int:id}', array('id' => $id, 'val' => $data));
                                } else {
                                    $mode = substr($rowname, 0, 3);
                                    // update (replace)
                                    if ($mode == 'upd') {
                                        $newacs = explode(',', $data);
                                    } elseif ($mode == 'add') {
                                        $newacs = array_unique(array_merge(explode(',', $row['acsgrp']), explode(',', $data)));
                                    } else {
                                        $newacs = array_unique(array_diff(explode(',', $row['acsgrp']), explode(',', $data)));
                                    }
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_articles
										SET acsgrp = {string:val}
										WHERE id = {int:id}', array('id' => $id, 'val' => implode(',', $newacs)));
                                    // send by xml?
                                    if (isset($_POST['xml'])) {
                                        $request = $smcFunc['db_query']('', '
											SELECT active
											FROM {db_prefix}portamx_articles
											WHERE id = {int:id}', array('id' => $id));
                                        list($active) = $smcFunc['db_fetch_row']($request);
                                        $smcFunc['db_free_result']($request);
                                        $acsnew = implode(',', $newacs);
                                        $xmlResult .= (!empty($xmlResult) ? '&' : '') . $id . '|' . $acsnew . '|' . count($newacs) . '|' . intval(allowPmxGroup($newacs)) . '|' . (!empty($active) ? '1' : '0');
                                    }
                                }
                            }
                        }
                        // clear cached blocks && Cat/Art Session Keys
                        $pmxCacheFunc['clean']();
                        if (isset($_SESSION['PortaMx'])) {
                            foreach ($_SESSION['PortaMx'] as $key => $val) {
                                if (strpos($key, 'pmxpost_') !== false) {
                                    unset($_SESSION['PortaMx'][$key]);
                                }
                            }
                        }
                        if (isset($_POST['xml'])) {
                            // return update result
                            ob_start();
                            if (!empty($_POST['result'])) {
                                echo $_POST['result'];
                            } else {
                                echo $xmlResult;
                            }
                            ob_end_flush();
                            exit;
                        }
                    }
                    // add a new article
                    if (!empty($_POST['add_new_article'])) {
                        $article = PortaMx_getDefaultArticle($_POST['add_new_article']);
                        $context['pmx']['subaction'] = 'editnew';
                    } elseif (!empty($_POST['edit_article']) || !empty($_POST['clone_article'])) {
                        $id = !empty($_POST['clone_article']) ? $_POST['clone_article'] : $_POST['edit_article'];
                        // load the article for edit/clone
                        $request = $smcFunc['db_query']('', '
							SELECT *
							FROM {db_prefix}portamx_articles
							WHERE id = {int:id}', array('id' => $id));
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $article = array('id' => $row['id'], 'name' => $row['name'], 'catid' => $row['catid'], 'acsgrp' => $row['acsgrp'], 'ctype' => $row['ctype'], 'config' => $row['config'], 'content' => $row['content'], 'active' => $row['active'], 'owner' => $row['owner'], 'created' => $row['created'], 'approved' => $row['approved'], 'approvedby' => $row['approvedby'], 'updated' => $row['updated'], 'updatedby' => $row['updatedby']);
                        $smcFunc['db_free_result']($request);
                        if (!empty($_POST['clone_article'])) {
                            $article['id'] = 0;
                            $article['active'] = 0;
                            $article['approved'] = 0;
                            $article['owner'] = $user_info['id'];
                            $article['created'] = 0;
                            $article['updated'] = 0;
                            $article['updatedby'] = 0;
                            $context['pmx']['subaction'] = 'editnew';
                        } else {
                            $context['pmx']['subaction'] = 'edit';
                        }
                    } elseif (!empty($_POST['delete_article'])) {
                        $delid = $_POST['delete_article'];
                        // get the current page
                        $context['pmx']['articlestart'] = getCurrentPage($delid, $context['pmx']['settings']['manager']['artpage'], true);
                        $smcFunc['db_query']('', '
							DELETE FROM {db_prefix}portamx_articles
							WHERE id = {int:id}', array('id' => $delid));
                        // clear cached blocks
                        $pmxCacheFunc['clean']();
                    } elseif (!empty($_POST['chg_approved'])) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_articles
							SET approved = CASE WHEN approved = 0 THEN {int:apptime} ELSE 0 END, approvedby = {int:appmember}
							WHERE id = {int:id}', array('id' => $_POST['chg_approved'], 'apptime' => forum_time(), 'appmember' => $user_info['id']));
                        // clear cached blocks
                        $pmxCacheFunc['clean']();
                    } elseif (!empty($_POST['chg_active'])) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_articles
							SET active = CASE WHEN active = 0 THEN {int:apptime} ELSE 0 END
							WHERE id = {int:id}', array('id' => $_POST['chg_active'], 'apptime' => forum_time()));
                        // clear cached blocks
                        $pmxCacheFunc['clean']();
                    }
                    if (isset($_POST['xml']) && (!empty($_POST['chg_active']) || !empty($_POST['chg_approved']))) {
                        $id = !empty($_POST['chg_active']) ? $_POST['chg_active'] : $_POST['chg_approved'];
                        $request = $smcFunc['db_query']('', '
							SELECT active, approved
							FROM {db_prefix}portamx_articles
							WHERE id = {int:id}', array('id' => $id));
                        list($active, $approved) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        // return update result
                        ob_start();
                        echo $id . ',' . (!empty($_POST['chg_active']) ? intval(!empty($active)) : intval(!empty($approved)));
                        ob_end_flush();
                        exit;
                    }
                } elseif (!empty($_POST['cancel_edit']) || !empty($_POST['cancel_overview'])) {
                    // called fron blocks move/clone ?
                    if (!empty($_POST['fromblock'])) {
                        // on cancel after saved remove the article
                        if ($_POST['sa'] == 'edit' && !empty($_POST['id'])) {
                            $smcFunc['db_query']('', '
								DELETE FROM {db_prefix}portamx_articles
								WHERE id = {int:id}', array('id' => $_POST['id']));
                            $pmxCacheFunc['clean']();
                        }
                        // redirect back to the blocks manager
                        @(list($mode, $side, $bid) = explode('.', $_POST['fromblock']));
                        redirectexit('action=' . $admMode . ';area=pmx_blocks;sa=' . $side . ';' . $context['session_var'] . '=' . $context['session_id']);
                    }
                    // Otherwise let's load the overview
                    $context['pmx']['subaction'] = 'overview';
                } elseif ($context['pmx']['subaction'] == 'editnew' || $context['pmx']['subaction'] == 'edit') {
                    $context['pmx']['fromblock'] = $_POST['fromblock'];
                    // check defined numeric vars (check_num_vars holds the posted array to check like [varname][varname] ...)
                    if (isset($_POST['check_num_vars'])) {
                        foreach ($_POST['check_num_vars'] as $val) {
                            $data = explode(',', $val);
                            $post = '$_POST' . str_replace(array('[', ']'), array('[\'', '\']'), $data[0]);
                            if (eval("return isset({$post});") && eval("return !is_numeric({$post});")) {
                                eval("{$post} = {$data['1']};");
                            }
                        }
                    }
                    if (isset($_POST['content']) && PortaMx_makeSafeContent($_POST['content']) != '') {
                        // convert html/script to bbc
                        if ($_POST['ctype'] == 'bbc_script' && in_array($_POST['contenttype'], array('html', 'script'))) {
                            $_POST['content'] = PortaMx_SmileyToBBC($_POST['content']);
                            if (preg_match_all('/<img.*(style[^\\"]*\\"([^\\"]*\\"))[^>]*>/U', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $repl = ' ' . str_replace(array('"', ': ', ':', 'px;'), array('', '="', '="', '" '), $match[2][$key]);
                                    $_POST['content'] = str_replace($val, str_replace($match[1][$key], $repl, $val), $_POST['content']);
                                }
                            }
                            require_once $sourcedir . '/Subs-Editor.php';
                            $modSettings['smiley_enable'] = true;
                            $user_info['smiley_set'] = 'PortaMx';
                            $_POST['content'] = html_to_bbc($_POST['content']);
                        } elseif ($_POST['contenttype'] == 'bbc_script' && in_array($_POST['ctype'], array('html', 'script'))) {
                            $_POST['content'] = PortaMx_BBCsmileys(parse_bbc(PortaMx_makeSafeContent($_POST['content'], $_POST['contenttype']), false));
                            $_POST['content'] = str_replace(array('<hr>', '<br>'), array('<hr />', '<br />'), $_POST['content']);
                            $_POST['content'] = preg_replace_callback('/<\\/[^>]*>|<[^\\/]*\\/>|<ul[^>]*>|<ol[^>]*>/', create_function('$matches', 'return $matches[0] ."\\n";'), $_POST['content']);
                            if (preg_match_all('/<img[^w]*(width=\\"([0-9]+)\\")(\\sheight=\\"([\\s0-9]+)\\")[^>]*>/', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $_POST['content'] = str_replace($match[1][$key], '', $_POST['content']);
                                    $_POST['content'] = str_replace($match[3][$key], 'style="width: ' . $match[2][$key] . 'px;height: ' . $match[4][$key] . 'px;"', $_POST['content']);
                                }
                                $_POST['content'] = preg_replace('/px;"[^c]*class=/', 'px;" class=', $_POST['content']);
                            }
                        } elseif ($_POST['ctype'] == 'php' && $_POST['contenttype'] == 'php') {
                            pmxPHP_convert();
                        } elseif ($_POST['ctype'] == 'html' && $_POST['contenttype'] == 'html') {
                            $_POST['content'] = str_replace('/ckeditor/../Smileys/', '/Smileys/', $_POST['content']);
                            if (preg_match_all('~<img.*(class[^r]*resized[^\\"]*\\")[^>]*>~', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $endChr = substr($val, -2) !== '/>' ? array('>', '/>') : array(' />', '/>');
                                    $repl = str_replace($match[1][$key], '', $val);
                                    $_POST['content'] = str_replace($val, str_replace($endChr[0], ' class="bbc_img resized"' . $endChr[1], $repl), $_POST['content']);
                                }
                            } elseif (preg_match_all('~<img[^>]*>~', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $endChr = substr($val, -2) !== ' />' ? array('>', '/>') : array(' />', '/>');
                                    if (strpos($val, '/Smileys/') === false) {
                                        $_POST['content'] = str_replace($val, str_replace($endChr[0], ' class="bbc_img resized"' . $endChr[1], $val), $_POST['content']);
                                    }
                                }
                            }
                        }
                    }
                    // get all data
                    $article = array('id' => $_POST['id'], 'name' => $_POST['name'], 'catid' => $_POST['catid'], 'acsgrp' => !empty($_POST['acsgrp']) ? implode(',', $_POST['acsgrp']) : '', 'ctype' => $_POST['ctype'], 'config' => serialize($_POST['config']), 'content' => $_POST['content'], 'active' => $_POST['active'], 'owner' => $_POST['owner'], 'created' => $_POST['created'], 'approved' => $_POST['approved'], 'approvedby' => $_POST['approvedby'], 'updated' => $_POST['updated'], 'updatedby' => $_POST['updatedby']);
                    // save article if have content..
                    if (!empty($article['content']) && empty($_POST['edit_change']) && (!empty($_POST['save_edit']) || !empty($article['content']) && !empty($_POST['save_edit_continue']))) {
                        // if new article get the last id
                        if ($context['pmx']['subaction'] == 'editnew') {
                            $request = $smcFunc['db_query']('', '
								SELECT MAX(id)
								FROM {db_prefix}portamx_articles', array());
                            list($dbid) = $smcFunc['db_fetch_row']($request);
                            $smcFunc['db_free_result']($request);
                            $article['id'] = strval(1 + ($dbid === null ? $article['id'] : $dbid));
                            $article['created'] = forum_time();
                            // auto approve for admins
                            if (allowPmx('pmx_admin')) {
                                $article['approved'] = forum_time();
                                $article['approvedby'] = $user_info['id'];
                            }
                            // insert new article
                            $smcFunc['db_insert']('ignore', '
								{db_prefix}portamx_articles', array('id' => 'int', 'name' => 'string', 'catid' => 'int', 'acsgrp' => 'string', 'ctype' => 'string', 'config' => 'string', 'content' => 'string', 'active' => 'int', 'owner' => 'int', 'created' => 'int', 'approved' => 'int', 'approvedby' => 'int', 'updated' => 'int', 'updatedby' => 'int'), $article, array());
                            // clear cache
                            $pmxCacheFunc['clean']();
                        } else {
                            $article['updated'] = forum_time();
                            $article['updatedby'] = $user_info['id'];
                            // update the article
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}portamx_articles
								SET name = {string:name}, catid = {int:catid}, acsgrp = {string:acsgrp}, ctype = {string:ctype}, config = {string:config},
										content = {string:content}, active = {int:active}, owner = {int:owner}, created = {int:created}, approved = {int:approved},
										approvedby = {int:approvedby}, updated = {int:updated}, updatedby = {int:updatedby}
								WHERE id = {int:id}', array('id' => $article['id'], 'name' => $article['name'], 'catid' => $article['catid'], 'acsgrp' => $article['acsgrp'], 'ctype' => $article['ctype'], 'config' => $article['config'], 'content' => $article['content'], 'active' => $article['active'], 'owner' => $article['owner'], 'created' => $article['created'], 'approved' => $article['approved'], 'approvedby' => $article['approvedby'], 'updated' => $article['updated'], 'updatedby' => $article['updatedby']));
                        }
                        // clear cache
                        $pmxCacheFunc['clean']();
                        $context['pmx']['subaction'] = 'edit';
                    }
                    // continue edit ?
                    if (!empty($_POST['save_edit']) || !empty($_POST['save_edit_continue'])) {
                        if (empty($_POST['save_edit_continue'])) {
                            // edit done, is it a move/clone from blocks?
                            if (!empty($context['pmx']['fromblock'])) {
                                @(list($mode, $side, $bid) = explode('.', $context['pmx']['fromblock']));
                                // was block moved?
                                if ($mode == 'move') {
                                    $request = $smcFunc['db_query']('', '
										SELECT pos, blocktype
										FROM {db_prefix}portamx_blocks
										WHERE id = {int:bid}', array('bid' => $bid));
                                    $block = $smcFunc['db_fetch_assoc']($request);
                                    $smcFunc['db_free_result']($request);
                                    // update all pos >= moved id
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_blocks
										SET pos = pos - 1
										WHERE side = {string:side} AND pos >= {int:pos}', array('side' => $side, 'pos' => $block['pos']));
                                    // delete the block
                                    $smcFunc['db_query']('', '
										DELETE FROM {db_prefix}portamx_blocks
										WHERE id = {int:id}', array('id' => $bid));
                                    // clear cache and SEF pages list
                                    $pmxCacheFunc['clean']();
                                }
                            }
                            // go to article overview
                            $context['pmx']['subaction'] = 'overview';
                            $context['pmx']['articlestart'] = getCurrentPage($article['id'], $context['pmx']['settings']['manager']['artpage']);
                        }
                    }
                    // clear cached blocks
                    $pmxCacheFunc['clean']();
                }
                if ($context['pmx']['subaction'] == 'overview') {
                    if (!isset($context['pmx']['articlestart'])) {
                        $context['pmx']['articlestart'] = 0;
                    }
                    redirectexit('action=' . $admMode . ';area=pmx_articles;' . $context['session_var'] . '=' . $context['session_id'] . ';pg=' . $context['pmx']['articlestart']);
                }
            }
            // load the template, initialize the page title
            loadTemplate($context['pmx_templatedir'] . 'AdminArticles');
            $context['page_title'] = $txt['pmx_articles'];
            $context['pmx']['AdminMode'] = $admMode;
            $context['pmx']['RegBlocks'] = eval($context['pmx']['registerblocks']);
            // direct edit request?
            if (isset($_GET['sa']) && PortaMx_makeSafe($_GET['sa']) == 'edit' && !empty($_GET['id'])) {
                // move or clone from blocks?
                if (isset($_GET['from'])) {
                    $context['pmx']['fromblock'] = PortaMx_makeSafe($_GET['from']) . '.' . PortaMx_makeSafe($_GET['id']);
                    // load the block
                    $request = $smcFunc['db_query']('', '
						SELECT *
						FROM {db_prefix}portamx_blocks
						WHERE id = {int:id}', array('id' => PortaMx_makeSafe($_GET['id'])));
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $smcFunc['db_free_result']($request);
                    // modify the config array
                    $cfg = unserialize($row['config']);
                    if (isset($cfg['pagename'])) {
                        $pgname = $cfg['pagename'];
                        unset($cfg['pagename']);
                    } else {
                        $pgname = '';
                    }
                    unset($cfg['ext_opts']);
                    if (isset($cfg['frontmode'])) {
                        unset($cfg['frontmode']);
                    }
                    $cfg['can_moderate'] = allowedTo('admin_forum') ? 0 : 1;
                    $article = array('id' => 0, 'name' => $pgname, 'catid' => 0, 'acsgrp' => $row['acsgrp'], 'ctype' => $row['blocktype'], 'config' => serialize($cfg), 'content' => $row['content'], 'active' => 0, 'owner' => $user_info['id'], 'created' => 0, 'approved' => 0, 'approvedby' => 0, 'updated' => 0, 'updatedby' => 0);
                    $context['pmx']['subaction'] = 'editnew';
                    $context['pmx']['articlestart'] = 0;
                } else {
                    $context['pmx']['fromblock'] = '';
                    $request = $smcFunc['db_query']('', '
						SELECT *
						FROM {db_prefix}portamx_articles
						WHERE id = {int:id}', array('id' => PortaMx_makeSafe($_GET['id'])));
                    if ($smcFunc['db_num_rows']($request) > 0) {
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $article = array('id' => $row['id'], 'name' => $row['name'], 'catid' => $row['catid'], 'acsgrp' => $row['acsgrp'], 'ctype' => $row['ctype'], 'config' => $row['config'], 'content' => $row['content'], 'active' => $row['active'], 'owner' => $row['owner'], 'created' => $row['created'], 'approved' => $row['approved'], 'approvedby' => $row['approvedby'], 'updated' => $row['updated'], 'updatedby' => $row['updatedby']);
                        $smcFunc['db_free_result']($request);
                        $context['pmx']['subaction'] = 'edit';
                        $context['pmx']['articlestart'] = 0;
                    }
                }
            }
            // continue edit or overview?
            if ($context['pmx']['subaction'] == 'overview') {
                // load article data for overview
                if (!allowPmx('pmx_articles') && allowPmx('pmx_create', true)) {
                    $where = 'WHERE a.owner = {int:owner}';
                } else {
                    $where = '';
                }
                if (!isset($_SESSION['PortaMx']['filter'])) {
                    $_SESSION['PortaMx']['filter'] = array('category' => '', 'approved' => 0, 'active' => 0, 'myown' => 0, 'member' => '');
                }
                if ($_SESSION['PortaMx']['filter']['category'] != '') {
                    $where .= (empty($where) ? 'WHERE ' : ' AND ') . 'a.catid IN ({array_int:catfilter})';
                }
                if ($_SESSION['PortaMx']['filter']['approved'] != 0) {
                    $where .= empty($where) ? 'WHERE ' : ' AND ';
                    if ($_SESSION['PortaMx']['filter']['active'] != 0) {
                        $where .= '(a.approved = 0 OR a.active = 0)';
                    } else {
                        $where .= 'a.approved = 0';
                    }
                }
                if ($_SESSION['PortaMx']['filter']['active'] != 0) {
                    $where .= empty($where) ? 'WHERE ' : ' AND ';
                    if ($_SESSION['PortaMx']['filter']['approved'] != 0) {
                        $where .= '(a.active = 0 OR a.approved = 0)';
                    } else {
                        $where .= 'a.active = 0';
                    }
                }
                if ($_SESSION['PortaMx']['filter']['myown'] != 0) {
                    $where .= (empty($where) ? 'WHERE ' : ' AND ') . 'a.owner = {int:owner}';
                }
                if ($_SESSION['PortaMx']['filter']['member'] != '') {
                    $where .= (empty($where) ? 'WHERE ' : ' AND ') . 'm.member_name LIKE {string:memname}';
                }
                if (isset($_GET['pg']) && !is_array($_GET['pg'])) {
                    $context['pmx']['articlestart'] = PortaMx_makeSafe($_GET['pg']);
                    unset($_GET['pg']);
                } elseif (!isset($context['pmx']['articlestart'])) {
                    $context['pmx']['articlestart'] = 0;
                }
                $cansee = allowPmx('pmx_articles, pmx_create', true);
                $isadmin = allowPmx('pmx_admin');
                $memerIDs = array();
                $context['pmx']['articles'] = array();
                $context['pmx']['article_rows'] = array();
                $context['pmx']['totalarticles'] = 0;
                $result = null;
                $request = $smcFunc['db_query']('', '
					SELECT a.id, a.name, a.catid, a.acsgrp, a.ctype, a.config, a.active, a.owner, a.created, a.approved, a.approvedby, a.updated, a.updatedby, a.content, c.artsort, c.level, c.name AS catname
					FROM {db_prefix}portamx_articles AS a' . ($_SESSION['PortaMx']['filter']['member'] != '' ? '
					LEFT JOIN {db_prefix}members AS m ON (a.owner = m.id_member)' : '') . '
					LEFT JOIN {db_prefix}portamx_categories AS c ON (a.catid = c.id)
					' . $where . '
					ORDER BY a.id', array('catfilter' => Pmx_StrToArray($_SESSION['PortaMx']['filter']['category']), 'memname' => str_replace('*', '%', $_SESSION['PortaMx']['filter']['member']), 'owner' => $user_info['id']));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        $cfg = unserialize($row['config']);
                        if (!empty($isadmin) || $cansee && !empty($cfg['can_moderate'])) {
                            $memerIDs[] = $row['owner'];
                            $memerIDs[] = $row['approvedby'];
                            $memerIDs[] = $row['updatedby'];
                            $context['pmx']['article_rows'][$row['id']] = array('name' => $row['name'], 'cat' => str_repeat('&bull;', $row['level']) . $row['catname']);
                            $result[] = array('id' => $row['id'], 'name' => $row['name'], 'catid' => $row['catid'], 'cat' => str_repeat('&bull;', $row['level']) . $row['catname'], 'acsgrp' => $row['acsgrp'], 'ctype' => $row['ctype'], 'config' => $cfg, 'active' => $row['active'], 'owner' => $row['owner'], 'created' => $row['created'], 'approved' => $row['approved'], 'approvedby' => $row['approvedby'], 'updated' => $row['updated'], 'updatedby' => $row['updatedby'], 'content' => $row['content']);
                        }
                    }
                    $smcFunc['db_free_result']($request);
                    if (!empty($result)) {
                        foreach ($result as $st => $data) {
                            $context['pmx']['articles'][$st] = $data;
                        }
                        $context['pmx']['totalarticles'] = count($result);
                        if ($context['pmx']['totalarticles'] <= $context['pmx']['articlestart']) {
                            $context['pmx']['articlestart'] = 0;
                        }
                        // get all members names
                        $request = $smcFunc['db_query']('', '
							SELECT id_member, member_name
							FROM {db_prefix}members
							WHERE id_member IN ({array_int:members})', array('members' => array_unique($memerIDs)));
                        if ($smcFunc['db_num_rows']($request) > 0) {
                            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                                $context['pmx']['articles_member'][$row['id_member']] = $row['member_name'];
                            }
                            $smcFunc['db_free_result']($request);
                        }
                    }
                }
                // load popup js for overview
                loadJavascriptFile(PortaMx_loadCompressed('PortaMxPopup.js'), array('external' => true));
            } elseif (empty($_POST['save_edit'])) {
                // prepare the editor
                PortaMx_EditArticle($article['ctype'], 'content', $article['content']);
                // load the class file and create the object
                require_once $context['pmx_sysclassdir'] . 'PortaMx_AdminArticlesClass.php';
                $context['pmx']['editarticle'] = new PortaMxC_SystemAdminArticle($article);
                $context['pmx']['editarticle']->pmxc_AdmArticle_loadinit();
            }
        } else {
            fatal_error($txt['pmx_acces_error']);
        }
    }
}
/**
* Receive all the Posts from Categories Manager, check and save it.
* Finally the categories are prepared and the templare loaded.
*/
function PortaMx_AdminCategories()
{
    global $smcFunc, $context, $scripturl, $pmxCacheFunc, $txt;
    $admMode = isset($_GET['action']) ? $_GET['action'] : '';
    // fix the linktree
    if ($admMode == 'admin') {
        foreach ($context['linktree'] as $key => $data) {
            if (strpos($data['url'], 'pmx_categories') !== false) {
                $context['linktree'] = array_merge(array_slice($context['linktree'], 0, $key), array(array('url' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'name' => $txt['pmx_extension'])), array_slice($context['linktree'], $key, count($context['linktree']) - $key));
                break;
            }
        }
    }
    if (($admMode == 'admin' || $admMode == 'portamx') && allowPmx('pmx_admin') && isset($_GET['area']) && $_GET['area'] == 'pmx_categories') {
        require_once $context['pmx_sourcedir'] . 'AdminSubs.php';
        $context['pmx']['subaction'] = isset($_POST['sa']) ? $_POST['sa'] : 'overview';
        // From template ?
        if (PortaMx_checkPOST()) {
            // check the Post session
            checkSession('post');
            // actions from overview ?
            if ($context['pmx']['subaction'] == 'overview' && empty($_POST['cancel_overview'])) {
                // updates from overview popups ?
                if (!empty($_POST['upd_overview'])) {
                    if (isset($_POST['xml'])) {
                        $xmlResult = '';
                    }
                    $updates = array();
                    foreach ($_POST['upd_overview'] as $updkey => $updvalues) {
                        foreach ($updvalues as $id => $values) {
                            if ($updkey == 'title') {
                                foreach ($values as $key => $val) {
                                    if ($key == 'lang') {
                                        foreach ($val as $langname => $langvalue) {
                                            $updates[$id]['config'][$updkey][$langname] = $langvalue;
                                        }
                                    } else {
                                        $updates[$id]['config'][$updkey . '_' . $key] = $val;
                                    }
                                }
                            } else {
                                $updates[$id][$updkey] = $values;
                            }
                        }
                    }
                    // save all updates
                    foreach ($updates as $id => $values) {
                        $request = $smcFunc['db_query']('', '
							SELECT config, acsgrp
							FROM {db_prefix}portamx_categories
							WHERE id = {int:id}', array('id' => $id));
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $smcFunc['db_free_result']($request);
                        foreach ($values as $rowname => $data) {
                            // update config array
                            if ($rowname == 'config') {
                                $cfg = unserialize($row['config']);
                                foreach ($data as $ckey => $cval) {
                                    if ($ckey == 'title') {
                                        foreach ($cval as $lang => $val) {
                                            $cfg[$ckey][$lang] = $val;
                                        }
                                    } else {
                                        $cfg[$ckey] = $cval;
                                    }
                                }
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}portamx_categories
									SET config = {string:config}
									WHERE id = {int:id}', array('id' => $id, 'config' => serialize($cfg)));
                            } elseif ($rowname == 'catname') {
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}portamx_categories
									SET name = {string:val}
									WHERE id = {int:id}', array('id' => $id, 'val' => $data));
                            } else {
                                $mode = substr($rowname, 0, 3);
                                // update (replace)
                                if ($mode == 'upd') {
                                    $newacs = explode(',', $data);
                                } elseif ($mode == 'add') {
                                    $newacs = array_unique(array_merge(explode(',', $row['acsgrp']), explode(',', $data)));
                                } else {
                                    $newacs = array_unique(array_diff(explode(',', $row['acsgrp']), explode(',', $data)));
                                }
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}portamx_categories
									SET acsgrp = {string:val}
									WHERE id = {int:id}', array('id' => $id, 'val' => implode(',', $newacs)));
                                // send by xml?
                                if (isset($_POST['xml'])) {
                                    $acsnew = implode(',', $newacs);
                                    $xmlResult .= (!empty($xmlResult) ? '&' : '') . $id . '|' . $acsnew . '|' . count($newacs) . '|' . intval(allowPmxGroup($newacs)) . '|1';
                                }
                            }
                        }
                    }
                    // clear cache
                    $pmxCacheFunc['clean']();
                    if (isset($_POST['xml'])) {
                        // return update result
                        ob_start();
                        if (!empty($_POST['result'])) {
                            echo $_POST['result'];
                        } else {
                            echo $xmlResult;
                        }
                        ob_end_flush();
                        exit;
                    }
                }
                // add new category
                if (!empty($_POST['add_new_category'])) {
                    $category = PortaMx_getDefaultCategory();
                    $context['pmx']['subaction'] = 'editnew';
                } elseif (!empty($_POST['edit_category']) || !empty($_POST['clone_category'])) {
                    $id = PortaMx_makeSafe(!empty($_POST['clone_category']) ? $_POST['clone_category'] : $_POST['edit_category']);
                    // load the category for edit/clone
                    $request = $smcFunc['db_query']('', '
						SELECT *
						FROM {db_prefix}portamx_categories
						WHERE id = {int:id}', array('id' => $id));
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $category = array('id' => $row['id'], 'name' => $row['name'], 'parent' => $row['parent'], 'level' => $row['level'], 'catorder' => $row['catorder'], 'acsgrp' => $row['acsgrp'], 'artsort' => $row['artsort'], 'config' => $row['config']);
                    $smcFunc['db_free_result']($request);
                    if (!empty($_POST['clone_category'])) {
                        $category['id'] = 0;
                        $category['parent'] = 0;
                        $category['level'] = 0;
                        $category['catorder'] = 0;
                        $context['pmx']['subaction'] = 'editnew';
                    } else {
                        $context['pmx']['subaction'] = 'edit';
                    }
                } elseif (!empty($_POST['delete_category'])) {
                    pmx_delete_cat(PortaMx_makeSafe($_POST['delete_category']));
                    // set catid in articles to none (0)
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}portamx_articles
						SET catid = 0
						WHERE catid = {int:id}', array('id' => PortaMx_makeSafe($_POST['delete_category'])));
                    // clear cache
                    $pmxCacheFunc['clean']();
                } elseif (!empty($_POST['move_category'])) {
                    pmx_move_cat(PortaMx_makeSafe($_POST['move_category']), PortaMx_makeSafe($_POST['catplace']), PortaMx_makeSafe($_POST['movetocat']));
                    // clear cache
                    $pmxCacheFunc['clean']();
                }
            } elseif (!empty($_POST['cancel_edit']) || !empty($_POST['cancel_overview'])) {
                $context['pmx']['subaction'] = 'overview';
            } elseif ($context['pmx']['subaction'] == 'editnew' || $context['pmx']['subaction'] == 'edit') {
                // check defined numeric vars (check_num_vars holds the posted array to check like [varname][varname] ...)
                if (isset($_POST['check_num_vars'])) {
                    if (isset($_POST['check_num_vars'])) {
                        foreach ($_POST['check_num_vars'] as $val) {
                            $data = explode(',', $val);
                            $post = '$_POST' . str_replace(array('[', ']'), array('[\'', '\']'), $data[0]);
                            if (eval("return isset({$post});") && eval("return !is_numeric({$post});")) {
                                eval("{$post} = {$data['1']};");
                            }
                        }
                    }
                }
                // get all data
                $category = array('id' => $_POST['id'], 'name' => PortaMx_makeSafe($_POST['name']), 'parent' => $_POST['parent'], 'level' => $_POST['level'], 'catorder' => $_POST['catorder'], 'acsgrp' => !empty($_POST['acsgrp']) ? implode(',', $_POST['acsgrp']) : '', 'artsort' => !empty($_POST['artsort']) ? implode(',', $_POST['artsort']) : '', 'config' => serialize($_POST['config']));
                // save category.
                if (empty($_POST['edit_change']) && (!empty($_POST['save_edit']) || !empty($_POST['save_edit_continue']))) {
                    // if new category get the last id and catorder
                    if ($context['pmx']['subaction'] == 'editnew') {
                        $category = pmx_insert_cat(PortaMx_makeSafe($_POST['catplace']), PortaMx_makeSafe($_POST['catid']), $category);
                        // get max catid
                        $request = $smcFunc['db_query']('', '
							SELECT MAX(id)
							FROM {db_prefix}portamx_categories', array());
                        list($maxid) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        $category['id'] = strval(1 + ($maxid === null ? $category['id'] : $maxid));
                    }
                    // now save all data
                    $smcFunc['db_insert']('replace', '
						{db_prefix}portamx_categories', array('id' => 'int', 'name' => 'string', 'parent' => 'int', 'level' => 'int', 'catorder' => 'int', 'acsgrp' => 'string', 'artsort' => 'string', 'config' => 'string'), array($category['id'], $category['name'], $category['parent'], $category['level'], $category['catorder'], $category['acsgrp'], $category['artsort'], $category['config']), array('id'));
                    // clear cache
                    $pmxCacheFunc['clean']();
                    $context['pmx']['subaction'] = 'edit';
                }
                // continue edit ?
                if (!empty($_POST['save_edit'])) {
                    $context['pmx']['subaction'] = 'overview';
                }
            }
            if ($context['pmx']['subaction'] == 'overview') {
                redirectexit('action=' . $admMode . ';area=pmx_categories;' . $context['session_var'] . '=' . $context['session_id']);
            }
        }
        // load template, setup pagetitle
        loadTemplate($context['pmx_templatedir'] . 'AdminCategories');
        $context['page_title'] = $txt['pmx_categories'];
        $context['pmx']['AdminMode'] = $admMode;
        // direct edit request?
        if (isset($_GET['sa']) && PortaMx_makeSafe($_GET['sa']) == 'edit' && !empty($_GET['id'])) {
            // load the category for edit
            $request = $smcFunc['db_query']('', '
				SELECT *
				FROM {db_prefix}portamx_categories
				WHERE id = {int:id}', array('id' => PortaMx_makeSafe($_GET['id'])));
            if ($smcFunc['db_num_rows']($request) > 0) {
                $row = $smcFunc['db_fetch_assoc']($request);
                $category = array('id' => $row['id'], 'name' => $row['name'], 'parent' => $row['parent'], 'level' => $row['level'], 'catorder' => $row['catorder'], 'acsgrp' => $row['acsgrp'], 'artsort' => $row['artsort'], 'config' => $row['config']);
                $smcFunc['db_free_result']($request);
                $context['pmx']['subaction'] = 'edit';
            }
        }
        // continue edit or overview ?
        if ($context['pmx']['subaction'] == 'overview') {
            // load all categories
            $context['pmx']['categories'] = PortaMx_getCategories(true);
            // load popup js for overview
            loadJavascriptFile(PortaMx_loadCompressed('PortaMxPopup.js'), array('external' => true));
        } elseif (empty($_POST['save_edit'])) {
            // load the class file and create the object
            require_once $context['pmx_sysclassdir'] . 'PortaMx_AdminCategoriesClass.php';
            $context['pmx']['editcategory'] = new PortaMxC_SystemAdminCategories($category);
            $context['pmx']['editcategory']->pmxc_AdmCategories_loadinit();
        }
    } else {
        fatal_error($txt['pmx_acces_error']);
    }
}
/**
* 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();
}
/**
* Create all the Informationen for the Admin Center.
* Finally load the templare.
*/
function PortaMx_AdminCenter()
{
    global $smcFunc, $context, $settings, $sourcedir, $scripturl, $txt, $pmxCacheFunc;
    // fix the linktree
    $admMode = isset($_GET['action']) ? $_GET['action'] : '';
    if ($admMode == 'admin') {
        foreach ($context['linktree'] as $key => $data) {
            if (strpos($data['url'], 'pmx_center') !== false) {
                $context['linktree'][$key]['name'] = $txt['pmx_extension'];
                break;
            }
        }
    }
    if (($admMode == 'admin' || $admMode == 'portamx') && allowPmx('pmx_admin')) {
        $context['pmx']['subaction'] = isset($_GET['sa']) ? $_GET['sa'] : 'main';
        if ($context['pmx']['subaction'] == 'settings') {
            $context['pmx']['subaction'] = 'main';
        }
        $context['pmx']['pmx_area'] = $_GET['area'];
        $context['pmx']['admmode'] = $admMode;
        // Admin center main?
        if ($context['pmx']['subaction'] == 'main') {
            // show the Admin center
            $liveinfo = getLiveInfo();
            $context['pmx_info'] = $liveinfo;
            $context['pmx_info']['installed'] = getInstalledPackage();
            $context['pmx_info']['versionOK'] = !empty($liveinfo['version']) && $liveinfo['version'] <= $context['pmx_info']['installed'];
            // If update available, get server from package_server table
            if (!empty($context['pmx_info']['update']) && empty($context['pmx_info']['versionOK'])) {
                $request = $smcFunc['db_query']('', '
						SELECT id_server
						FROM {db_prefix}package_servers
						WHERE url = {string:url}', array('url' => substr($context['pmx']['server']['url'], 0, -1)));
                if ($row = $smcFunc['db_fetch_assoc']($request)) {
                    $context['pmx_info']['updserver'] = $row['id_server'];
                    $smcFunc['db_free_result']($request);
                } else {
                    $smcFunc['db_insert']('', '
						{db_prefix}package_servers', array('name' => 'string', 'url' => 'string'), array('PortaMx File Server', substr($context['pmx']['server']['url'], 0, -1)), array('id_server'));
                    $context['pmx_info']['updserver'] = $smcFunc['db_insert_id']('{db_prefix}package_servers', 'id_server');
                }
            }
        } elseif ($context['pmx']['subaction'] == 'flist') {
            checkSession('get');
            $srcdir = $sourcedir;
            $thmdir = $settings['default_theme_dir'];
            $dirs = array('pmx_source_files' => array($srcdir => array('/PortaMx/', '/PortaMx/Class/', '/PortaMx/Class/System/')), 'pmx_template_files' => array($thmdir => array('/PortaMx/', '/PortaMx/SysCss/', '/PortaMx/BlockCss/', '/PortaMx/Scripts/')), 'pmx_language_files' => array($thmdir . '/languages' => array('/PortaMx/')));
            $allfiles = array();
            $fileExt = array();
            $installed = getInstalledLanguages();
            foreach ($installed as $data) {
                $fileExt[] = $data['langext'] . '.php';
            }
            // read all dirs
            foreach ($dirs as $dirname => $basedirs) {
                foreach ($basedirs as $base => $subdirs) {
                    foreach ($subdirs as $dir) {
                        if (is_dir($base . $dir)) {
                            $files = array();
                            if ($dh = opendir($base . $dir)) {
                                while (($file = readdir($dh)) !== false) {
                                    if (is_file($base . $dir . $file)) {
                                        $files[] = $file;
                                    }
                                }
                                closedir($dh);
                            }
                        }
                        if (!empty($files)) {
                            $allfiles[$dirname][$dir] = array('dir' => $base . $dir, 'subdir' => $dir, 'files' => $files);
                        }
                    }
                }
            }
            // cleanup..
            unset($dirs[$dirname]);
            // get lifeinfo
            $currentversion = getLiveInfo('version');
            // Package ...
            $result['pmx_filepackage']['files'][''] = array();
            $result['pmx_filepackage']['current'] = $currentversion;
            $result['pmx_filepackage']['installed'] = getInstalledPackage();
            // check all files
            foreach ($allfiles as $dirtext => $dirname) {
                $lowdate = '01.01.1900';
                $lowversion = '';
                foreach ($dirname as $data) {
                    $subdir = $data['subdir'];
                    foreach ($data['files'] as $file) {
                        if ($file != 'index.php' && substr($file, -1, 1) != '~') {
                            $handle = fopen($data['dir'] . $file, "r");
                            $content = fread($handle, 512);
                            fclose($handle);
                            $versOK = preg_match("~\\*\\s.version\\s([A-Za-z0-9\\.\\-\\s]+)~i", $content, $version) != 0;
                            if ($versOK && strcasecmp(trim($version[1]), $lowversion) >= 0) {
                                $lowversion = $version[1];
                            }
                            $dateOK = preg_match("~\\*\\s.date\\s([A-Za-z0-9\\.\\-]+)~i", $content, $date) != 0;
                            if ($dateOK && $date[1] > $lowdate) {
                                $lowdate = $date[1];
                            }
                            $result[$dirtext]['files'][$file] = array('subdir' => $subdir, 'version' => $versOK ? $version[1] : '?.???', 'date' => $dateOK ? $date[1] : '??.??.????');
                            unset($content);
                        }
                    }
                }
                $result[$dirtext]['current'] = $currentversion;
                $result[$dirtext]['installed'] = $lowversion;
                $result[$dirtext]['lowdate'] = $lowdate;
            }
            $context['pmx_info'] = $result;
            $context['pmx_installed_ext'] = $fileExt;
            unset($result);
        } elseif ($context['pmx']['subaction'] == 'showlang') {
            checkSession('get');
            // fix the linktree
            if ($context['pmx']['admmode'] == 'admin') {
                foreach ($context['linktree'] as $key => $data) {
                    if (strpos($data['url'], 'pmx_languages') !== false) {
                        $context['linktree'] = array_merge(array_slice($context['linktree'], 0, $key), array(array('url' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'name' => $txt['pmx_extension'])), array_slice($context['linktree'], $key, count($context['linktree']) - $key));
                        break;
                    }
                }
            }
            // get all installed languages
            $context['pmx']['instlang'] = getInstalledLanguages();
            // get all existing languages
            $info = readDocServer($context['pmx']['server']['lang']);
            if (!empty($info)) {
                if (GetFirstChildContentByName($info, 'copyright') == 'PortaMx') {
                    $elmlist = GetChildByPathAndName($info, '', 'item');
                    foreach ($elmlist as $elm) {
                        $context['pmx']['langsets'][] = array('name' => GetFirstChildContentByName($elm, 'name'), 'version' => GetFirstChildContentByName($elm, 'version'), 'charset' => GetFirstChildContentByName($elm, 'charset'), 'link' => GetFirstChildContentByName($elm, 'link'));
                    }
                }
            }
            // check for manually installable languages
            getManuallyLanguages($context['pmx']['instlang']);
        } elseif ($context['pmx']['subaction'] == 'admlang') {
            checkSession('post');
            // lang delete ?
            if (isset($_POST['lang_delete']) && !empty($_POST['lang_delete'])) {
                // get the values...
                $langId = PortaMx_makeSafe($_POST['lang_delete']);
                $failed = AdmCenterLangDelete($langId);
                if (empty($failed)) {
                    redirectexit('action=' . $admMode . ';area=' . $context['pmx']['pmx_area'] . ';sa=showlang;' . $context['session_var'] . '=' . $context['session_id']);
                } else {
                    AdmCenterError($txt['pmx_center_langdelfailed'], $txt['pmx_center_langdelerror'], 'showlang');
                }
            } elseif (isset($_POST['lang_install']) && !empty($_POST['lang_install'])) {
                // Get the install values ...
                $InstLink = PortaMx_makeSafe($_POST['lang_install']);
                $failed = true;
                $info = readDocServer($context['pmx']['server']['lang'] . $InstLink);
                if (GetFirstChildContentByName($info, 'copyright') == 'PortaMx') {
                    // get the language description
                    $langSet = array();
                    $langSet['name'] = GetFirstChildContentByName($info, 'name');
                    $langSet['version'] = GetFirstChildContentByName($info, 'version');
                    $langSet['charset'] = GetFirstChildContentByName($info, 'charset');
                    $langSet['langext'] = GetFirstChildContentByName($info, 'langext');
                    // get installed languages
                    $langlist = getInstalledLanguages();
                    $instId = '';
                    foreach ($langlist as $id => $data) {
                        $instId = compareLang($langSet, $data) ? $id : $instId;
                    }
                    // if Update, delete old lang first
                    $failed = false;
                    if (!empty($instId)) {
                        $failed = AdmCenterLangDelete($instId);
                    } else {
                        $instId = 'lang' . $langSet['langext'];
                    }
                    if (empty($failed)) {
                        // get filelist
                        $langfiles = array();
                        $elmlist = GetChildByPathAndName($info, '', 'item');
                        foreach ($elmlist as $elm) {
                            $fname = GetFirstChildContentByName($elm, 'name');
                            $langfiles[$fname] = GetFirstChildContentByName($elm, 'path');
                        }
                        // now get languagefiles from Portamx server
                        foreach ($langfiles as $file => $path) {
                            $content = readDocServer($context['pmx']['server']['lang'] . $InstLink . 'PortaMx/' . $file . $langSet['langext'], '<?php');
                            $content = trim($content);
                            if (!empty($content)) {
                                $fsize = strlen($content);
                                $filename = $settings['default_theme_dir'] . $path . $file . $langSet['langext'] . '.php';
                                if (file_exists($filename)) {
                                    if (!is_writable($filename)) {
                                        @chmod($filename, 0644);
                                        if (!is_writable($filename)) {
                                            @chmod($filename, 0777);
                                        }
                                    }
                                }
                                if (empty($failed)) {
                                    $written = 0;
                                    $fhd = fopen($filename, 'w');
                                    if ($fhd) {
                                        $written = fwrite($fhd, $content);
                                        fclose($fhd);
                                    }
                                }
                                if (!empty($failed) || $written != $fsize) {
                                    $failed = true;
                                    break;
                                }
                            } else {
                                $failed = true;
                                break;
                            }
                        }
                        if (empty($failed)) {
                            sleep(1);
                            // add or replace the installed language
                            $lset = array('name' => $langSet['name'], 'version' => $langSet['version'], 'charset' => $langSet['charset'], 'langext' => $langSet['langext']);
                            // save installed languages
                            $smcFunc['db_insert']('replace', '
								{db_prefix}portamx_settings', array('varname' => 'string', 'config' => 'string'), array($instId, serialize($lset)), array('varname'));
                            // clear the filecache and redirect exit
                            // clear cache
                            $pmxCacheFunc['clean']();
                            redirectexit('action=' . $admMode . ';area=' . $context['pmx']['pmx_area'] . ';sa=showlang;' . $context['session_var'] . '=' . $context['session_id']);
                        }
                    }
                }
                if (!empty($failed)) {
                    if (isset($context['pmx']['feed_error_text']) && !empty($context['pmx']['feed_error_text'])) {
                        AdmCenterError($txt['pmx_center_langfetchfailed'] . '<br />' . $context['pmx']['feed_error_text'], $txt['pmx_center_langinsterror'], 'showlang');
                    } else {
                        AdmCenterError($txt['pmx_center_langfetchfailed'], $txt['pmx_center_langinsterror'], 'showlang');
                    }
                }
            } elseif (isset($_POST['lang_install_manually']) && !empty($_POST['lang_install_manually'])) {
                // Get the install values ...
                $manlang = PortaMx_makeSafe($_POST['lang_install_manually']);
                $langlist = getInstalledLanguages();
                getManuallyLanguages($langlist);
                $langSet = $context['pmx']['manualylangsets'][$manlang];
                $instId = '';
                foreach ($langlist as $id => $data) {
                    $instId = compareLang($data, $langSet) ? $id : $instId;
                }
                // new id if lang not exist
                if (empty($instId)) {
                    $instId = $manlang;
                }
                // add or replace the installed language
                $lset = array('name' => $langSet['name'], 'version' => $langSet['version'], 'charset' => $langSet['charset'], 'langext' => $langSet['langext'], 'manually' => true);
                // save installed language
                $smcFunc['db_insert']('replace', '
						{db_prefix}portamx_settings', array('varname' => 'string', 'config' => 'string'), array($instId, serialize($lset)), array('varname'));
                // clear the filecache and redirect exit
                $pmxCacheFunc['clean']();
                redirectexit('action=' . $admMode . ';area=' . $context['pmx']['pmx_area'] . ';sa=showlang;' . $context['session_var'] . '=' . $context['session_id']);
            } else {
                AdmCenterError($txt['pmx_actionfault']);
            }
        }
        // setup pagetitle
        $context['page_title'] = $txt['pmx_admin_center'];
        // load the template
        loadTemplate($context['pmx_templatedir'] . 'AdminCenter');
    } else {
        fatal_error($txt['pmx_acces_error']);
    }
}
    /**
     * ShowContent
     */
    function pmxc_ShowContent()
    {
        global $scripturl, $context, $user_info, $txt;
        echo '
				<div style="padding-bottom:4px;"' . (isset($this->cfg['config']['visuals']['questiontext']) ? ' class="' . $this->cfg['config']['visuals']['questiontext'] . '"' : '') . '>
					<a href="' . $scripturl . '?topic=' . $this->polls['topic'] . '.0"><b>' . $this->polls['question'] . '</b></a>';
        if (!empty($this->polls['is_locked']) && (!empty($this->polls['allow_view_results']) || empty($this->polls['allow_view_results']) && empty($this->polls['allow_vote']) && empty($this->polls['is_expired']))) {
            echo '<span' . (isset($this->cfg['config']['visuals']['bodytext']) ? ' class="' . $this->cfg['config']['visuals']['bodytext'] . '"' : '') . '>' . $txt['pmx_poll_select_locked'] . '</span>';
        }
        echo '
				</div>';
        if (!empty($this->polls['allow_vote'])) {
            echo '
				<div id="pxm_allowvotepoll' . $this->cfg['id'] . '"' . (!empty($this->polls['allow_view_results']) && $this->currentpoll['state'] == '1' ? ' style="display:none"' : '') . '>
					<form id="pmx_voteform' . $this->cfg['id'] . '" action="' . $scripturl . '?action=vote;topic=' . $this->polls['topic'] . ';poll=' . $this->polls['id'] . '" method="post" accept-charset="', $context['character_set'], '">
						<input type="hidden" name="poll" value="' . $this->polls['id'] . '" />
						<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" />
						<input type="hidden" name="pmx_votepoll" value="' . pmx_http_build_query($_GET) . '" />
						<div style="padding-top:4px;line-height:1em;">';
            $i = 0;
            foreach ($this->polls['options'] as $option) {
                echo '
							<div class="polloptions"><label id="pmx_pollopt' . $this->cfg['id'] . '_' . $i . '" style="border:none; background:transparent;" for="' . $option['id'] . '">' . $option['vote_button'] . ' <span style="vertical-align:3px;">' . $option['option'], '</span></label></div>';
                $i++;
            }
            echo '
						</div>
						<div>' . $this->polls['allowed_warning'] . '</div>';
            if (!empty($this->polls['expired'])) {
                echo '
						<div style="padding-top:4px;"><b>' . $txt['poll_expires_on'] . ':</b> ' . $this->polls['expired'] . '</div>';
            }
            echo '
						<hr class="pmx_hr" />
						<input style="margin:2px;float:right;" type="button" class="button_submit" name="button" value="' . $txt['poll_vote'] . '" onmouseup="pmx_VotePoll(\'' . $this->cfg['id'] . '\', this)" />';
            if ($this->polls['allow_view_results']) {
                echo '
						<input style="margin:2px;float:left;" type="button" class="button_submit" name="button" value="' . $txt['pmx_poll_results'] . '" onmouseup="pmx_ShowPollResult(\'' . $this->cfg['id'] . '\', this)" />';
            }
            echo '
					</form>
				</div>';
        }
        if (!empty($this->polls['allow_view_results'])) {
            echo '
				<div id="pxm_allowviewpoll' . $this->cfg['id'] . '"' . (!empty($this->polls['allow_vote']) && $this->currentpoll['state'] == '0' ? ' style="display:none"' : '') . '>
					<table class="pmx_table">';
            $tablen = 100 / $this->polls['tablen'];
            $tablen = $tablen > 100 ? 100 : $tablen;
            $ownpolls = isset($this->PollChoices[$this->polls['id']]) ? $this->PollChoices[$this->polls['id']] : array();
            // Guestpolls
            // ;id,timestamp,[vote,vote...]; etc
            $cook = pmx_getcookie('guest_poll_vote');
            if (empty($cook)) {
                $guestpolls = array();
            } else {
                $guestinfo = explode(';', trim($cook, ';'));
                // Find the poll we're after.
                foreach ($guestinfo as $i => $guestvoted) {
                    $temp = explode(',', $guestvoted);
                    if ($temp[0] != $this->polls['id']) {
                        continue;
                    } else {
                        $guestpolls[] = $temp[2];
                    }
                }
            }
            foreach ($this->polls['options'] as $key => $option) {
                $barlen = $option['percent'] == 0 ? '0' : ceil($option['percent'] * $tablen);
                $barlen = $barlen > 100 ? 100 : $barlen;
                $strong = $option['percent'] > 0 && ($user_info['is_guest'] && is_array($guestpolls) && in_array($key, $guestpolls)) || !$user_info['is_guest'] && is_array($ownpolls) && in_array($key, $ownpolls) ? array(0 => '<b>', 1 => '</b>') : array(0 => '', 1 => '');
                echo '
				<tr>
					<td style="text-align:left;height:35px;width:95%;">' . $strong[0] . $option['option'] . $strong[1] . '
						<div style="height: 10px;width:' . $barlen . '%;"' . ($barlen > 0 ? ' class="poll_bar"' : '') . '></div>
					</td>
					<td style="text-align:right;">
						<div style="margin-top:14px;white-space:nowrap;margin-left:8px;">
						 ' . $strong[0] . $option['votes'] . ' (' . $option['percent'] . '%)' . $strong[1] . '
						</div>
					</td>
				</tr>';
            }
            echo '
					</table>
					<div style="clear:both; padding-top:8px;"><b>' . $txt['poll_total_voters'] . ':</b> ' . $this->polls['total_votes'] . '</div>';
            if (!empty($this->polls['expired'])) {
                echo '
					<div style="padding-top:4px;"><b>' . (!empty($this->polls['is_expired']) ? $txt['pmx_poll_closed'] . '</b>' : $txt['poll_expires_on'] . ':</b> ' . $this->polls['expired']) . '</div>';
            }
            if (!empty($this->polls['allow_vote']) || !empty($this->polls['allow_change_vote'])) {
                echo '
					<hr class="pmx_hr" />';
                if (!empty($this->polls['allow_vote'])) {
                    echo '
						<input style="margin:2px;float:right;" type="button" class="button_submit" name="button" value="' . $txt['poll_return_vote'] . '" onmouseup="pmx_ShowPollVote(' . $this->cfg['id'] . ', ' . $this->currentpoll['id'] . ')" />';
                }
                if (!empty($this->polls['allow_change_vote'])) {
                    echo '
					<input  style="margin:2px;float:right;" type="button" class="button_submit" name="button" value="' . $txt['poll_change_vote'] . '" onmouseup="pmx_ChangePollVote(' . $this->cfg['id'] . ', this)" />
					<form id="pmx_voteform' . $this->cfg['id'] . '" action="' . $scripturl . '?action=vote;topic=' . $this->polls['topic'] . ';poll=' . $this->polls['id'] . '" method="post" accept-charset="', $context['character_set'], '">
						<input type="hidden" name="poll" value="' . $this->polls['id'] . '" />
						<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" />
						<input type="hidden" name="pmx_votepoll" value="' . pmx_http_build_query($_GET) . '" />
					</form>';
                }
            }
            echo '
				</div>';
        }
        if (empty($this->polls['allow_view_results']) && empty($this->polls['allow_vote']) && empty($this->polls['is_expired'])) {
            echo '
				<div style="padding:0 3px;">';
            foreach ($this->polls['options'] as $option) {
                echo '
					' . $option['option'] . '<div style="line-height:0.8em; padding-bottom:0.5em;">&nbsp;&laquo;&ndash;&raquo;</div>';
            }
            if (!empty($this->polls['expired'])) {
                echo '
					<div style="padding-top:4px;"><b>' . (!empty($this->polls['is_expired']) ? $txt['pmx_poll_closed'] . '</b>' : $txt['poll_expires_on'] . ':</b> ' . $this->polls['expired']) . '</div>';
            }
            echo '
				</div>';
            if (!empty($this->polls['allow_vote']) || !empty($this->polls['allow_change_vote'])) {
                echo '
				<hr class="pmx_hr" />';
                if (!empty($this->polls['allow_change_vote'])) {
                    echo '
				<input  style="margin:2px;float:right;" type="button" class="button_submit" name="button" value="' . $txt['poll_change_vote'] . '" onmouseup="pmx_ChangePollVote(' . $this->cfg['id'] . ', this)" />
				<form id="pmx_voteform' . $this->cfg['id'] . '" action="' . $scripturl . '?action=vote;topic=' . $this->polls['topic'] . ';poll=' . $this->polls['id'] . '" method="post" accept-charset="', $context['character_set'], '">
					<input type="hidden" name="poll" value="' . $this->polls['id'] . '" />
					<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" />
					<input type="hidden" name="pmx_votepoll" value="' . pmx_http_build_query($_GET) . '" />
				</form>';
                }
            }
        }
        // multiple polls enabled?
        if (count($this->pollquestions) > 1) {
            $maxwidth = in_array($this->cfg['side'], array('right', 'left')) ? '98%' : 0;
            $cact = empty($_SERVER['QUERY_STRING']) ? '' : '?' . PortaMx_makeSafe($_SERVER['QUERY_STRING']);
            echo '
				<form id="pmx_votechange' . $this->cfg['id'] . '" action="' . $scripturl . $cact . '" method="post" accept-charset="', $context['character_set'], '">
					<input id="pollchanged' . $this->cfg['id'] . '" type="hidden" name="pollchanged' . $this->cfg['id'] . '" value="' . $this->polls['id'] . '" />
					<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" />
					<div style="padding:5px 0 2px 0;">' . $txt['pmx_pollmultiview'] . '</div>
						<select name="pollselect"' . (!empty($maxwidth) ? ' style="width:' . $maxwidth . ';"' : '') . ' onchange="pmx_ChangeCurrentPoll(\'' . $this->cfg['id'] . '\', this);">';
            foreach ($this->pollquestions as $id => $question) {
                echo '
							<option value="' . $id . '"' . ($id == $this->currentpoll['id'] ? ' selected="selected"' : '') . '>' . $question . '</option>';
            }
            echo '
					</select>
				</form>';
        }
    }
    /**
     * InitContent.
     * Checked is a shout received ($_POST).
     */
    function pmxc_InitContent()
    {
        global $user_info, $smcFunc, $pmxCacheFunc;
        $this->pmxc_ShoutSetup();
        // shout send?
        if (isset($_POST['pmx_shout']) && !empty($_POST['pmx_shout']) && $_POST['shoutbox_id'] == $this->cfg['id']) {
            if (!empty($this->canShout)) {
                checkSession('post');
                $shoutcmd = PortaMx_makeSafe($_POST['pmx_shout']);
                $update = false;
                // get the shouts
                $shouts = unserialize($this->cfg['content']);
                $shouts = is_array($shouts) ? $shouts : array();
                // delete a shout?
                if ($shoutcmd == 'delete') {
                    $id = PortaMx_makeSafe($_POST['shoutid']);
                    if (isset($shouts[$id])) {
                        unset($shouts[$id]);
                        if (!empty($shouts)) {
                            $new = array();
                            foreach ($shouts as $data) {
                                $new[] = $data;
                            }
                            $shouts = $new;
                        }
                        $this->cfg['content'] = serialize($shouts);
                        unset($new);
                        $update = true;
                    }
                }
                // update a shout?
                if ($shoutcmd == 'update') {
                    $id = PortaMx_makeSafe($_POST['shoutid']);
                    if (isset($shouts[$id])) {
                        // clean the input stream
                        $post = PortaMx_makeSafeContent(str_replace(array("\n", "\t"), array('[br]', ' '), $_POST['post']));
                        $post = $this->ShortenBBCpost($post, intval($this->cfg['config']['settings']['maxlen']));
                        if ($this->BBCtoHTML($post) != '') {
                            // convert html to char
                            $post = $this->HTMLtoChar($post);
                            $shouts[$id]['post'] = $this->ChartoHTML($post, true);
                            $this->cfg['content'] = serialize($shouts);
                            $update = true;
                        }
                    }
                }
                // save a new shout ?
                if ($shoutcmd == 'save') {
                    // clean the input stream
                    $post = PortaMx_makeSafeContent(str_replace(array("\n", "\t"), array('[br]', ' '), $_POST['post']));
                    $post = $this->ShortenBBCpost($post, intval($this->cfg['config']['settings']['maxlen']));
                    if ($this->BBCtoHTML($post) != '') {
                        // get the shouts
                        $shout = array('uid' => $user_info['id'], 'ip' => $user_info['ip'], 'time' => forum_time(false), 'post' => $this->ChartoHTML($post, true));
                        array_unshift($shouts, $shout);
                        // max shouts reached?
                        if (isset($this->cfg['config']['settings']['maxshouts']) && count($shouts) > $this->cfg['config']['settings']['maxshouts']) {
                            array_splice($shouts, $this->cfg['config']['settings']['maxshouts']);
                            // resort
                            $new = array();
                            foreach ($shouts as $data) {
                                $new[] = $data;
                            }
                            $shouts = $new;
                            unset($new);
                        }
                        $this->cfg['content'] = serialize($shouts);
                        $update = true;
                    }
                }
                // need to save?
                if (!empty($update)) {
                    $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_blocks
							SET content = {string:content}
							WHERE id = {int:id}', array('id' => $this->cfg['id'], 'content' => $this->cfg['content']));
                }
                // cleanup
                unset($shouts);
                if ($this->cfg['cache'] > 0) {
                    $pmxCacheFunc['clear']($this->cache_key, $this->cache_mode);
                }
            }
        }
        if ($this->visible) {
            // get the shouts
            $this->shouts = unserialize($this->cfg['content']);
            $this->shouts = is_array($this->shouts) ? $this->shouts : array();
            // get member data
            if ($this->cfg['cache'] > 0) {
                if (($this->memdata = $pmxCacheFunc['get']($this->cache_key, $this->cache_mode)) === null) {
                    $this->get_memberdata();
                    $pmxCacheFunc['put']($this->cache_key, $this->memdata, $this->cache_time, $this->cache_mode);
                }
            } else {
                $this->get_memberdata();
            }
        }
        // call the show content on Post
        if (isset($_POST['pmx_shout']) && !empty($_POST['pmx_shout']) && $_POST['shoutbox_id'] == $this->cfg['id']) {
            unset($_POST);
            $_POST['reload'] = true;
            $this->pmxc_ShowContent();
        }
        // return the visibility flag (true/false)
        return $this->visible;
    }
/**
* Receive all the Posts from Articles Manager, check and save it.
* Finally the articles are prepared and the template loaded.
*/
function PortaMx_AdminBlocks()
{
    global $smcFunc, $context, $sourcedir, $scripturl, $user_info, $pmxCacheFunc, $modSettings, $txt;
    $_GET = PortaMx_makeSafe($_GET);
    $admMode = $_GET['action'];
    $pmx_area = $_GET['area'];
    $newBlockSide = '';
    // fix the linktree
    if ($admMode == 'admin') {
        foreach ($context['linktree'] as $key => $data) {
            if (strpos($data['url'], 'pmx_blocks') !== false) {
                $context['linktree'] = array_merge(array_slice($context['linktree'], 0, $key), array(array('url' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'name' => $txt['pmx_extension'])), array_slice($context['linktree'], $key, count($context['linktree']) - $key));
                break;
            }
        }
    }
    if (($admMode == 'admin' || $admMode == 'portamx') && $pmx_area == 'pmx_blocks') {
        if (allowPmx('pmx_admin, pmx_blocks')) {
            require_once $context['pmx_sourcedir'] . 'AdminSubs.php';
            $context['pmx']['subaction'] = isset($_POST['sa']) ? $_POST['sa'] : 'all';
            // From template ?
            if (PortaMx_checkPOST()) {
                // check the Post array
                checkSession('post');
                $context['pmx']['function'] = $_POST['function'];
                // actions from overview ?
                if ($context['pmx']['function'] == 'overview') {
                    // update action from overview?
                    if (!empty($_POST['upd_overview'])) {
                        $updates = array();
                        $chgSides = array();
                        foreach ($_POST['upd_overview'] as $side => $sidevalues) {
                            $chgSides[] = $side;
                            foreach ($sidevalues as $updkey => $updvalues) {
                                foreach ($updvalues as $id => $values) {
                                    if ($updkey == 'title') {
                                        foreach ($values as $key => $val) {
                                            if ($key == 'lang') {
                                                foreach ($val as $langname => $langvalue) {
                                                    $updates[$id]['config'][$updkey][$langname] = $langvalue;
                                                }
                                            } else {
                                                $updates[$id]['config'][$updkey . '_' . $key] = $val;
                                            }
                                        }
                                    } else {
                                        $updates[$id][$updkey] = $values;
                                    }
                                }
                            }
                        }
                        // save all updates (title, access)
                        foreach ($updates as $id => $values) {
                            $request = $smcFunc['db_query']('', '
								SELECT config, acsgrp, blocktype
								FROM {db_prefix}portamx_blocks
								WHERE id = {int:id}', array('id' => $id));
                            $row = $smcFunc['db_fetch_assoc']($request);
                            $smcFunc['db_free_result']($request);
                            $blocktype = $row['blocktype'];
                            foreach ($values as $rowname => $data) {
                                // update config array
                                if ($rowname == 'config') {
                                    $cfg = unserialize($row['config']);
                                    foreach ($data as $ckey => $cval) {
                                        if ($ckey == 'title') {
                                            foreach ($cval as $lang => $val) {
                                                $cfg[$ckey][$lang] = $val;
                                            }
                                        } else {
                                            $cfg[$ckey] = $cval;
                                        }
                                    }
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_blocks
										SET config = {string:config}
										WHERE id = {int:id}', array('id' => $id, 'config' => serialize($cfg)));
                                } else {
                                    if (!empty($_POST['xml']) && !isset($xmlResult)) {
                                        $xmlResult = '';
                                    }
                                    // update (replace)
                                    $mode = substr($rowname, 0, 3);
                                    if ($mode == 'upd') {
                                        $newacs = explode(',', $data);
                                    } elseif ($mode == 'add') {
                                        $newacs = array_unique(array_merge(explode(',', $row['acsgrp']), explode(',', $data)));
                                    } else {
                                        $newacs = array_unique(array_diff(explode(',', $row['acsgrp']), explode(',', $data)));
                                    }
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_blocks
										SET acsgrp = {string:val}
										WHERE id = {int:id}', array('id' => $id, 'val' => implode(',', $newacs)));
                                    // send by xml?
                                    if (isset($xmlResult)) {
                                        $request = $smcFunc['db_query']('', '
											SELECT active
											FROM {db_prefix}portamx_blocks
											WHERE id = {int:id}', array('id' => $id));
                                        list($active) = $smcFunc['db_fetch_row']($request);
                                        $smcFunc['db_free_result']($request);
                                        $count = count($newacs);
                                        $newacs = implode(',', $newacs);
                                        $xmlResult .= (!empty($xmlResult) ? '&' : '') . $id . '|' . $newacs . '|' . $count . '|' . intval(allowPmxGroup($newacs)) . '|' . $active;
                                    }
                                }
                            }
                            // clear cache
                            $pmxCacheFunc['clean']();
                        }
                        if (!empty($_POST['xml']) && isset($xmlResult)) {
                            // return update acces result
                            ob_start();
                            echo $xmlResult;
                            ob_end_flush();
                            exit;
                        }
                    } elseif (!empty($_POST['chg_status'])) {
                        $id = PortaMx_makeSafe($_POST['chg_status']);
                        $request = $smcFunc['db_query']('', '
							SELECT side, blocktype
							FROM {db_prefix}portamx_blocks
							WHERE id = {int:id}', array('id' => $id));
                        list($side, $blocktype) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_blocks
							SET active = CASE WHEN active = 0 THEN 1 ELSE 0 END
							WHERE id = {int:id}', array('id' => $id));
                        // Post send by xml http ?
                        if (!empty($_POST['xml'])) {
                            // check if we have active blocks in this panel
                            $request = $smcFunc['db_query']('', '
								SELECT acsgrp, active
								FROM {db_prefix}portamx_blocks
								WHERE id = {int:id}', array('id' => $id));
                            list($acs, $status) = $smcFunc['db_fetch_row']($request);
                            $smcFunc['db_free_result']($request);
                            // clear cache
                            $pmxCacheFunc['clean']();
                            // return result
                            ob_start();
                            echo $status . ',' . intval(allowPmxGroup($acs));
                            ob_end_flush();
                            exit;
                        }
                    }
                    // add new block
                    if (!empty($_POST['add_new_block'])) {
                        $id = null;
                        $context['pmx']['function'] = 'editnew';
                        list($newBlockSide) = array_keys($_POST['add_new_block']);
                        list($block) = array_values($_POST['add_new_block']);
                    } elseif (!empty($_POST['upd_rowpos'])) {
                        list($side) = each($_POST['upd_rowpos']);
                        list($fromID, $place, $toID) = Pmx_StrToArray($_POST['upd_rowpos'][$side]['rowpos']);
                        $request = $smcFunc['db_query']('', '
							SELECT id, pos
							FROM {db_prefix}portamx_blocks
							WHERE id IN({array_int:ids})', array('ids' => array($fromID, $toID)));
                        while ($row = $smcFunc['db_fetch_assoc']($request)) {
                            $moveData[$row['id']] = $row['pos'];
                        }
                        $smcFunc['db_free_result']($request);
                        // create the query...
                        if ($moveData[$fromID] > $moveData[$toID]) {
                            $query = 'SET pos = pos + 1 WHERE side = \'' . $side . '\' AND pos >= ' . $moveData[$toID] . ' AND pos <= ' . $moveData[$fromID];
                        } else {
                            $query = 'SET pos = pos - 1 WHERE side = \'' . $side . '\' AND pos >= ' . $moveData[$fromID] . ' AND pos <= ' . $moveData[$toID];
                        }
                        // .. and execute
                        $smcFunc['db_query']('', 'UPDATE {db_prefix}portamx_blocks ' . $query, array());
                        // update the fromID pos
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_blocks
							SET pos = {int:pos}
							WHERE id = {int:id}', array('id' => $fromID, 'pos' => $moveData[$toID]));
                    } elseif (!empty($_POST['edit_block'])) {
                        $id = $_POST['edit_block'];
                        $context['pmx']['function'] = 'edit';
                        $block = null;
                    } elseif (!empty($_POST['clone_block']) || !empty($_POST['move_block'])) {
                        if (!empty($_POST['clone_block'])) {
                            list($id, $side) = Pmx_StrToArray($_POST['clone_block']);
                        } else {
                            list($id, $side) = Pmx_StrToArray($_POST['move_block']);
                        }
                        // load the block for move/clone
                        $request = $smcFunc['db_query']('', '
							SELECT *
							FROM {db_prefix}portamx_blocks
							WHERE id = {int:id}', array('id' => $id));
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $smcFunc['db_free_result']($request);
                        // redirect on move/clone to articles..
                        if ($side == 'articles') {
                            redirectexit('action=' . $admMode . ';area=pmx_articles;sa=edit;id=' . $id . ';from=' . (!empty($_POST['clone_block']) ? 'clone.' : 'move.') . $_GET['sa'] . ';' . $context['session_var'] . '=' . $context['session_id']);
                        }
                        // block move
                        if (!empty($_POST['move_block'])) {
                            // update all pos >= moved id
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}portamx_blocks
								SET pos = pos - 1
								WHERE side = {string:side} AND pos >= {int:pos}', array('side' => $row['side'], 'pos' => $row['pos']));
                            // get max pos for destination panel
                            $request = $smcFunc['db_query']('', '
								SELECT MAX(pos)
								FROM {db_prefix}portamx_blocks
								WHERE side = {string:side}', array('side' => $side));
                            list($dbpos) = $smcFunc['db_fetch_row']($request);
                            $smcFunc['db_free_result']($request);
                            $block['pos'] = strval(1 + ($dbpos === null ? 0 : $dbpos));
                            $block['side'] = $side;
                            // now update the block
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}portamx_blocks
								SET pos = {int:pos}, side = {string:side}
								WHERE id = {int:id}', array('id' => $id, 'pos' => $block['pos'], 'side' => $block['side']));
                            // clear cache
                            $pmxCacheFunc['clean']();
                            $context['pmx']['function'] = 'overview';
                            if ($context['pmx']['subaction'] != 'all') {
                                $context['pmx']['subaction'] = $block['side'];
                            }
                        } else {
                            $block = array('id' => $row['id'], 'side' => $row['side'], 'pos' => $row['pos'], 'active' => $row['active'], 'cache' => $row['cache'], 'blocktype' => $row['blocktype'], 'acsgrp' => $row['acsgrp'], 'config' => $row['config'], 'content' => $row['content']);
                            $block['side'] = $side;
                            $block['active'] = 0;
                            $context['pmx']['function'] = 'editnew';
                            if ($context['pmx']['subaction'] != 'all') {
                                $context['pmx']['subaction'] = $block['side'];
                            }
                        }
                    } elseif (!empty($_POST['block_delete'])) {
                        $request = $smcFunc['db_query']('', '
							SELECT side, pos, blocktype
							FROM {db_prefix}portamx_blocks
							WHERE id = {int:id}', array('id' => $_POST['block_delete']));
                        list($side, $pos, $blocktype) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        // update all pos >= deleted id
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_blocks
							SET pos = pos - 1
							WHERE side = {string:side} AND pos >= {int:pos}', array('side' => $side, 'pos' => $pos));
                        // delete the block
                        $smcFunc['db_query']('', '
							DELETE FROM {db_prefix}portamx_blocks
							WHERE id = {int:id}', array('id' => $_POST['block_delete']));
                        // clear cache
                        $pmxCacheFunc['clean']();
                    }
                    // Post send by xml http ?
                    if (!empty($_POST['xml'])) {
                        // return result
                        ob_start();
                        echo $_POST['result'];
                        ob_end_flush();
                        exit;
                    }
                    // redirect ?
                    if ($context['pmx']['function'] == 'overview') {
                        redirectexit('action=' . $admMode . ';area=' . $pmx_area . ';sa=' . $context['pmx']['subaction'] . ';' . $context['session_var'] . '=' . $context['session_id']);
                    }
                }
                // edit block canceled ?
                if (!empty($_POST['cancel_edit'])) {
                    $context['pmx']['function'] = 'overview';
                } elseif (empty($_POST['edit_block']) && empty($_POST['add_new_block']) && ($context['pmx']['function'] == 'editnew' || $context['pmx']['function'] == 'edit')) {
                    // check defined numeric vars (check_num_vars holds the posted array to check like [varname][varname] ...)
                    if (isset($_POST['check_num_vars'])) {
                        foreach ($_POST['check_num_vars'] as $val) {
                            $data = explode(',', $val);
                            $post = '$_POST' . str_replace(array('[', ']'), array('[\'', '\']'), $data[0]);
                            if (eval("return isset({$post});") && eval("return !is_numeric({$post});")) {
                                eval("{$post} = {$data['1']};");
                            }
                        }
                    }
                    // add a change date to config array
                    $_POST['config']['created'] = time();
                    // blocktype change?
                    if (!empty($_POST['chg_blocktype'])) {
                        if (isset($_POST['content']) && PortaMx_makeSafeContent($_POST['content']) != '') {
                            // convert html/script to bbc
                            if ($_POST['blocktype'] == 'bbc_script' && in_array($_POST['contenttype'], array('html', 'script'))) {
                                $_POST['content'] = PortaMx_SmileyToBBC($_POST['content']);
                                if (preg_match_all('/<img.*(style[^\\"]*\\"([^\\"]*\\"))[^>]*>/U', $_POST['content'], $match) > 0) {
                                    foreach ($match[0] as $key => $val) {
                                        $repl = ' ' . str_replace(array('"', ': ', ':', 'px;'), array('', '="', '="', '" '), $match[2][$key]);
                                        $_POST['content'] = str_replace($val, str_replace($match[1][$key], $repl, $val), $_POST['content']);
                                    }
                                }
                                require_once $sourcedir . '/Subs-Editor.php';
                                $modSettings['smiley_enable'] = true;
                                $user_info['smiley_set'] = 'PortaMx';
                                $_POST['content'] = html_to_bbc($_POST['content']);
                            } elseif ($_POST['contenttype'] == 'bbc_script' && in_array($_POST['blocktype'], array('html', 'script'))) {
                                $_POST['content'] = PortaMx_BBCsmileys(parse_bbc(PortaMx_makeSafeContent($_POST['content'], $_POST['contenttype']), false));
                                $_POST['content'] = str_replace(array('<hr>', '<br>'), array('<hr />', '<br />'), $_POST['content']);
                                $_POST['content'] = preg_replace_callback('/<\\/[^>]*>|<[^\\/]*\\/>|<ul[^>]*>|<ol[^>]*>/', create_function('$matches', 'return $matches[0] ."\\n";'), $_POST['content']);
                                if (preg_match_all('/<img[^w]*(width=\\"([0-9]+)\\")(\\sheight=\\"([\\s0-9]+)\\")[^>]*>/', $_POST['content'], $match) > 0) {
                                    foreach ($match[0] as $key => $val) {
                                        $_POST['content'] = str_replace($match[1][$key], '', $_POST['content']);
                                        $_POST['content'] = str_replace($match[3][$key], 'style="width: ' . $match[2][$key] . 'px;height: ' . $match[4][$key] . 'px;"', $_POST['content']);
                                    }
                                    $_POST['content'] = preg_replace('/px;"[^c]*class=/', 'px;" class=', $_POST['content']);
                                }
                            } elseif ($_POST['blocktype'] == 'php') {
                                if ($_POST['contenttype'] == 'php') {
                                    pmxPHP_convert();
                                }
                            }
                        }
                        $id = $_POST['id'];
                    }
                    // save data
                    if (empty($_POST['move_block']) && (!empty($_POST['save_edit']) || !empty($_POST['save_edit_continue']) || !empty($_POST['chg_blocktype']))) {
                        if ($_POST['blocktype'] == 'php' && $_POST['contenttype'] == 'php') {
                            pmxPHP_convert();
                        } elseif ($_POST['blocktype'] == 'html') {
                            $_POST['content'] = str_replace('/ckeditor/../Smileys/', '/Smileys/', $_POST['content']);
                            if (preg_match_all('~<img.*(class[^r]*resized[^\\"]*\\")[^>]*>~', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $endChr = substr($val, -2) !== '/>' ? array('>', ' />') : array(' />', '/>');
                                    $repl = str_replace($match[1][$key], '', $val);
                                    $_POST['content'] = str_replace($val, str_replace($endChr[0], ' class="bbc_img resized"' . $endChr[1], $repl), $_POST['content']);
                                }
                            } elseif (preg_match_all('~<img[^>]*>~', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $endChr = substr($val, -2) !== '/>' ? array('>', ' />') : array(' />', '/>');
                                    if (strpos($val, '/Smileys/') === false) {
                                        $_POST['content'] = str_replace($val, str_replace($endChr[0], ' class="bbc_img resized"' . $endChr[1], $val), $_POST['content']);
                                    }
                                }
                            }
                        } elseif ($_POST['blocktype'] != 'shoutbox') {
                            $_POST['content'] = isset($_POST['content']) ? PortaMx_makeSafeContent($_POST['content'], $_POST['blocktype']) : '';
                        }
                        $block = array('id' => $_POST['id'], 'side' => $_POST['side'], 'pos' => $_POST['pos'], 'active' => $_POST['active'], 'cache' => $_POST['cache'], 'blocktype' => $_POST['blocktype'], 'acsgrp' => !empty($_POST['acsgrp']) ? implode(',', $_POST['acsgrp']) : '', 'config' => serialize($_POST['config']), 'content' => $_POST['content']);
                        $id = $_POST['id'];
                    }
                    // save block..
                    if (!empty($_POST['save_edit']) || !empty($_POST['save_edit_continue'])) {
                        // if new block get the last id
                        if ($context['pmx']['function'] == 'editnew') {
                            $request = $smcFunc['db_query']('', '
								SELECT MAX(a.id), MAX(b.pos)
								FROM {db_prefix}portamx_blocks as a
								LEFT JOIN {db_prefix}portamx_blocks as b ON(b.side = {string:side})
								GROUP BY b.side', array('side' => $block['side']));
                            list($dbid, $dbpos) = $smcFunc['db_fetch_row']($request);
                            $smcFunc['db_free_result']($request);
                            $block['id'] = strval(1 + ($dbid === null ? 0 : $dbid));
                            $block['pos'] = strval(1 + ($dbpos === null ? 0 : $dbpos));
                        }
                        // now save all data
                        $smcFunc['db_insert']('replace', '
							{db_prefix}portamx_blocks', array('id' => 'int', 'side' => 'string', 'pos' => 'int', 'active' => 'int', 'cache' => 'int', 'blocktype' => 'string', 'acsgrp' => 'string', 'config' => 'string', 'content' => 'string'), array($block['id'], $block['side'], $block['pos'], $block['active'], $block['cache'], $block['blocktype'], $block['acsgrp'], $block['config'], $block['content']), array('id'));
                        // clear cache
                        $pmxCacheFunc['clean']();
                        $postKey = 'pmxpost_' . $block['blocktype'] . $block['id'];
                        if (isset($_SESSION['PortaMx'][$postKey])) {
                            unset($_SESSION['PortaMx'][$postKey]);
                        }
                        if (isset($_SESSION['PortaMx'][$postKey . '_0'])) {
                            unset($_SESSION['PortaMx'][$postKey . '_0']);
                        }
                        $context['pmx']['function'] = 'edit';
                    }
                    // end edit ?
                    if (!empty($_POST['save_edit'])) {
                        $context['pmx']['function'] = 'overview';
                        if (!empty($block['active'])) {
                            redirectexit('action=' . $admMode . ';area=' . $pmx_area . ';sa=' . $context['pmx']['subaction'] . ';' . $context['session_var'] . '=' . $context['session_id']);
                        }
                    } elseif (!empty($_POST['save_edit_continue'])) {
                        if (!empty($block['active'])) {
                            $_SESSION['pmx_save_edit_continue'] = $block['id'];
                            redirectexit('action=' . $admMode . ';area=' . $pmx_area . ';sa=' . $context['pmx']['subaction'] . ';' . $context['session_var'] . '=' . $context['session_id']);
                        }
                    }
                }
            } else {
                $context['pmx']['subaction'] = isset($_GET['sa']) && $_GET['sa'] != 'settings' ? $_GET['sa'] : 'all';
                $context['pmx']['function'] = 'overview';
                // direct edit request?
                if (isset($_GET['edit']) && intval($_GET['edit']) != 0) {
                    $id = $_GET['edit'];
                    $context['pmx']['function'] = 'edit';
                    $block = null;
                } elseif (isset($_SESSION['pmx_save_edit_continue'])) {
                    $block = null;
                    $id = $_SESSION['pmx_save_edit_continue'];
                    unset($_SESSION['pmx_save_edit_continue']);
                    $context['pmx']['function'] = 'edit';
                }
            }
            // load template and languages, setup pagetitle
            loadTemplate($context['pmx_templatedir'] . 'AdminBlocks');
            loadLanguage($context['pmx_templatedir'] . 'AdminBlocks');
            $context['pmx']['RegBlocks'] = eval($context['pmx']['registerblocks']);
            $context['page_title'] = $txt['pmx_blocks'];
            $context['pmx']['AdminMode'] = $admMode;
            // continue edit or overview ?
            if ($context['pmx']['function'] == 'overview') {
                // load blocks data for overview
                $context['pmx']['blocks'] = array();
                $request = $smcFunc['db_query']('', '
					SELECT id, side, pos, active, cache, blocktype, acsgrp, config
					FROM {db_prefix}portamx_blocks
					WHERE side IN ({array_string:side})
					ORDER BY side, pos', array('side' => Pmx_StrToArray($context['pmx']['subaction'] == 'all' ? implode(',', array_keys($txt['pmx_admBlk_sides'])) : $context['pmx']['subaction'])));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        $context['pmx']['blocks'][$row['side']][$row['pos']] = array('id' => $row['id'], 'side' => $row['side'], 'pos' => $row['pos'], 'active' => $row['active'], 'cache' => $row['cache'], 'blocktype' => $row['blocktype'], 'acsgrp' => $row['acsgrp'], 'config' => unserialize($row['config']));
                    }
                    $smcFunc['db_free_result']($request);
                }
                // load popup js and css for overview
                loadJavascriptFile(PortaMx_loadCompressed('PortaMxPopup.js'), array('external' => true));
            } elseif (empty($_POST['save_edit'])) {
                // load the class file and create the object
                require_once $context['pmx_sysclassdir'] . 'PortaMx_AdminBlocksClass.php';
                $context['pmx']['editblock'] = PortaMx_getAdmEditBlock($id, $block, $newBlockSide);
            }
        } else {
            fatal_lang_error('pmx_acces_error', false);
        }
    }
}
/**
* Receive all the Posts from Settings Manager, check and save it.
* Finally the Admin settings are prepared and the templare loaded.
*/
function PortaMx_AdminSettings()
{
    global $boarddir, $scripturl, $smcFunc, $context, $modSettings, $txt, $pmxCacheFunc;
    $admMode = PortaMx_makeSafe($_GET['action']);
    $pmx_area = PortaMx_makeSafe($_GET['area']);
    if (($admMode == 'admin' || $admMode == 'portamx') && ($pmx_area == 'pmx_settings' || $pmx_area == 'pmx_sefengine') && allowPmx('pmx_admin')) {
        if ($admMode == 'admin') {
            // fix the linktree
            foreach ($context['linktree'] as $key => $data) {
                if (strpos($data['url'], 'pmx_settings') !== false || strpos($data['url'], 'pmx_sefengine') !== false) {
                    $context['linktree'] = array_merge(array_slice($context['linktree'], 0, $key), array(array('url' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'name' => $txt['pmx_extension'])), array_slice($context['linktree'], $key, count($context['linktree']) - $key));
                    break;
                }
            }
        }
        require_once $context['pmx_sourcedir'] . 'AdminSubs.php';
        $context['pmx']['subaction'] = isset($_GET['sa']) ? $_GET['sa'] : ($pmx_area == 'pmx_sefengine' ? '' : 'globals');
        // From template ?
        if (PortaMx_checkPOST()) {
            checkSession('post');
            $currentPanel = '';
            // check the Post array
            if (isset($_POST['save_settings']) && !empty($_POST['save_settings'])) {
                // check defined numeric vars (check_num_vars holds the posted array to check like [varname][varname] ...)
                if (isset($_POST['check_num_vars'])) {
                    foreach ($_POST['check_num_vars'] as $val) {
                        $data = explode(',', $val);
                        $post = '$_POST' . str_replace(array('[', ']'), array('[\'', '\']'), $data[0]);
                        if (eval("return isset({$post});") && eval("return !is_numeric({$post});")) {
                            eval("{$post} = {$data['1']};");
                        }
                    }
                    unset($_POST['check_num_vars']);
                }
                if (!empty($_POST['curPanel'])) {
                    $currentPanel = 'pn=' . $_POST['curPanel'] . ';';
                }
                // access update?
                if (!empty($_POST['update_access'])) {
                    $perms = array('pmx_promote' => array(), 'pmx_create' => array(), 'pmx_articles' => array(), 'pmx_blocks' => array(), 'pmx_admin' => array());
                    if (isset($_POST['setaccess'])) {
                        foreach ($_POST['setaccess'] as $acsname => $acsdata) {
                            $perms[$acsname] = $acsdata;
                        }
                    }
                    $smcFunc['db_insert']('replace', '
						{db_prefix}portamx_settings', array('varname' => 'string', 'config' => 'string'), array('permissions', serialize($perms)), array('varname'));
                    // clear settins cache
                    $pmxCacheFunc['clean']();
                } elseif (!empty($_POST['update_pmxsef'])) {
                    $arrayToken = array('pmxsef_stripchars', 'pmxsef_actions');
                    foreach ($_POST as $token => $value) {
                        if (substr($token, 0, 7) == 'pmxsef_') {
                            // check...
                            if ($token == 'pmxsef_spacechar') {
                                $_POST[$token] = !in_array(substr($_POST[$token], 0, 1), array('-', '_', '')) ? '-' : (!empty($_POST[$token]) ? substr($_POST[$token], 0, 1) : '');
                            } elseif ($token == 'pmxsef_ssefspace') {
                                $_POST[$token] = substr($_POST[$token], 0, 1);
                            } elseif ($token == 'pmxsef_aliasactions') {
                                $alias = array();
                                $tmp = Pmx_StrToArray($_POST[$token], ',');
                                foreach ($tmp as $d) {
                                    $t = Pmx_StrToArray($d, '=');
                                    if (!in_array($t[0], array('admin', 'portamx'))) {
                                        $alias[$t[1]] = $t[0];
                                    }
                                }
                                $_POST[$token] = serialize($alias);
                            } elseif ($token == 'pmxsef_ignorerequests') {
                                $alias = array();
                                $tmp = Pmx_StrToArray($_POST[$token], ',');
                                foreach ($tmp as $d) {
                                    $t = Pmx_StrToArray($d, '=');
                                    $alias[$t[0]] = $t[1];
                                }
                                $_POST[$token] = serialize($alias);
                            } elseif (in_array($token, $arrayToken)) {
                                $_POST[$token] = implode(',', Pmx_StrToArray($_POST[$token], ','));
                            }
                            if ($token != 'pmxsef_enable') {
                                $smcFunc['db_insert']('replace', '
									{db_prefix}settings', array('variable' => 'string', 'value' => 'string'), array($token, $_POST[$token]), array('variable'));
                            }
                        }
                    }
                    // alway disable SEF if no .htaccess or web.config found
                    if ((file_exists($boarddir . '/.htaccess') || file_exists($boarddir . '/web.config')) == false) {
                        $_POST['pmxsef_enable'] = '0';
                    }
                    // setup the the SMF hooks
                    $hooklist = array('integrate_pre_load' => 'pmxsef_convertSEF', 'integrate_buffer' => 'ob_pmxsef', 'integrate_redirect' => 'pmxsef_Redirect', 'integrate_outgoing_email' => 'pmxsef_EmailOutput', 'integrate_exit' => 'pmxsef_XMLOutput', 'integrate_fix_url' => 'pmxsef_fixurl');
                    // get the hooks from database
                    $smfhooks = array();
                    $request = $smcFunc['db_query']('', '
						SELECT variable, value FROM {db_prefix}settings
						WHERE variable IN ({array_string:hooks})', array('hooks' => array_keys($hooklist)));
                    if ($smcFunc['db_num_rows']($request) > 0) {
                        while ($row = $smcFunc['db_fetch_assoc']($request)) {
                            $smfhooks[$row['variable']] = $row['value'];
                        }
                        $smcFunc['db_free_result']($request);
                    }
                    // update the hooks
                    foreach ($hooklist as $hookname => $value) {
                        if (isset($smfhooks[$hookname])) {
                            $smfhooks[$hookname] = trim((!empty($_POST['pmxsef_enable']) ? $value . ',' : '') . trim(str_replace($value, '', $smfhooks[$hookname]), ','), ',');
                        } else {
                            $smfhooks[$hookname] = trim(!empty($_POST['pmxsef_enable']) ? $value : '');
                        }
                        $smcFunc['db_insert']('replace', '
							{db_prefix}settings', array('variable' => 'string', 'value' => 'string'), array($hookname, $smfhooks[$hookname]), array('variable'));
                    }
                    if (!empty($_POST['pmxsef_enable'])) {
                        $oldState = intval(!empty($modSettings['queryless_urls']));
                        updateSettings(array('queryless_urls' => '0'));
                        $smcFunc['db_insert']('replace', '
								{db_prefix}settings', array('variable' => 'string', 'value' => 'string'), array('oldstate_queryless_urls', $oldState), array('variable'));
                    } else {
                        if (isset($modSettings['oldstate_queryless_urls'])) {
                            updateSettings(array('queryless_urls' => $modSettings['oldstate_queryless_urls']));
                        }
                    }
                    // clear cache
                    $pmxCacheFunc['clean']();
                } else {
                    $config = array();
                    $request = $smcFunc['db_query']('', '
							SELECT config
							FROM {db_prefix}portamx_settings
							WHERE varname = {string:settings}', array('settings' => 'settings'));
                    if ($smcFunc['db_num_rows']($request) > 0) {
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $smcFunc['db_free_result']($request);
                        $config = unserialize($row['config']);
                    }
                    $setKeys = array_diff(array_keys($_POST), array('pmx_fronttheme', 'pmx_frontthempg', 'pmx_ecl', 'pmx_eclmodal', 'pmx_eclmodalmobi', 'pmx_eclmodaltop', 'pmx_eclmodalaction', 'save_settings', 'sa', 'sc'));
                    foreach ($setKeys as $key) {
                        if ($key == 'promotes') {
                            $promo = Pmx_StrToIntArray($_POST[$key]);
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}portamx_settings
									SET config = {string:config}
									WHERE varname = {string:settings}', array('config' => serialize($promo), 'settings' => 'promotes'));
                            // find all promoted block
                            $blocks = null;
                            $request = $smcFunc['db_query']('', '
								SELECT id
								FROM {db_prefix}portamx_blocks
								WHERE active = 1 AND blocktype = {string:blocktype}', array('blocktype' => 'promotedposts'));
                            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                                $blocks[] = $row['id'];
                            }
                            $smcFunc['db_free_result']($request);
                            $_SESSION['pmx_refresh_promote'] = $blocks;
                        } else {
                            if ($key == 'dl_access') {
                                $_POST['dl_access'] = implode(',', $_POST['dl_access']);
                            }
                            $config[$key] = $_POST[$key];
                        }
                    }
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}portamx_settings
							SET config = {string:config}
							WHERE varname = {string:settings}', array('config' => serialize($config), 'settings' => 'settings'));
                    // other settings they stored in smf_settings table
                    $setKeys = array('pmx_fronttheme', 'pmx_frontthempg', 'pmx_ecl', 'pmx_eclmodal', 'pmx_eclmodalmobi', 'pmx_eclmodaltop', 'pmx_eclmodalaction', 'pmx_quickreply');
                    foreach ($setKeys as $key) {
                        if (isset($_POST[$key])) {
                            $smcFunc['db_insert']('replace', '
								{db_prefix}settings', array('variable' => 'string', 'value' => 'string'), array($key, $_POST[$key]), array('variable'));
                        }
                    }
                    // set frontmode flag
                    $smcFunc['db_insert']('replace', '
						{db_prefix}settings', array('variable' => 'string', 'value' => 'string'), array('pmx_frontmode', $config['frontpage'] == 'none' ? '0' : '1'), array('variable'));
                    if (isset($_POST['pmx_ecl'])) {
                        pmx_setcookie('pmx_eclauth', '');
                        if (!empty($_POST['pmx_ecl'])) {
                            pmx_setECL_Cookie(true);
                        }
                    }
                    // clear cached values
                    $pmxCacheFunc['clean']();
                }
            }
            redirectexit('action=' . $admMode . ';area=' . $pmx_area . (!empty($context['pmx']['subaction']) ? ';sa=' . $context['pmx']['subaction'] : '') . ';' . $currentPanel . $context['session_var'] . '=' . $context['session_id']);
        }
        // SEF engine settings ?
        if ($pmx_area == 'pmx_sefengine') {
            // pmxsef default settings
            $context['pmx']['pmxsef_enable'] = '0';
            $context['pmx']['pmxsef_lowercase'] = '1';
            $context['pmx']['pmxsef_autosave'] = '0';
            $context['pmx']['pmxsef_spacechar'] = '-';
            $context['pmx']['pmxsef_ssefspace'] = '';
            $context['pmx']['pmxsef_stripchars'] = '&quot;,&amp;,&lt;,&gt;,~,!,@,#,$,%,^,&,*,(,),-,=,+,<,[,{,],},>,;,:,\',",/,?,\\,|';
            $context['pmx']['pmxsef_singletoken'] = 'add,advanced,all,asc,calendar,check,children,conversation,desc,home,kstart,nw,profile,save,sound,togglebar,topicseen,view,viewweek,xml';
            $context['pmx']['pmxsef_actions'] = 'about:mozilla,about:unknown,activate,admin,announce,attachapprove,buddy,calendar,clock,collapse,community,coppa,credits,deletemsg,display,dlattach,editpoll,editpoll2,emailuser,findmember,groups,help,helpadmin,im,jseditor,jsmodify,jsoption,keepalive,lock,lockvoting,login,login2,logout,markasread,mergetopics,mlist,moderate,modifycat,modifykarma,movetopic,movetopic2,notify,notifyboard,openidreturn,pm,portamx,post,post2,printpage,profile,promote,quotefast,quickmod,quickmod2,recent,register,register2,reminder,removepoll,removetopic2,reporttm,requestmembers,restoretopic,search,search2,sendtopic,smstats,suggest,spellcheck,splittopics,stats,sticky,trackip,unread,unreadreplies,verificationcode,viewprofile,vote,viewquery,viewsmfile,who,.xml,xmlhttp';
            $context['pmx']['pmxsef_ignoreactions'] = '';
            $context['pmx']['pmxsef_aliasactions'] = '';
            $context['pmx']['pmxsef_ignorerequests'] = '';
            $context['pmx']['pmxsef_codepages'] = '/PortaMx/sefcodepages/x';
            $nocheck = array('pmxsef_enable', 'pmxsef_lowercase', 'pmxsef_spacechar');
            // read the settings from database
            $request = $smcFunc['db_query']('', '
				SELECT variable, value FROM {db_prefix}settings
				WHERE variable LIKE {string:variable}', array('variable' => 'pmxsef_%'));
            if ($smcFunc['db_num_rows']($request) > 0) {
                while ($row = $smcFunc['db_fetch_assoc']($request)) {
                    $value = trim($row['value']);
                    if ($row['variable'] == 'pmxsef_aliasactions') {
                        $tmp = unserialize($value);
                        if (!empty($tmp)) {
                            foreach ($tmp as $act => $alias) {
                                $context['pmx'][$row['variable']][] = $alias . '=' . $act;
                            }
                            $context['pmx'][$row['variable']] = implode(',', $context['pmx'][$row['variable']]);
                        }
                    } elseif ($row['variable'] == 'pmxsef_ignorerequests') {
                        $tmp = unserialize($value);
                        if (!empty($tmp)) {
                            foreach ($tmp as $act => $alias) {
                                $context['pmx'][$row['variable']][] = $act . '=' . $alias;
                            }
                            $context['pmx'][$row['variable']] = implode(',', $context['pmx'][$row['variable']]);
                        }
                    } elseif (in_array($row['variable'], $nocheck) || !empty($value)) {
                        $context['pmx'][$row['variable']] = $value;
                    }
                }
                $smcFunc['db_free_result']($request);
            }
            // check if enabled
            $request = $smcFunc['db_query']('', '
				SELECT value FROM {db_prefix}settings
				WHERE variable = {string:hook}', array('hook' => 'integrate_pre_load'));
            if ($smcFunc['db_num_rows']($request) > 0) {
                $row = $smcFunc['db_fetch_assoc']($request);
                $smcFunc['db_free_result']($request);
                if (strpos($row['value'], 'pmxsef_convertSEF') !== false) {
                    $context['pmx']['pmxsef_enable'] = '1';
                }
            }
        } else {
            $context['pmx']['admthemes'] = PortaMx_getsmfThemes();
            $context['pmx']['admgroups'] = PortaMx_getUserGroups(true);
            $context['pmx']['limitgroups'] = PortaMx_getUserGroups(true, false);
            $context['pmx']['acsgroups'] = PortaMx_getUserGroups(false, !empty($context['pmx']['settings']['postcountacs']));
            $context['pmx']['sysstat'] = $pmxCacheFunc['stat']();
            $request = $smcFunc['db_query']('', '
				SELECT variable, value FROM {db_prefix}settings
				WHERE variable IN ({array_string:vars})', array('vars' => array('pmx_fronttheme', 'pmx_frontthempg', 'pmx_ecl', 'pmx_eclmodal', 'pmx_eclmodalmobi', 'pmx_eclmodaltop', 'pmx_eclmodalaction')));
            if ($smcFunc['db_num_rows']($request) > 0) {
                while ($row = $smcFunc['db_fetch_assoc']($request)) {
                    $context['pmx'][$row['variable']] = $row['value'];
                }
                $smcFunc['db_free_result']($request);
            }
        }
        // setup pagetitle
        $context['page_title'] = $txt['pmx_settings'];
        $context['pmx']['AdminMode'] = $admMode;
        // load language and execute template
        loadLanguage($context['pmx_templatedir'] . 'AdminSettings');
        loadTemplate($context['pmx_templatedir'] . 'AdminSettings');
    } else {
        fatal_error($txt['pmx_acces_error']);
    }
}