/**
     * InitContent.
     */
    function pmxc_InitContent()
    {
        global $user_info, $modSettings, $txt;
        if ($this->visible) {
            // show current time as realtime?
            if (!empty($this->cfg['config']['settings']['show_time']) && !empty($this->cfg['config']['settings']['show_realtime'])) {
                $cdate = date('Y,n-1,j,G,', Forum_Time()) . intval(date('i', Forum_Time())) . ',' . intval(date('s', Forum_Time()));
                if (empty($modSettings['pmxUserLoginLoaded'])) {
                    addInlineJavascript('
	var pmx_rtcFormat = {};');
                }
                if (empty($this->cfg['config']['settings']['rtc_format'])) {
                    addInlineJavascript('
	pmx_rtcFormat[' . $this->cfg['id'] . '] = "' . (empty($user_info['time_format']) ? $modSettings['time_format'] : $user_info['time_format']) . '";');
                } else {
                    addInlineJavascript('
	pmx_rtcFormat[' . $this->cfg['id'] . '] = "' . $this->cfg['config']['settings']['rtc_format'] . '";');
                }
                if (empty($modSettings['pmxUserLoginLoaded'])) {
                    addInlineJavascript('
	var pmx_rctMonths = new Array("' . implode('","', $txt['months']) . '");
	var pmx_rctShortMonths = new Array("' . implode('","', $txt['months_short']) . '");
	var pmx_rctDays = new Array("' . implode('","', $txt['days']) . '");
	var pmx_rctShortDays = new Array("' . implode('","', $txt['days_short']) . '");
	var pmx_rtcFormatTypes = new Array("%a", "%A", "%d", "%b", "%B", "%m", "%Y", "%y", "%H", "%I", "%M", "%S", "%p", "%%", "%D", "%e", "%R", "%T");
	var pmx_rtcOffset = new Date(' . $cdate . ') - new Date();');
                    loadJavascriptFile(PortaMx_loadCompressed('PortaMxUser.js'), array('external' => true));
                    $modSettings['pmxUserLoginLoaded'] = true;
                }
            }
        }
        // return the visibility flag (true/false)
        return $this->visible;
    }
/**
* System none modal ECL init
*/
function pmx_eclnonemodal()
{
    global $context, $settings, $modSettings, $maintenance, $scripturl, $options, $txt;
    if (!empty($modSettings['pmx_eclmodal']) && !pmx_checkECL_Cookie()) {
        if (!empty($modSettings['pmxportal_disabled'])) {
            loadJavascriptFile(PortaMx_loadCompressed('PortaMx.js', array('dir' => $settings['default_theme_dir'] . '/PortaMx/Scripts/', 'url' => $settings['default_theme_url'] . '/PortaMx/Scripts/')), array('external' => true));
            addInlineJavascript('
	var pmxIsInit = true;');
            loadLanguage('PortaMx/PortaMx');
        }
        addInlineJavascript('
	var eclOverlay = true;
	function Setlang(elm){window.location.href = elm.options[elm.selectedIndex].value;}');
        loadCSSFile(PortaMx_loadCompressed('pmx_ecl.css', array('dir' => $settings['default_theme_dir'] . '/PortaMx/SysCss/', 'url' => $settings['default_theme_url'] . '/PortaMx/SysCss/')), array('external' => true));
        loadtemplate('PortaMx/EclMain');
        $context['template_layers'][] = 'eclmain';
    }
}
    /**
     * InitContent.
     */
    function pmxc_InitContent()
    {
        global $context, $user_info, $modSettings, $pmxCacheFunc;
        // if visible init the content
        if ($this->visible) {
            $cbtopic = isset($_GET['topic']) ? $_GET['topic'] : 0;
            if ($this->cfg['cache'] > 0) {
                // check the block cache
                if (($cachedata = $pmxCacheFunc['get']($this->cache_key, $this->cache_mode)) !== null) {
                    list($this->topics, $isRead, $this->boards, $this->cat_board) = $cachedata;
                    if (isset($isRead[$user_info['id']]) && array_key_exists($cbtopic, $isRead[$user_info['id']]) && empty($isRead[$user_info['id']][$cbtopic])) {
                        $isRead[$user_info['id']][$cbtopic] = 1;
                        $cachedata = array($this->topics, $isRead, $this->boards, $this->cat_board);
                        $pmxCacheFunc['put']($this->cache_key, $cachedata, $this->cache_time, $this->cache_mode);
                    }
                } else {
                    $cachedata = $this->cbt_fetchdata();
                    $pmxCacheFunc['put']($this->cache_key, $cachedata, $this->cache_time, $this->cache_mode);
                    list($this->topics, $isRead, $this->boards, $this->cat_board) = $cachedata;
                }
            } else {
                $cachedata = $this->cbt_fetchdata();
                list($this->topics, $isRead, $this->boards, $this->cat_board) = $cachedata;
            }
            unset($cachedata);
            $this->isRead = isset($isRead[$user_info['id']]) ? $isRead[$user_info['id']] : null;
            // no boards .. disable the block
            if (!empty($this->boards)) {
                if (empty($modSettings['pmxCBTNavLoaded'])) {
                    addInlineJavascript('
	var pmxCBTimages = new Array("' . $context['pmx_imageurl'] . 'minus.png", "' . $context['pmx_imageurl'] . 'plus.png");
	var pmxCBTallBoards = {};');
                    loadJavascriptFile(PortaMx_loadCompressed('PortaMxCBTNav.js'), array('external' => true));
                    $modSettings['pmxCBTNavLoaded'] = true;
                }
                addInlineJavascript('
	pmxCBTallBoards[' . $this->cfg['id'] . '] = new Array("' . implode('", "', $this->boards) . '");');
            } else {
                $this->visible = false;
            }
        }
        // return the visibility flag (true/false)
        return $this->visible;
    }
 /**
  * InitContent.
  * Checks the cache status and create the content.
  */
 function pmxc_InitContent()
 {
     global $pmxCacheFunc, $modSettings;
     // if visible init the content
     if ($this->visible) {
         if ($this->cfg['cache'] > 0) {
             // check the block cache
             if (($this->faderdata = $pmxCacheFunc['get']($this->cache_key, $this->cache_mode)) === null) {
                 $this->getFaderData();
                 $pmxCacheFunc['put']($this->cache_key, $this->faderdata, $this->cache_time, $this->cache_mode);
             }
         } else {
             $this->getFaderData();
         }
         if (empty($modSettings['pmxFaderLoaded'])) {
             loadJavascriptFile(PortaMx_loadCompressed('PortaMxFader.js'), array('external' => true));
             $modSettings['pmxFaderLoaded'] = true;
         }
     }
     // return the visibility flag (true/false)
     return $this->visible;
 }
/**
* 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']);
        }
    }
}
/**
* 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();
}
/**
* 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']);
    }
}
    /**
     * InitContent.
     * Get the poll data and load the header.
     */
    function pmxc_InitContent()
    {
        global $context, $smcFunc, $user_info, $txt, $pmxCacheFunc;
        if ($this->visible) {
            $this->pmxc_checkCacheStatus();
            // call the cache trigger
            if (!empty($this->cfg['config']['settings']['polls'])) {
                if (isset($_POST['pollchanged' . $this->cfg['id']])) {
                    if ($this->cfg['cache'] > 0) {
                        $pmxCacheFunc['clear']($this->cache_key, $this->cache_mode);
                    }
                }
            } else {
                $this->visible = false;
            }
        }
        // member can see polls?
        $this->boardsAllowed = boardsAllowedTo('poll_view');
        if (empty($this->boardsAllowed) || empty($this->visible)) {
            $this->visible = false;
            return $this->visible;
        }
        // check the block cache
        if (($cachedata = $pmxCacheFunc['get']($this->cache_key, $this->cache_mode)) !== null) {
            if (!isset($cachedata[$user_info['id']])) {
                $this->Create_polldata();
                if ($this->visible) {
                    $cachedata[$user_info['id']] = array($this->polldata, $this->currentpoll, $this->polls, $this->pollquestions);
                    $pmxCacheFunc['put']($this->cache_key, $cachedata, $this->cache_time, $this->cache_mode);
                }
            } else {
                list($this->polldata, $this->currentpoll, $this->polls, $this->pollquestions) = $cachedata[$user_info['id']];
            }
        }
        if ($cachedata === null) {
            // get content data
            $this->Create_polldata();
            if ($this->visible) {
                // cache the block if enabled
                if ($this->cfg['cache'] > 0) {
                    $cachedata[$user_info['id']] = array($this->polldata, $this->currentpoll, $this->polls, $this->pollquestions);
                    $pmxCacheFunc['put']($this->cache_key, $cachedata, $this->cache_time, $this->cache_mode);
                    unset($cachedata);
                }
            }
        }
        if ($this->visible) {
            // get users pollchoices
            $this->PollChoices = array();
            $request = $smcFunc['db_query']('', '
					SELECT id_poll, id_choice
					FROM {db_prefix}log_polls
					WHERE id_poll IN ({array_int:polls}) AND id_member = {int:idmem}', array('polls' => $this->cfg['config']['settings']['polls'], 'idmem' => $user_info['id']));
            if ($smcFunc['db_num_rows']($request) > 0) {
                while ($row = $smcFunc['db_fetch_assoc']($request)) {
                    if (isset($this->PollChoices[$row['id_poll']])) {
                        $this->PollChoices[$row['id_poll']] .= $row['id_choice'] . ',';
                    } else {
                        $this->PollChoices[$row['id_poll']] = $row['id_choice'] . ',';
                    }
                }
                $smcFunc['db_free_result']($request);
            }
            foreach ($this->PollChoices as $key => $val) {
                $this->PollChoices[$key] = explode(',', trim($val, ','));
            }
            // load javascript to header
            if (strpos($context['html_headers'], 'pmx_VotePoll') === false) {
                PortaMx_loadCompressed('
			function pmx_VotePoll(id, elm)
			{
				// check if any option selected
				var isVoted = false;
				var elmName = "pmx_pollopt" + id + "_";
				var i = 0;
				while(document.getElementById(elmName + i))
				{
					isVoted = (document.getElementById(document.getElementById(elmName + i).htmlFor).checked == true ? true : isVoted);
					i++;
				}
				if(isVoted)
				{
					pmxWinGetTop(\'poll\'+ id);
					document.getElementById("pmx_voteform" + id).submit();
				}
				else
					alert("' . $txt['pmx_poll_novote_opt'] . '");
			}
			function pmx_ShowPollResult(id, poll)
			{
				document.getElementById("pxm_allowvotepoll" + id).style.display = "none";
				document.getElementById("pxm_allowviewpoll" + id).style.display = "";
				pmx_SavePolldata(id, poll, 1);
				return false;
			}
			function pmx_ShowPollVote(id, poll)
			{
				document.getElementById("pxm_allowviewpoll" + id).style.display = "none";
				document.getElementById("pxm_allowvotepoll" + id).style.display = "";
				pmx_SavePolldata(id, poll, 0);
				return false;
			}
			function pmx_ChangePollVote(id, elm)
			{
				pmxWinGetTop(\'poll\'+ id);
				document.getElementById("pmx_voteform" + id).submit();
			}
			function pmx_ChangeCurrentPoll(id, elm)
			{
				var idx = elm.selectedIndex;
				var pollid = elm.options[idx].value;
				pmx_SavePolldata(id, pollid, 0);
				document.getElementById("pollchanged" + id).value = pollid;
				pmxWinGetTop(\'poll\'+ id);
				document.getElementById("pmx_votechange" + id).submit();
			}
			function pmx_SavePolldata(id, poll, state)
			{
				pmx_setCookie("poll" + id, poll + "," + state, "Poll");
			}', array(), true);
            }
        }
        // return the visibility flag (true/false)
        return $this->visible;
    }
    /**
     * Shout setup variables
     */
    function pmxc_ShoutSetup()
    {
        global $context, $modSettings, $txt;
        // check if member can shout
        if (isset($this->cfg['config']['settings']['shout_acs'])) {
            $this->canShout = allowPmxGroup(implode(',', $this->cfg['config']['settings']['shout_acs']));
        } else {
            $this->canShout = false;
        }
        // disable shout if a user banned
        foreach (array('cannot_access', 'cannot_login', 'cannot_post') as $bannmode) {
            $this->canShout = isset($_SESSION['ban'][$bannmode]) ? false : $this->canShout;
        }
        // we CAN shout ...
        if ($this->canShout) {
            if (empty($modSettings['pmxShoutBoxLoaded'])) {
                addInlineJavascript('
	var pmx_shoutbox_confirm = "' . $txt['pmx_shoutbox_shoutconfirm'] . '";
	var pmx_shoutbox_send_title = "' . $txt['pmx_shoutbox_send_title'] . '";
	var pmx_shoutbox_button = "' . $txt['pmx_shoutbox_button'] . '";
	var pmx_shoutbox_button_title = "' . $txt['pmx_shoutbox_button_title'] . '";
	var pmx_shoutbox_button_open = "' . $txt['pmx_shoutbox_button_open'] . '";
	var pmx_shoutbox_admimg = new Array("' . $context['pmx_imageurl'] . 'shout_admon.gif", "' . $context['pmx_imageurl'] . 'shout_admoff.gif");');
                loadJavascriptFile(PortaMx_loadCompressed('PortaMxShouts.js'), array('external' => true));
                $modSettings['pmxShoutBoxLoaded'] = true;
            }
        }
        // setup bb codes
        $this->bb_code = array(array('code' => 'b', 'image' => $context['pmx_imageurl'] . 'shoutbbc_b.gif', 'title' => $txt['pmx_shoutbbc_b']), array('code' => 'i', 'image' => $context['pmx_imageurl'] . 'shoutbbc_i.gif', 'title' => $txt['pmx_shoutbbc_i']), array('code' => 'u', 'image' => $context['pmx_imageurl'] . 'shoutbbc_u.gif', 'title' => $txt['pmx_shoutbbc_u']), array('code' => 'center', 'image' => $context['pmx_imageurl'] . 'shoutbbc_center.gif', 'title' => $txt['pmx_shoutbbc_center']), array('code' => 'hr', 'image' => $context['pmx_imageurl'] . 'shoutbbc_hr.gif', 'title' => $txt['pmx_shoutbbc_hr']), array('code' => 'sub', 'image' => $context['pmx_imageurl'] . 'shoutbbc_sub.gif', 'title' => $txt['pmx_shoutbbc_sub']), array('code' => 'sup', 'image' => $context['pmx_imageurl'] . 'shoutbbc_sup.gif', 'title' => $txt['pmx_shoutbbc_sup']));
        foreach ($this->bb_code as $data) {
            $this->legalcodes[] = $data['code'];
        }
        // setup bbc colors codes
        $this->bb_colors = array($txt['pmx_shoutbbc_changecolor'] => $txt['pmx_shoutbbc_changecolor'], $txt['pmx_shoutbbc_colorBlack'] => '#000000', $txt['pmx_shoutbbc_colorRed'] => '#ff0000', $txt['pmx_shoutbbc_colorYellow'] => '#ffff00', $txt['pmx_shoutbbc_colorPink'] => '#ff00ff', $txt['pmx_shoutbbc_colorGreen'] => '#008000', $txt['pmx_shoutbbc_colorOrange'] => '#FFA500', $txt['pmx_shoutbbc_colorPurple'] => '#800080', $txt['pmx_shoutbbc_colorBlue'] => '#0000ff', $txt['pmx_shoutbbc_colorBeige'] => '#F5F5DC', $txt['pmx_shoutbbc_colorBrown'] => '#A52A2A', $txt['pmx_shoutbbc_colorTeal'] => '#008080', $txt['pmx_shoutbbc_colorNavy'] => '#000080', $txt['pmx_shoutbbc_colorMaroon'] => '#800000', $txt['pmx_shoutbbc_colorLimeGreen'] => '#00ff00', $txt['pmx_shoutbbc_colorWhite'] => '#ffffff');
        // setup the PortaMx smileys
        $codes = array('(:1)', '(:2)', '(:3)', '(:4)', '(:5)', '(:6)', '(:7)', '(:8)', '(:9)', '(:0)', '(;1)', '(;2)', '(;3)', '(;4)', '(;5)', '(;6)', '(;7)', '(;8)', '(;9)', '(;0)');
        $files = array('smiley', 'wink', 'cheesy', 'grin', 'angry', 'sad', 'shocked', 'cool', 'huh', 'rolleyes', 'tongue', 'embarrassed', 'lipsrsealed', 'undecided', 'kiss', 'cry', 'evil', 'azn', 'afro', 'laugh');
        $smPath = $modSettings['smileys_url'] . '/PortaMx/';
        foreach ($codes as $i => $code) {
            $this->smileys[] = array('code' => $code, 'image' => $smPath . $files[$i] . '.gif', 'title' => ucfirst($files[$i]));
        }
    }
/**
* 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);
        }
    }
}