/**
     * InitContent.
     * Checks the autocache and create the content if necessary.
     */
    function pmxc_InitContent()
    {
        global $smcFunc, $context, $user_info, $scripturl, $txt;
        if ($this->visible) {
            $this->download_content = parse_bbc($this->cfg['content']);
            if (isset($this->cfg['config']['settings']['download_board']) && !empty($this->cfg['config']['settings']['download_board'])) {
                // get downloads for board
                $request = $smcFunc['db_query']('', '
						SELECT a.id_attach, a.size, a.downloads, t.id_topic, t.locked, m.subject, m.body
						FROM {db_prefix}attachments a
						LEFT JOIN {db_prefix}messages m ON (a.id_msg = m.id_msg)
						LEFT JOIN {db_prefix}topics t ON (m.id_topic = t.id_topic)
						WHERE m.id_board = {int:board} AND a.mime_type NOT LIKE {string:likestr} AND t.locked = 0', array('board' => $this->cfg['config']['settings']['download_board'], 'likestr' => 'IMAGE%'));
                $dlacs = implode('=1,', $this->cfg['config']['settings']['download_acs']);
                $entrys = $smcFunc['db_num_rows']($request);
                if ($entrys > 0) {
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        $this->download_content .= '
						<div style="text-align:left;">';
                        if (allowPmxGroup($dlacs)) {
                            $this->download_content .= '
							<a href="' . $scripturl . '?action=dlattach;id=' . $row['id_attach'] . ';fld=' . $this->cfg['id'] . '">
								<img style="vertical-align:middle;" src="' . $context['pmx_imageurl'] . 'download.png" alt="*" title="' . (empty($row['file_order']) ? $row['subject'] : substr($row['subject'], 4)) . '" /></a>';
                        }
                        if ($user_info['is_admin']) {
                            $this->download_content .= '
							<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '">
								<strong>' . (empty($row['file_order']) ? $row['subject'] : substr($row['subject'], 4)) . '</strong>
							</a>';
                        } else {
                            $this->download_content .= '
							<strong>' . (empty($row['file_order']) ? $row['subject'] : substr($row['subject'], 4)) . '</strong>';
                        }
                        $this->download_content .= '
							<div class="dlcomment">' . parse_bbc(trim($row['body'])) . '</div>
							<b>[' . round($row['size'] / 1000, 3) . '</b> ' . $txt['pmx_kb_downloads'] . '<b>' . $row['downloads'] . '</b>]
						</div>' . ($entrys > 1 ? '<hr class="pmx_hr" />' : '');
                        $entrys--;
                    }
                    $smcFunc['db_free_result']($request);
                } else {
                    $this->download_content .= '<br />' . $txt['pmx_download_empty'];
                }
            } else {
                $this->download_content .= '<br />' . $txt['pmx_download_empty'];
            }
        }
        // return the visibility flag (true/false)
        return $this->visible;
    }
    /**
     * AdmBlock_init().
     * Setup caching and get the articles.
     */
    function pmxc_AdmBlock_init()
    {
        global $smcFunc;
        $this->can_cached = 1;
        // enable caching
        $this->articles = array();
        // get all active and approved articles
        $request = $smcFunc['db_query']('', '
			SELECT a.id, a.name, a.acsgrp, a.ctype, a.config, a.owner, a.active, a.created, a.updated, a.content, m.member_name
			FROM {db_prefix}portamx_articles AS a
			LEFT JOIN {db_prefix}members AS m ON (a.owner = m.id_member)
			WHERE a.active > 0 AND a.approved > 0
			ORDER BY a.id', array());
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $row['config'] = unserialize($row['config']);
                if (!empty($this->cfg['config']['settings']['inherit_acs']) || allowPmxGroup($row['acsgrp'])) {
                    $row['side'] = $this->cfg['side'];
                    $this->articles[] = $row;
                }
            }
            $smcFunc['db_free_result']($request);
        }
    }
/**
* Receive all the posts from the articles manager, check it, then save it.
* Finally the articles are prepared and the template loaded.
*/
function PortaMx_AdminArticles()
{
    global $smcFunc, $pmxCacheFunc, $context, $sourcedir, $scripturl, $modSettings, $user_info, $txt;
    $admMode = isset($_GET['action']) ? $_GET['action'] : '';
    // fix the linktree
    if ($admMode == 'admin') {
        foreach ($context['linktree'] as $key => $data) {
            if (strpos($data['url'], 'pmx_articles') !== false) {
                $context['linktree'] = array_merge(array_slice($context['linktree'], 0, $key), array(array('url' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'name' => $txt['pmx_extension'])), array_slice($context['linktree'], $key, count($context['linktree']) - $key));
                break;
            }
        }
    }
    if (($admMode == 'admin' || $admMode == 'portamx') && isset($_GET['area']) && $_GET['area'] == 'pmx_articles') {
        if (allowPmx('pmx_admin, pmx_articles, pmx_create')) {
            require_once $context['pmx_sourcedir'] . 'AdminSubs.php';
            $context['pmx']['subaction'] = !empty($_POST['sa']) ? $_POST['sa'] : 'overview';
            // From template ?
            if (PortaMx_checkPOST()) {
                // Make sure we have a valid session...
                checkSession('post');
                // get current pageindex
                if (isset($_POST['articlestart'])) {
                    $context['pmx']['articlestart'] = $_POST['articlestart'];
                }
                // actions from overview?
                if ($context['pmx']['subaction'] == 'overview' && empty($_POST['cancel_overview'])) {
                    // from xml on overview?
                    if (isset($_POST['xml'])) {
                        $xmlResult = '';
                    }
                    // filter set ?
                    if (isset($_POST['filter'])) {
                        $_SESSION['PortaMx']['filter'] = $_POST['filter'];
                    }
                    // Row pos updates from overview?
                    if (!empty($_POST['upd_rowpos'])) {
                        list($fromID, $place, $idto) = Pmx_StrToArray($_POST['upd_rowpos']);
                        $request = $smcFunc['db_query']('', '
							SELECT id
							FROM {db_prefix}portamx_articles
							WHERE id ' . ($place == 'before' ? '<' : '>') . ' {int:id}
							LIMIT 1', array('id' => $idto));
                        list($toID) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        $toID = is_null($toID) ? $place == 'before' ? -1 : 0 : $toID;
                        $request = $smcFunc['db_query']('', '
							SELECT MAX(id) +1
							FROM {db_prefix}portamx_articles', array());
                        list($maxID) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        // create the query...
                        if ($toID == -1) {
                            // move from to first
                            $query = array('SET id = 0 WHERE id = ' . $fromID, 'SET id = id + 1 WHERE id >= 1 AND id <= ' . $fromID, 'SET id = 1 WHERE id = 0');
                        } elseif ($toID == 0) {
                            // move from to end
                            $query = array('SET id = ' . $maxID . ' WHERE id = ' . $fromID, 'SET id = id - 1 WHERE id >= ' . $fromID);
                        } elseif ($toID > $fromID) {
                            // to > from - move to after from
                            $query = array('SET id = id + 1 WHERE id >= ' . $toID, 'SET id = ' . $toID . ' WHERE id = ' . $fromID, 'SET id = id - 1 WHERE id >= ' . $fromID);
                        } else {
                            // to < from - move to before from
                            $query = array('SET id = 0 WHERE id = ' . $fromID, 'SET id = id + 1 WHERE id >= ' . $toID . ' AND id <= ' . $fromID, 'SET id = ' . $toID . ' WHERE id = 0');
                        }
                        // execute
                        foreach ($query as $qdata) {
                            $smcFunc['db_query']('', 'UPDATE {db_prefix}portamx_articles ' . $qdata, array());
                        }
                    }
                    // updates from overview popups ?
                    if (!empty($_POST['upd_overview'])) {
                        $updates = array();
                        foreach ($_POST['upd_overview'] as $updkey => $updvalues) {
                            foreach ($updvalues as $id => $values) {
                                if ($updkey == 'title') {
                                    foreach ($values as $key => $val) {
                                        if ($key == 'lang') {
                                            foreach ($val as $langname => $langvalue) {
                                                $updates[$id]['config'][$updkey][$langname] = $langvalue;
                                            }
                                        } else {
                                            $updates[$id]['config'][$updkey . '_' . $key] = $val;
                                        }
                                    }
                                } else {
                                    $updates[$id][$updkey] = $values;
                                }
                            }
                        }
                        // save all updates
                        $idList = array();
                        $catList = array();
                        foreach ($updates as $id => $values) {
                            $idList[] = $id;
                            foreach ($values as $rowname => $data) {
                                $request = $smcFunc['db_query']('', '
									SELECT config, catid, acsgrp
									FROM {db_prefix}portamx_articles
									WHERE id = {int:id}', array('id' => $id));
                                $row = $smcFunc['db_fetch_assoc']($request);
                                $smcFunc['db_free_result']($request);
                                $catList[] = $row['catid'];
                                // update config
                                if ($rowname == 'config') {
                                    $cfg = unserialize($row['config']);
                                    foreach ($data as $ckey => $cval) {
                                        if ($ckey == 'title') {
                                            foreach ($cval as $lang => $val) {
                                                $cfg[$ckey][$lang] = $val;
                                            }
                                        } else {
                                            $cfg[$ckey] = $cval;
                                        }
                                    }
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_articles
										SET config = {string:config}
										WHERE id = {int:id}', array('id' => $id, 'config' => serialize($cfg)));
                                } elseif ($rowname == 'category') {
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_articles
										SET catid = {int:val}
										WHERE id = {int:id}', array('id' => $id, 'val' => $data));
                                } else {
                                    $mode = substr($rowname, 0, 3);
                                    // update (replace)
                                    if ($mode == 'upd') {
                                        $newacs = explode(',', $data);
                                    } elseif ($mode == 'add') {
                                        $newacs = array_unique(array_merge(explode(',', $row['acsgrp']), explode(',', $data)));
                                    } else {
                                        $newacs = array_unique(array_diff(explode(',', $row['acsgrp']), explode(',', $data)));
                                    }
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_articles
										SET acsgrp = {string:val}
										WHERE id = {int:id}', array('id' => $id, 'val' => implode(',', $newacs)));
                                    // send by xml?
                                    if (isset($_POST['xml'])) {
                                        $request = $smcFunc['db_query']('', '
											SELECT active
											FROM {db_prefix}portamx_articles
											WHERE id = {int:id}', array('id' => $id));
                                        list($active) = $smcFunc['db_fetch_row']($request);
                                        $smcFunc['db_free_result']($request);
                                        $acsnew = implode(',', $newacs);
                                        $xmlResult .= (!empty($xmlResult) ? '&' : '') . $id . '|' . $acsnew . '|' . count($newacs) . '|' . intval(allowPmxGroup($newacs)) . '|' . (!empty($active) ? '1' : '0');
                                    }
                                }
                            }
                        }
                        // clear cached blocks && Cat/Art Session Keys
                        $pmxCacheFunc['clean']();
                        if (isset($_SESSION['PortaMx'])) {
                            foreach ($_SESSION['PortaMx'] as $key => $val) {
                                if (strpos($key, 'pmxpost_') !== false) {
                                    unset($_SESSION['PortaMx'][$key]);
                                }
                            }
                        }
                        if (isset($_POST['xml'])) {
                            // return update result
                            ob_start();
                            if (!empty($_POST['result'])) {
                                echo $_POST['result'];
                            } else {
                                echo $xmlResult;
                            }
                            ob_end_flush();
                            exit;
                        }
                    }
                    // add a new article
                    if (!empty($_POST['add_new_article'])) {
                        $article = PortaMx_getDefaultArticle($_POST['add_new_article']);
                        $context['pmx']['subaction'] = 'editnew';
                    } elseif (!empty($_POST['edit_article']) || !empty($_POST['clone_article'])) {
                        $id = !empty($_POST['clone_article']) ? $_POST['clone_article'] : $_POST['edit_article'];
                        // load the article for edit/clone
                        $request = $smcFunc['db_query']('', '
							SELECT *
							FROM {db_prefix}portamx_articles
							WHERE id = {int:id}', array('id' => $id));
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $article = array('id' => $row['id'], 'name' => $row['name'], 'catid' => $row['catid'], 'acsgrp' => $row['acsgrp'], 'ctype' => $row['ctype'], 'config' => $row['config'], 'content' => $row['content'], 'active' => $row['active'], 'owner' => $row['owner'], 'created' => $row['created'], 'approved' => $row['approved'], 'approvedby' => $row['approvedby'], 'updated' => $row['updated'], 'updatedby' => $row['updatedby']);
                        $smcFunc['db_free_result']($request);
                        if (!empty($_POST['clone_article'])) {
                            $article['id'] = 0;
                            $article['active'] = 0;
                            $article['approved'] = 0;
                            $article['owner'] = $user_info['id'];
                            $article['created'] = 0;
                            $article['updated'] = 0;
                            $article['updatedby'] = 0;
                            $context['pmx']['subaction'] = 'editnew';
                        } else {
                            $context['pmx']['subaction'] = 'edit';
                        }
                    } elseif (!empty($_POST['delete_article'])) {
                        $delid = $_POST['delete_article'];
                        // get the current page
                        $context['pmx']['articlestart'] = getCurrentPage($delid, $context['pmx']['settings']['manager']['artpage'], true);
                        $smcFunc['db_query']('', '
							DELETE FROM {db_prefix}portamx_articles
							WHERE id = {int:id}', array('id' => $delid));
                        // clear cached blocks
                        $pmxCacheFunc['clean']();
                    } elseif (!empty($_POST['chg_approved'])) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_articles
							SET approved = CASE WHEN approved = 0 THEN {int:apptime} ELSE 0 END, approvedby = {int:appmember}
							WHERE id = {int:id}', array('id' => $_POST['chg_approved'], 'apptime' => forum_time(), 'appmember' => $user_info['id']));
                        // clear cached blocks
                        $pmxCacheFunc['clean']();
                    } elseif (!empty($_POST['chg_active'])) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_articles
							SET active = CASE WHEN active = 0 THEN {int:apptime} ELSE 0 END
							WHERE id = {int:id}', array('id' => $_POST['chg_active'], 'apptime' => forum_time()));
                        // clear cached blocks
                        $pmxCacheFunc['clean']();
                    }
                    if (isset($_POST['xml']) && (!empty($_POST['chg_active']) || !empty($_POST['chg_approved']))) {
                        $id = !empty($_POST['chg_active']) ? $_POST['chg_active'] : $_POST['chg_approved'];
                        $request = $smcFunc['db_query']('', '
							SELECT active, approved
							FROM {db_prefix}portamx_articles
							WHERE id = {int:id}', array('id' => $id));
                        list($active, $approved) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        // return update result
                        ob_start();
                        echo $id . ',' . (!empty($_POST['chg_active']) ? intval(!empty($active)) : intval(!empty($approved)));
                        ob_end_flush();
                        exit;
                    }
                } elseif (!empty($_POST['cancel_edit']) || !empty($_POST['cancel_overview'])) {
                    // called fron blocks move/clone ?
                    if (!empty($_POST['fromblock'])) {
                        // on cancel after saved remove the article
                        if ($_POST['sa'] == 'edit' && !empty($_POST['id'])) {
                            $smcFunc['db_query']('', '
								DELETE FROM {db_prefix}portamx_articles
								WHERE id = {int:id}', array('id' => $_POST['id']));
                            $pmxCacheFunc['clean']();
                        }
                        // redirect back to the blocks manager
                        @(list($mode, $side, $bid) = explode('.', $_POST['fromblock']));
                        redirectexit('action=' . $admMode . ';area=pmx_blocks;sa=' . $side . ';' . $context['session_var'] . '=' . $context['session_id']);
                    }
                    // Otherwise let's load the overview
                    $context['pmx']['subaction'] = 'overview';
                } elseif ($context['pmx']['subaction'] == 'editnew' || $context['pmx']['subaction'] == 'edit') {
                    $context['pmx']['fromblock'] = $_POST['fromblock'];
                    // check defined numeric vars (check_num_vars holds the posted array to check like [varname][varname] ...)
                    if (isset($_POST['check_num_vars'])) {
                        foreach ($_POST['check_num_vars'] as $val) {
                            $data = explode(',', $val);
                            $post = '$_POST' . str_replace(array('[', ']'), array('[\'', '\']'), $data[0]);
                            if (eval("return isset({$post});") && eval("return !is_numeric({$post});")) {
                                eval("{$post} = {$data['1']};");
                            }
                        }
                    }
                    if (isset($_POST['content']) && PortaMx_makeSafeContent($_POST['content']) != '') {
                        // convert html/script to bbc
                        if ($_POST['ctype'] == 'bbc_script' && in_array($_POST['contenttype'], array('html', 'script'))) {
                            $_POST['content'] = PortaMx_SmileyToBBC($_POST['content']);
                            if (preg_match_all('/<img.*(style[^\\"]*\\"([^\\"]*\\"))[^>]*>/U', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $repl = ' ' . str_replace(array('"', ': ', ':', 'px;'), array('', '="', '="', '" '), $match[2][$key]);
                                    $_POST['content'] = str_replace($val, str_replace($match[1][$key], $repl, $val), $_POST['content']);
                                }
                            }
                            require_once $sourcedir . '/Subs-Editor.php';
                            $modSettings['smiley_enable'] = true;
                            $user_info['smiley_set'] = 'PortaMx';
                            $_POST['content'] = html_to_bbc($_POST['content']);
                        } elseif ($_POST['contenttype'] == 'bbc_script' && in_array($_POST['ctype'], array('html', 'script'))) {
                            $_POST['content'] = PortaMx_BBCsmileys(parse_bbc(PortaMx_makeSafeContent($_POST['content'], $_POST['contenttype']), false));
                            $_POST['content'] = str_replace(array('<hr>', '<br>'), array('<hr />', '<br />'), $_POST['content']);
                            $_POST['content'] = preg_replace_callback('/<\\/[^>]*>|<[^\\/]*\\/>|<ul[^>]*>|<ol[^>]*>/', create_function('$matches', 'return $matches[0] ."\\n";'), $_POST['content']);
                            if (preg_match_all('/<img[^w]*(width=\\"([0-9]+)\\")(\\sheight=\\"([\\s0-9]+)\\")[^>]*>/', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $_POST['content'] = str_replace($match[1][$key], '', $_POST['content']);
                                    $_POST['content'] = str_replace($match[3][$key], 'style="width: ' . $match[2][$key] . 'px;height: ' . $match[4][$key] . 'px;"', $_POST['content']);
                                }
                                $_POST['content'] = preg_replace('/px;"[^c]*class=/', 'px;" class=', $_POST['content']);
                            }
                        } elseif ($_POST['ctype'] == 'php' && $_POST['contenttype'] == 'php') {
                            pmxPHP_convert();
                        } elseif ($_POST['ctype'] == 'html' && $_POST['contenttype'] == 'html') {
                            $_POST['content'] = str_replace('/ckeditor/../Smileys/', '/Smileys/', $_POST['content']);
                            if (preg_match_all('~<img.*(class[^r]*resized[^\\"]*\\")[^>]*>~', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $endChr = substr($val, -2) !== '/>' ? array('>', '/>') : array(' />', '/>');
                                    $repl = str_replace($match[1][$key], '', $val);
                                    $_POST['content'] = str_replace($val, str_replace($endChr[0], ' class="bbc_img resized"' . $endChr[1], $repl), $_POST['content']);
                                }
                            } elseif (preg_match_all('~<img[^>]*>~', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $endChr = substr($val, -2) !== ' />' ? array('>', '/>') : array(' />', '/>');
                                    if (strpos($val, '/Smileys/') === false) {
                                        $_POST['content'] = str_replace($val, str_replace($endChr[0], ' class="bbc_img resized"' . $endChr[1], $val), $_POST['content']);
                                    }
                                }
                            }
                        }
                    }
                    // get all data
                    $article = array('id' => $_POST['id'], 'name' => $_POST['name'], 'catid' => $_POST['catid'], 'acsgrp' => !empty($_POST['acsgrp']) ? implode(',', $_POST['acsgrp']) : '', 'ctype' => $_POST['ctype'], 'config' => serialize($_POST['config']), 'content' => $_POST['content'], 'active' => $_POST['active'], 'owner' => $_POST['owner'], 'created' => $_POST['created'], 'approved' => $_POST['approved'], 'approvedby' => $_POST['approvedby'], 'updated' => $_POST['updated'], 'updatedby' => $_POST['updatedby']);
                    // save article if have content..
                    if (!empty($article['content']) && empty($_POST['edit_change']) && (!empty($_POST['save_edit']) || !empty($article['content']) && !empty($_POST['save_edit_continue']))) {
                        // if new article get the last id
                        if ($context['pmx']['subaction'] == 'editnew') {
                            $request = $smcFunc['db_query']('', '
								SELECT MAX(id)
								FROM {db_prefix}portamx_articles', array());
                            list($dbid) = $smcFunc['db_fetch_row']($request);
                            $smcFunc['db_free_result']($request);
                            $article['id'] = strval(1 + ($dbid === null ? $article['id'] : $dbid));
                            $article['created'] = forum_time();
                            // auto approve for admins
                            if (allowPmx('pmx_admin')) {
                                $article['approved'] = forum_time();
                                $article['approvedby'] = $user_info['id'];
                            }
                            // insert new article
                            $smcFunc['db_insert']('ignore', '
								{db_prefix}portamx_articles', array('id' => 'int', 'name' => 'string', 'catid' => 'int', 'acsgrp' => 'string', 'ctype' => 'string', 'config' => 'string', 'content' => 'string', 'active' => 'int', 'owner' => 'int', 'created' => 'int', 'approved' => 'int', 'approvedby' => 'int', 'updated' => 'int', 'updatedby' => 'int'), $article, array());
                            // clear cache
                            $pmxCacheFunc['clean']();
                        } else {
                            $article['updated'] = forum_time();
                            $article['updatedby'] = $user_info['id'];
                            // update the article
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}portamx_articles
								SET name = {string:name}, catid = {int:catid}, acsgrp = {string:acsgrp}, ctype = {string:ctype}, config = {string:config},
										content = {string:content}, active = {int:active}, owner = {int:owner}, created = {int:created}, approved = {int:approved},
										approvedby = {int:approvedby}, updated = {int:updated}, updatedby = {int:updatedby}
								WHERE id = {int:id}', array('id' => $article['id'], 'name' => $article['name'], 'catid' => $article['catid'], 'acsgrp' => $article['acsgrp'], 'ctype' => $article['ctype'], 'config' => $article['config'], 'content' => $article['content'], 'active' => $article['active'], 'owner' => $article['owner'], 'created' => $article['created'], 'approved' => $article['approved'], 'approvedby' => $article['approvedby'], 'updated' => $article['updated'], 'updatedby' => $article['updatedby']));
                        }
                        // clear cache
                        $pmxCacheFunc['clean']();
                        $context['pmx']['subaction'] = 'edit';
                    }
                    // continue edit ?
                    if (!empty($_POST['save_edit']) || !empty($_POST['save_edit_continue'])) {
                        if (empty($_POST['save_edit_continue'])) {
                            // edit done, is it a move/clone from blocks?
                            if (!empty($context['pmx']['fromblock'])) {
                                @(list($mode, $side, $bid) = explode('.', $context['pmx']['fromblock']));
                                // was block moved?
                                if ($mode == 'move') {
                                    $request = $smcFunc['db_query']('', '
										SELECT pos, blocktype
										FROM {db_prefix}portamx_blocks
										WHERE id = {int:bid}', array('bid' => $bid));
                                    $block = $smcFunc['db_fetch_assoc']($request);
                                    $smcFunc['db_free_result']($request);
                                    // update all pos >= moved id
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_blocks
										SET pos = pos - 1
										WHERE side = {string:side} AND pos >= {int:pos}', array('side' => $side, 'pos' => $block['pos']));
                                    // delete the block
                                    $smcFunc['db_query']('', '
										DELETE FROM {db_prefix}portamx_blocks
										WHERE id = {int:id}', array('id' => $bid));
                                    // clear cache and SEF pages list
                                    $pmxCacheFunc['clean']();
                                }
                            }
                            // go to article overview
                            $context['pmx']['subaction'] = 'overview';
                            $context['pmx']['articlestart'] = getCurrentPage($article['id'], $context['pmx']['settings']['manager']['artpage']);
                        }
                    }
                    // clear cached blocks
                    $pmxCacheFunc['clean']();
                }
                if ($context['pmx']['subaction'] == 'overview') {
                    if (!isset($context['pmx']['articlestart'])) {
                        $context['pmx']['articlestart'] = 0;
                    }
                    redirectexit('action=' . $admMode . ';area=pmx_articles;' . $context['session_var'] . '=' . $context['session_id'] . ';pg=' . $context['pmx']['articlestart']);
                }
            }
            // load the template, initialize the page title
            loadTemplate($context['pmx_templatedir'] . 'AdminArticles');
            $context['page_title'] = $txt['pmx_articles'];
            $context['pmx']['AdminMode'] = $admMode;
            $context['pmx']['RegBlocks'] = eval($context['pmx']['registerblocks']);
            // direct edit request?
            if (isset($_GET['sa']) && PortaMx_makeSafe($_GET['sa']) == 'edit' && !empty($_GET['id'])) {
                // move or clone from blocks?
                if (isset($_GET['from'])) {
                    $context['pmx']['fromblock'] = PortaMx_makeSafe($_GET['from']) . '.' . PortaMx_makeSafe($_GET['id']);
                    // load the block
                    $request = $smcFunc['db_query']('', '
						SELECT *
						FROM {db_prefix}portamx_blocks
						WHERE id = {int:id}', array('id' => PortaMx_makeSafe($_GET['id'])));
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $smcFunc['db_free_result']($request);
                    // modify the config array
                    $cfg = unserialize($row['config']);
                    if (isset($cfg['pagename'])) {
                        $pgname = $cfg['pagename'];
                        unset($cfg['pagename']);
                    } else {
                        $pgname = '';
                    }
                    unset($cfg['ext_opts']);
                    if (isset($cfg['frontmode'])) {
                        unset($cfg['frontmode']);
                    }
                    $cfg['can_moderate'] = allowedTo('admin_forum') ? 0 : 1;
                    $article = array('id' => 0, 'name' => $pgname, 'catid' => 0, 'acsgrp' => $row['acsgrp'], 'ctype' => $row['blocktype'], 'config' => serialize($cfg), 'content' => $row['content'], 'active' => 0, 'owner' => $user_info['id'], 'created' => 0, 'approved' => 0, 'approvedby' => 0, 'updated' => 0, 'updatedby' => 0);
                    $context['pmx']['subaction'] = 'editnew';
                    $context['pmx']['articlestart'] = 0;
                } else {
                    $context['pmx']['fromblock'] = '';
                    $request = $smcFunc['db_query']('', '
						SELECT *
						FROM {db_prefix}portamx_articles
						WHERE id = {int:id}', array('id' => PortaMx_makeSafe($_GET['id'])));
                    if ($smcFunc['db_num_rows']($request) > 0) {
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $article = array('id' => $row['id'], 'name' => $row['name'], 'catid' => $row['catid'], 'acsgrp' => $row['acsgrp'], 'ctype' => $row['ctype'], 'config' => $row['config'], 'content' => $row['content'], 'active' => $row['active'], 'owner' => $row['owner'], 'created' => $row['created'], 'approved' => $row['approved'], 'approvedby' => $row['approvedby'], 'updated' => $row['updated'], 'updatedby' => $row['updatedby']);
                        $smcFunc['db_free_result']($request);
                        $context['pmx']['subaction'] = 'edit';
                        $context['pmx']['articlestart'] = 0;
                    }
                }
            }
            // continue edit or overview?
            if ($context['pmx']['subaction'] == 'overview') {
                // load article data for overview
                if (!allowPmx('pmx_articles') && allowPmx('pmx_create', true)) {
                    $where = 'WHERE a.owner = {int:owner}';
                } else {
                    $where = '';
                }
                if (!isset($_SESSION['PortaMx']['filter'])) {
                    $_SESSION['PortaMx']['filter'] = array('category' => '', 'approved' => 0, 'active' => 0, 'myown' => 0, 'member' => '');
                }
                if ($_SESSION['PortaMx']['filter']['category'] != '') {
                    $where .= (empty($where) ? 'WHERE ' : ' AND ') . 'a.catid IN ({array_int:catfilter})';
                }
                if ($_SESSION['PortaMx']['filter']['approved'] != 0) {
                    $where .= empty($where) ? 'WHERE ' : ' AND ';
                    if ($_SESSION['PortaMx']['filter']['active'] != 0) {
                        $where .= '(a.approved = 0 OR a.active = 0)';
                    } else {
                        $where .= 'a.approved = 0';
                    }
                }
                if ($_SESSION['PortaMx']['filter']['active'] != 0) {
                    $where .= empty($where) ? 'WHERE ' : ' AND ';
                    if ($_SESSION['PortaMx']['filter']['approved'] != 0) {
                        $where .= '(a.active = 0 OR a.approved = 0)';
                    } else {
                        $where .= 'a.active = 0';
                    }
                }
                if ($_SESSION['PortaMx']['filter']['myown'] != 0) {
                    $where .= (empty($where) ? 'WHERE ' : ' AND ') . 'a.owner = {int:owner}';
                }
                if ($_SESSION['PortaMx']['filter']['member'] != '') {
                    $where .= (empty($where) ? 'WHERE ' : ' AND ') . 'm.member_name LIKE {string:memname}';
                }
                if (isset($_GET['pg']) && !is_array($_GET['pg'])) {
                    $context['pmx']['articlestart'] = PortaMx_makeSafe($_GET['pg']);
                    unset($_GET['pg']);
                } elseif (!isset($context['pmx']['articlestart'])) {
                    $context['pmx']['articlestart'] = 0;
                }
                $cansee = allowPmx('pmx_articles, pmx_create', true);
                $isadmin = allowPmx('pmx_admin');
                $memerIDs = array();
                $context['pmx']['articles'] = array();
                $context['pmx']['article_rows'] = array();
                $context['pmx']['totalarticles'] = 0;
                $result = null;
                $request = $smcFunc['db_query']('', '
					SELECT a.id, a.name, a.catid, a.acsgrp, a.ctype, a.config, a.active, a.owner, a.created, a.approved, a.approvedby, a.updated, a.updatedby, a.content, c.artsort, c.level, c.name AS catname
					FROM {db_prefix}portamx_articles AS a' . ($_SESSION['PortaMx']['filter']['member'] != '' ? '
					LEFT JOIN {db_prefix}members AS m ON (a.owner = m.id_member)' : '') . '
					LEFT JOIN {db_prefix}portamx_categories AS c ON (a.catid = c.id)
					' . $where . '
					ORDER BY a.id', array('catfilter' => Pmx_StrToArray($_SESSION['PortaMx']['filter']['category']), 'memname' => str_replace('*', '%', $_SESSION['PortaMx']['filter']['member']), 'owner' => $user_info['id']));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        $cfg = unserialize($row['config']);
                        if (!empty($isadmin) || $cansee && !empty($cfg['can_moderate'])) {
                            $memerIDs[] = $row['owner'];
                            $memerIDs[] = $row['approvedby'];
                            $memerIDs[] = $row['updatedby'];
                            $context['pmx']['article_rows'][$row['id']] = array('name' => $row['name'], 'cat' => str_repeat('&bull;', $row['level']) . $row['catname']);
                            $result[] = array('id' => $row['id'], 'name' => $row['name'], 'catid' => $row['catid'], 'cat' => str_repeat('&bull;', $row['level']) . $row['catname'], 'acsgrp' => $row['acsgrp'], 'ctype' => $row['ctype'], 'config' => $cfg, 'active' => $row['active'], 'owner' => $row['owner'], 'created' => $row['created'], 'approved' => $row['approved'], 'approvedby' => $row['approvedby'], 'updated' => $row['updated'], 'updatedby' => $row['updatedby'], 'content' => $row['content']);
                        }
                    }
                    $smcFunc['db_free_result']($request);
                    if (!empty($result)) {
                        foreach ($result as $st => $data) {
                            $context['pmx']['articles'][$st] = $data;
                        }
                        $context['pmx']['totalarticles'] = count($result);
                        if ($context['pmx']['totalarticles'] <= $context['pmx']['articlestart']) {
                            $context['pmx']['articlestart'] = 0;
                        }
                        // get all members names
                        $request = $smcFunc['db_query']('', '
							SELECT id_member, member_name
							FROM {db_prefix}members
							WHERE id_member IN ({array_int:members})', array('members' => array_unique($memerIDs)));
                        if ($smcFunc['db_num_rows']($request) > 0) {
                            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                                $context['pmx']['articles_member'][$row['id_member']] = $row['member_name'];
                            }
                            $smcFunc['db_free_result']($request);
                        }
                    }
                }
                // load popup js for overview
                loadJavascriptFile(PortaMx_loadCompressed('PortaMxPopup.js'), array('external' => true));
            } elseif (empty($_POST['save_edit'])) {
                // prepare the editor
                PortaMx_EditArticle($article['ctype'], 'content', $article['content']);
                // load the class file and create the object
                require_once $context['pmx_sysclassdir'] . 'PortaMx_AdminArticlesClass.php';
                $context['pmx']['editarticle'] = new PortaMxC_SystemAdminArticle($article);
                $context['pmx']['editarticle']->pmxc_AdmArticle_loadinit();
            }
        } else {
            fatal_error($txt['pmx_acces_error']);
        }
    }
}
/**
* Receive all the Posts from Categories Manager, check and save it.
* Finally the categories are prepared and the templare loaded.
*/
function PortaMx_AdminCategories()
{
    global $smcFunc, $context, $scripturl, $pmxCacheFunc, $txt;
    $admMode = isset($_GET['action']) ? $_GET['action'] : '';
    // fix the linktree
    if ($admMode == 'admin') {
        foreach ($context['linktree'] as $key => $data) {
            if (strpos($data['url'], 'pmx_categories') !== false) {
                $context['linktree'] = array_merge(array_slice($context['linktree'], 0, $key), array(array('url' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'name' => $txt['pmx_extension'])), array_slice($context['linktree'], $key, count($context['linktree']) - $key));
                break;
            }
        }
    }
    if (($admMode == 'admin' || $admMode == 'portamx') && allowPmx('pmx_admin') && isset($_GET['area']) && $_GET['area'] == 'pmx_categories') {
        require_once $context['pmx_sourcedir'] . 'AdminSubs.php';
        $context['pmx']['subaction'] = isset($_POST['sa']) ? $_POST['sa'] : 'overview';
        // From template ?
        if (PortaMx_checkPOST()) {
            // check the Post session
            checkSession('post');
            // actions from overview ?
            if ($context['pmx']['subaction'] == 'overview' && empty($_POST['cancel_overview'])) {
                // updates from overview popups ?
                if (!empty($_POST['upd_overview'])) {
                    if (isset($_POST['xml'])) {
                        $xmlResult = '';
                    }
                    $updates = array();
                    foreach ($_POST['upd_overview'] as $updkey => $updvalues) {
                        foreach ($updvalues as $id => $values) {
                            if ($updkey == 'title') {
                                foreach ($values as $key => $val) {
                                    if ($key == 'lang') {
                                        foreach ($val as $langname => $langvalue) {
                                            $updates[$id]['config'][$updkey][$langname] = $langvalue;
                                        }
                                    } else {
                                        $updates[$id]['config'][$updkey . '_' . $key] = $val;
                                    }
                                }
                            } else {
                                $updates[$id][$updkey] = $values;
                            }
                        }
                    }
                    // save all updates
                    foreach ($updates as $id => $values) {
                        $request = $smcFunc['db_query']('', '
							SELECT config, acsgrp
							FROM {db_prefix}portamx_categories
							WHERE id = {int:id}', array('id' => $id));
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $smcFunc['db_free_result']($request);
                        foreach ($values as $rowname => $data) {
                            // update config array
                            if ($rowname == 'config') {
                                $cfg = unserialize($row['config']);
                                foreach ($data as $ckey => $cval) {
                                    if ($ckey == 'title') {
                                        foreach ($cval as $lang => $val) {
                                            $cfg[$ckey][$lang] = $val;
                                        }
                                    } else {
                                        $cfg[$ckey] = $cval;
                                    }
                                }
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}portamx_categories
									SET config = {string:config}
									WHERE id = {int:id}', array('id' => $id, 'config' => serialize($cfg)));
                            } elseif ($rowname == 'catname') {
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}portamx_categories
									SET name = {string:val}
									WHERE id = {int:id}', array('id' => $id, 'val' => $data));
                            } else {
                                $mode = substr($rowname, 0, 3);
                                // update (replace)
                                if ($mode == 'upd') {
                                    $newacs = explode(',', $data);
                                } elseif ($mode == 'add') {
                                    $newacs = array_unique(array_merge(explode(',', $row['acsgrp']), explode(',', $data)));
                                } else {
                                    $newacs = array_unique(array_diff(explode(',', $row['acsgrp']), explode(',', $data)));
                                }
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}portamx_categories
									SET acsgrp = {string:val}
									WHERE id = {int:id}', array('id' => $id, 'val' => implode(',', $newacs)));
                                // send by xml?
                                if (isset($_POST['xml'])) {
                                    $acsnew = implode(',', $newacs);
                                    $xmlResult .= (!empty($xmlResult) ? '&' : '') . $id . '|' . $acsnew . '|' . count($newacs) . '|' . intval(allowPmxGroup($newacs)) . '|1';
                                }
                            }
                        }
                    }
                    // clear cache
                    $pmxCacheFunc['clean']();
                    if (isset($_POST['xml'])) {
                        // return update result
                        ob_start();
                        if (!empty($_POST['result'])) {
                            echo $_POST['result'];
                        } else {
                            echo $xmlResult;
                        }
                        ob_end_flush();
                        exit;
                    }
                }
                // add new category
                if (!empty($_POST['add_new_category'])) {
                    $category = PortaMx_getDefaultCategory();
                    $context['pmx']['subaction'] = 'editnew';
                } elseif (!empty($_POST['edit_category']) || !empty($_POST['clone_category'])) {
                    $id = PortaMx_makeSafe(!empty($_POST['clone_category']) ? $_POST['clone_category'] : $_POST['edit_category']);
                    // load the category for edit/clone
                    $request = $smcFunc['db_query']('', '
						SELECT *
						FROM {db_prefix}portamx_categories
						WHERE id = {int:id}', array('id' => $id));
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $category = array('id' => $row['id'], 'name' => $row['name'], 'parent' => $row['parent'], 'level' => $row['level'], 'catorder' => $row['catorder'], 'acsgrp' => $row['acsgrp'], 'artsort' => $row['artsort'], 'config' => $row['config']);
                    $smcFunc['db_free_result']($request);
                    if (!empty($_POST['clone_category'])) {
                        $category['id'] = 0;
                        $category['parent'] = 0;
                        $category['level'] = 0;
                        $category['catorder'] = 0;
                        $context['pmx']['subaction'] = 'editnew';
                    } else {
                        $context['pmx']['subaction'] = 'edit';
                    }
                } elseif (!empty($_POST['delete_category'])) {
                    pmx_delete_cat(PortaMx_makeSafe($_POST['delete_category']));
                    // set catid in articles to none (0)
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}portamx_articles
						SET catid = 0
						WHERE catid = {int:id}', array('id' => PortaMx_makeSafe($_POST['delete_category'])));
                    // clear cache
                    $pmxCacheFunc['clean']();
                } elseif (!empty($_POST['move_category'])) {
                    pmx_move_cat(PortaMx_makeSafe($_POST['move_category']), PortaMx_makeSafe($_POST['catplace']), PortaMx_makeSafe($_POST['movetocat']));
                    // clear cache
                    $pmxCacheFunc['clean']();
                }
            } elseif (!empty($_POST['cancel_edit']) || !empty($_POST['cancel_overview'])) {
                $context['pmx']['subaction'] = 'overview';
            } elseif ($context['pmx']['subaction'] == 'editnew' || $context['pmx']['subaction'] == 'edit') {
                // check defined numeric vars (check_num_vars holds the posted array to check like [varname][varname] ...)
                if (isset($_POST['check_num_vars'])) {
                    if (isset($_POST['check_num_vars'])) {
                        foreach ($_POST['check_num_vars'] as $val) {
                            $data = explode(',', $val);
                            $post = '$_POST' . str_replace(array('[', ']'), array('[\'', '\']'), $data[0]);
                            if (eval("return isset({$post});") && eval("return !is_numeric({$post});")) {
                                eval("{$post} = {$data['1']};");
                            }
                        }
                    }
                }
                // get all data
                $category = array('id' => $_POST['id'], 'name' => PortaMx_makeSafe($_POST['name']), 'parent' => $_POST['parent'], 'level' => $_POST['level'], 'catorder' => $_POST['catorder'], 'acsgrp' => !empty($_POST['acsgrp']) ? implode(',', $_POST['acsgrp']) : '', 'artsort' => !empty($_POST['artsort']) ? implode(',', $_POST['artsort']) : '', 'config' => serialize($_POST['config']));
                // save category.
                if (empty($_POST['edit_change']) && (!empty($_POST['save_edit']) || !empty($_POST['save_edit_continue']))) {
                    // if new category get the last id and catorder
                    if ($context['pmx']['subaction'] == 'editnew') {
                        $category = pmx_insert_cat(PortaMx_makeSafe($_POST['catplace']), PortaMx_makeSafe($_POST['catid']), $category);
                        // get max catid
                        $request = $smcFunc['db_query']('', '
							SELECT MAX(id)
							FROM {db_prefix}portamx_categories', array());
                        list($maxid) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        $category['id'] = strval(1 + ($maxid === null ? $category['id'] : $maxid));
                    }
                    // now save all data
                    $smcFunc['db_insert']('replace', '
						{db_prefix}portamx_categories', array('id' => 'int', 'name' => 'string', 'parent' => 'int', 'level' => 'int', 'catorder' => 'int', 'acsgrp' => 'string', 'artsort' => 'string', 'config' => 'string'), array($category['id'], $category['name'], $category['parent'], $category['level'], $category['catorder'], $category['acsgrp'], $category['artsort'], $category['config']), array('id'));
                    // clear cache
                    $pmxCacheFunc['clean']();
                    $context['pmx']['subaction'] = 'edit';
                }
                // continue edit ?
                if (!empty($_POST['save_edit'])) {
                    $context['pmx']['subaction'] = 'overview';
                }
            }
            if ($context['pmx']['subaction'] == 'overview') {
                redirectexit('action=' . $admMode . ';area=pmx_categories;' . $context['session_var'] . '=' . $context['session_id']);
            }
        }
        // load template, setup pagetitle
        loadTemplate($context['pmx_templatedir'] . 'AdminCategories');
        $context['page_title'] = $txt['pmx_categories'];
        $context['pmx']['AdminMode'] = $admMode;
        // direct edit request?
        if (isset($_GET['sa']) && PortaMx_makeSafe($_GET['sa']) == 'edit' && !empty($_GET['id'])) {
            // load the category for edit
            $request = $smcFunc['db_query']('', '
				SELECT *
				FROM {db_prefix}portamx_categories
				WHERE id = {int:id}', array('id' => PortaMx_makeSafe($_GET['id'])));
            if ($smcFunc['db_num_rows']($request) > 0) {
                $row = $smcFunc['db_fetch_assoc']($request);
                $category = array('id' => $row['id'], 'name' => $row['name'], 'parent' => $row['parent'], 'level' => $row['level'], 'catorder' => $row['catorder'], 'acsgrp' => $row['acsgrp'], 'artsort' => $row['artsort'], 'config' => $row['config']);
                $smcFunc['db_free_result']($request);
                $context['pmx']['subaction'] = 'edit';
            }
        }
        // continue edit or overview ?
        if ($context['pmx']['subaction'] == 'overview') {
            // load all categories
            $context['pmx']['categories'] = PortaMx_getCategories(true);
            // load popup js for overview
            loadJavascriptFile(PortaMx_loadCompressed('PortaMxPopup.js'), array('external' => true));
        } elseif (empty($_POST['save_edit'])) {
            // load the class file and create the object
            require_once $context['pmx_sysclassdir'] . 'PortaMx_AdminCategoriesClass.php';
            $context['pmx']['editcategory'] = new PortaMxC_SystemAdminCategories($category);
            $context['pmx']['editcategory']->pmxc_AdmCategories_loadinit();
        }
    } else {
        fatal_error($txt['pmx_acces_error']);
    }
}
    /**
     * Get category and his childs
     */
    function getCatsAndChilds($cats, $acs, $acs_inherit = false)
    {
        global $context, $smcFunc;
        $catIDs = array();
        $catNames = array();
        $this->categories = array();
        $corder = $cats['catorder'];
        $cat = PortaMx_getCatByOrder(array($cats), $corder);
        while (is_array($cat)) {
            if (!is_array($cat['config'])) {
                $cat['config'] = unserialize($cat['config']);
            }
            // check ecl
            if (empty($cat['config']['check_ecl']) || !empty($cat['config']['check_ecl']) && pmx_checkECL_Cookie(!empty($cat['config']['check_eclbots']))) {
                if (!empty($cat['artsum'])) {
                    // get custom css if set
                    if (!empty($cat['config']['cssfile'])) {
                        $this->getCustomCSS($cat);
                    }
                    // inherit acs from block?
                    if (!empty($acs_inherit)) {
                        $cat['acsgrp'] = $acs;
                    }
                    if (allowPmxGroup($cat['acsgrp'])) {
                        $ttl = $this->getUserTitle($cat);
                        if (empty($ttl)) {
                            $ttl = htmlspecialchars($cat['name'], ENT_QUOTES);
                        }
                        $this->categories[$cat['name']] = array('id' => $cat['id'], 'name' => $cat['name'], 'artsort' => $cat['artsort'], 'acsgrp' => $cat['acsgrp'], 'config' => $cat['config'], 'side' => $this->cfg['side'], 'blocktype' => 'category', 'customclass' => '', 'title' => $ttl);
                        $catIDs[] = $cat['id'];
                        $catNames[$cat['id']] = $cat['name'];
                    }
                }
            } else {
                break;
            }
            $addSub = !empty($cat['config']['settings']['addsubcats']) && $cat['config']['settings']['showmode'] == 'sidebar' || !empty($cat['config']['settings']['showsubcats']) && $cat['config']['settings']['showmode'] == 'pages';
            if (!empty($addSub)) {
                $corder = PortaMx_getNextCat($corder);
                $cat = PortaMx_getCatByOrder(array($cats), $corder);
            } else {
                break;
            }
        }
        if (!empty($catIDs)) {
            // get articles for any cat
            $request = $smcFunc['db_query']('', '
				SELECT a.id, a.name, a.acsgrp, a.catid, a.ctype, a.config, a.owner, a.active, a.created, a.updated, a.approved, a.content, CASE WHEN m.real_name = {string:empty} THEN m.member_name ELSE m.real_name END AS mem_name
				FROM {db_prefix}portamx_articles AS a
				LEFT JOIN {db_prefix}members AS m ON (a.owner = m.id_member)
				WHERE a.catid IN ({array_int:cats}) AND a.active > 0 AND a.approved > 0
				ORDER BY a.id', array('cats' => $catIDs, 'empty' => ''));
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $row['config'] = unserialize($row['config']);
                // check ecl
                if (empty($row['config']['check_ecl']) || !empty($row['config']['check_ecl']) && pmx_checkECL_Cookie(!empty($row['config']['check_eclbots']))) {
                    if (!empty($this->categories[$catNames[$row['catid']]]['config']['settings']['inherit_acs'])) {
                        $row['acsgrp'] = $this->categories[$catNames[$row['catid']]]['acsgrp'];
                    }
                    if (allowPmxGroup($row['acsgrp'])) {
                        if (!empty($this->categories[$catNames[$row['catid']]]['config']['settings']['catstyle'])) {
                            $row['config']['visuals'] = $this->categories[$catNames[$row['catid']]]['config']['visuals'];
                            $row['config']['cssfile'] = $this->categories[$catNames[$row['catid']]]['config']['cssfile'];
                        }
                        $row['side'] = $this->cfg['side'];
                        $row['blocktype'] = !empty($this->cfg['config']) ? 'static_article' : 'article';
                        $row['member_name'] = $row['mem_name'];
                        // get custom css if set
                        if (!empty($row['config']['cssfile'])) {
                            $this->getCustomCSS($row);
                        }
                        $this->articles[$catNames[$row['catid']]][] = $row;
                    }
                }
            }
            $smcFunc['db_free_result']($request);
        }
        // articles found?
        $ccats = $this->categories;
        foreach ($ccats as $cname => $cdata) {
            if (!empty($this->articles[$cname])) {
                $this->articles[$cname] = PortaMx_ArticleSort($this->articles[$cname], $this->categories[$cname]['artsort']);
                // if article reqested, get the tile
                if (!empty($this->postarray[$this->postKey]['art']) && $cname == (empty($this->postarray[$this->postKey]['child']) ? $this->postarray[$this->postKey]['cat'] : $this->postarray[$this->postKey]['child'])) {
                    foreach ($this->articles[$cname] as $art) {
                        if ($art['name'] == $this->postarray[$this->postKey]['art']) {
                            $context['pmx']['pagenames']['art'] = $this->getUserTitle($art);
                            if (empty($context['pmx']['pagenames']['art'])) {
                                $context['pmx']['pagenames']['art'] = htmlspecialchars($art['name'], ENT_QUOTES);
                            }
                            break;
                        }
                    }
                }
            } else {
                unset($this->categories[$cname]);
            }
        }
    }
/**
* Top frame
**/
function Pmx_Frame_top($cfg, $count)
{
    global $context, $scripturl, $options, $txt;
    $context['pmx_framecount']++;
    $context['pmx_frames'][$context['pmx_framecount']] = true;
    if (!empty($cfg['config']['skip_outerframe'])) {
        $context['pmx_frames'][$context['pmx_framecount']] = false;
        return null;
    }
    // get the block title for user language have it or forum default
    $blocktitle = PortaMx_getTitle($cfg['config']);
    // the title align
    $ttladjust = '';
    switch ($cfg['config']['title_align']) {
        case 'left':
            $imgalign = 'right';
            $txtalign = 'left';
            $ttlimg = $txtalign;
            $toggleClass = 'class="float' . $imgalign;
            break;
        case 'right':
            $imgalign = 'left';
            $txtalign = 'right';
            $ttlimg = $txtalign;
            $toggleClass = 'class="float' . $imgalign;
            break;
        case 'center':
            $imgalign = 'right';
            $txtalign = 'center';
            $ttlimg = 'left';
            $toggleClass = 'class="float' . $imgalign;
    }
    if ($cfg['config']['title_icon'] == 'none.png') {
        $cfg['config']['title_icon'] = '';
    }
    if (empty($cfg['config']['title_icon'])) {
        $ttladjust = ' pmxadj';
    }
    if ($cfg['config']['title_align'] == 'center') {
        if (!empty($cfg['config']['title_icon']) && !empty($cfg['config']['collapse']) && $context['pmx']['settings']['shrinkimages'] != 2) {
            $ttladjust = ' pmxadj_center';
        } elseif (empty($cfg['config']['title_icon']) && empty($cfg['config']['collapse'])) {
            $ttladjust = '';
        } elseif (empty($cfg['config']['title_icon'])) {
            $ttladjust = ' pmxadj_' . $imgalign;
        } else {
            $ttladjust = ' pmxadj_' . $ttlimg;
        }
    }
    $cfg['config']['innerpad'] = isset($cfg['config']['innerpad']) ? $cfg['config']['innerpad'] : '4';
    $innerPad = Pmx_getInnerPad($cfg['config']['innerpad']);
    // custom css ?
    if (!empty($cfg['customclass'])) {
        $isCustHeader = !empty($cfg['customclass']['header']);
        $isCustFrame = !empty($cfg['customclass']['frame']);
    } else {
        $isCustHeader = $isCustFrame = false;
    }
    $IDtype = $cfg['blocktype'] . $cfg['id'];
    $frame = false;
    $cfg['noID'] = in_array($cfg['blocktype'], array('category', 'article', 'static_category', 'static_article'));
    $showAcs = allowPmxGroup($cfg['acsgrp']);
    $cfg['active'] = !isset($cfg['active']) ? true : $cfg['active'];
    echo '
						<div' . (empty($cfg['noID']) ? ' id="block.id.' . $cfg['id'] . '" ' : '') . ' style="margin-bottom:' . (empty($count) ? '0' : $context['pmx']['settings']['panelpad']) . 'px; overflow:hidden;' . (in_array(strtolower($cfg['side']), array('left', 'right')) ? 'width:' . $context['pmx']['settings'][strtolower($cfg['side']) . '_panel']['size'] . 'px; padding-' . (strtolower($cfg['side']) == 'left' ? 'right:' : 'left:') . $context['pmx']['settings']['panelpad'] . 'px;' : '') . (empty($cfg['active']) || empty($showAcs) ? 'display:none;' : '') . '">';
    // show the collapse, if set and have a header
    $head_bar = !empty($cfg['config']['visuals']['header']) && $cfg['config']['visuals']['header'] !== 'hide' ? str_replace('bg', '_bar', $cfg['config']['visuals']['header']) : '';
    if (!empty($cfg['config']['visuals']['header']) && $cfg['config']['visuals']['header'] != 'none' || empty($cfg['config']['visuals']['header']) && !empty($cfg['config']['visuals']['body'])) {
        echo '
							<div class="' . (!empty($head_bar) ? $head_bar : 'title_no_bar') . '">
								<h3';
        if (!empty($cfg['config']['collapse']) && $context['pmx']['settings']['shrinkimages'] != 2) {
            if (!isset($options['collapse' . $IDtype])) {
                $cook = pmx_getcookie('pmx_upshr' . $IDtype, false);
                $options['collapse' . $IDtype] = is_null($cook) ? '0' : $cook;
            }
        } else {
            $options['collapse' . $IDtype] = '0';
        }
        echo ' class="' . (!empty($cfg['config']['visuals']['header']) ? $cfg['config']['visuals']['header'] : $cfg['config']['visuals']['body']) . ' cbodypad">';
        // show the collapse / expand icon
        if (!empty($cfg['config']['collapse'])) {
            echo '
									<span id="upshrink_' . $IDtype . '_Img" ' . (empty($options['collapse' . $IDtype]) ? $toggleClass . $context['pmx_img_expand'] : $toggleClass . $context['pmx_img_colapse']) . ' title="' . (empty($options['collapse' . $IDtype]) ? $txt['pmx_collapse'] : $txt['pmx_expand']) . $blocktitle . '"></span>';
        }
        // show the title icon is set
        if (!empty($cfg['config']['title_icon'])) {
            echo '
									<img class="title_images pmx' . $ttlimg . '" src="' . $context['pmx_Iconsurl'] . $cfg['config']['title_icon'] . '" alt="*" title="' . $blocktitle . '" />';
        }
        echo '
									<span class="pmxtitle pmx' . $txtalign . $ttladjust . '">';
        // if quickedit link the title to blockedit?
        if (!empty($context['pmx']['settings']['manager']['qedit']) && allowPmx('pmx_admin') && !empty($blocktitle)) {
            $btyp = str_replace('static_', '', $cfg['blocktype']);
            echo '
										<a href="' . $scripturl . '?action=' . (allowPmx('pmx_admin', true) ? 'portamx' : 'admin') . ';area=pmx_' . (in_array($btyp, array('category', 'article')) ? $btyp == 'category' ? 'categories;sa=edit;id=' . preg_replace('/_[0-9]+/', '', $cfg['catid']) : 'articles;sa=edit;id=' . preg_replace('/_[0-9]+/', '', $cfg['id']) : 'blocks;sa=' . $cfg['side']) . ';edit=' . preg_replace('/_[0-9]+/', '', $cfg['id']) . ';' . $context['session_var'] . '=' . $context['session_id'] . '" onclick="pmxsetEditTop(this)">' . $blocktitle . '</a>';
        } else {
            echo '
									' . (empty($blocktitle) ? '&nbsp;' : $blocktitle);
        }
        echo '
									</span>
								</h3>
							</div>';
    }
    // show content frame
    $frameclass = $cfg['config']['visuals']['frame'] . ' ' . $cfg['config']['visuals']['body'] . (strpos($head_bar, 'notrnd') !== false ? ' notrnd' : '');
    if (!empty($cfg['config']['visuals']['frame']) || $isCustFrame) {
        echo '
							<div' . (!empty($cfg['config']['collapse']) ? ' id="upshrink_' . $IDtype . '"' . (empty($options['collapse' . $IDtype]) ? '' : ' style="display:none;"') : '') . '>
								<div class="' . $frameclass . '" style="padding:' . $innerPad[0] . 'px ' . $innerPad[1] . 'px !important; margin-top:0px;">
									<div';
    } else {
        echo '
							<div' . (!empty($cfg['config']['collapse']) ? ' id="upshrink_' . $IDtype . '"' . (empty($options['collapse' . $IDtype]) ? '' : ' style="display:none;"') : '') . (!empty($cfg['config']['visuals']['body']) ? ' class="blockcontent fr_' . $head_bar . ' ' . $cfg['config']['visuals']['body'] . '"' : '') . '>
								<div' . (!empty($hashead) ? ' class="pmx_noframe_' . $cfg['blocktype'] . '"' : '') . ' style="padding:' . $innerPad[0] . 'px ' . $innerPad[1] . 'px !important;">
									<div';
    }
    // have a bodytext class ?
    if (!empty($cfg['config']['visuals']['bodytext'])) {
        echo ' class="' . $cfg['config']['visuals']['bodytext'] . '"';
    }
    // have overflow and (min-/max-)height?
    if (!empty($cfg['config']['overflow'])) {
        echo ' style="' . (isset($cfg['config']['maxheight']) && !empty($cfg['config']['maxheight']) ? (empty($cfg['config']['height']) ? 'max-height' : $cfg['config']['height']) . ':' . $cfg['config']['maxheight'] . 'px;' : '') . 'overflow:' . $cfg['config']['overflow'] . ';text-overflow:ellipsis;white-space:nowrap;"';
    }
    echo '>';
    // if header or frame and can collaps?
    if (!empty($cfg['config']['collapse']) && $cfg['config']['visuals']['header'] != 'none') {
        $tmp = '
		var ' . $IDtype . ' = new smc_Toggle({
		bToggleEnabled: true,
		bCurrentlyCollapsed: ' . (empty($options['collapse' . $IDtype]) ? 'false' : 'true') . ',
		aSwappableContainers: [
			\'upshrink_' . $IDtype . '\'
		],
		aSwapImages: [
			{
				sId: \'upshrink_' . $IDtype . '_Img\',';
        if ($context['pmx']['settings']['shrinkimages'] == '0') {
            $tmp .= '
				srcCollapsed: \'' . $context['pmx_img_colapse'] . '\',
				altCollapsed: ' . JavaScriptEscape($txt['pmx_expand'] . $blocktitle) . ',';
        } else {
            $tmp .= '
				altCollapsed: ' . JavaScriptEscape($txt['pmx_expand'] . $blocktitle) . ',';
        }
        if ($context['pmx']['settings']['shrinkimages'] == '0') {
            $tmp .= '
				srcExpanded: \'' . $context['pmx_img_expand'] . '\',
				altExpanded: ' . JavaScriptEscape($txt['pmx_collapse'] . $blocktitle) . '
			}';
        } else {
            $tmp .= '
				altExpanded: ' . JavaScriptEscape($txt['pmx_collapse'] . $blocktitle) . '
			}';
        }
        $tmp .= '
		],
		oCookieOptions: {
			bUseCookie: true,
			sCookieName: \'' . 'pmx_upshr' . $IDtype . '\',
			sCookieValue: \'' . $options['collapse' . $IDtype] . '\'
		}
	});';
        addInlineJavascript("\t" . str_replace("\n", "\n\t", PortaMx_compressJS($tmp)), true);
        unset($tmp);
    }
}
 /**
  * The Contructor.
  * Saved the config and checks the visiblity access.
  * If access true, the block css file is loaded if exist.
  */
 function PortaMxC_Blocks($blockconfig, &$visible)
 {
     global $context, $modSettings, $maintenance;
     // load the config
     if (isset($blockconfig['config'])) {
         $blockconfig['config'] = unserialize($blockconfig['config']);
     }
     $this->cfg = $blockconfig;
     $visible = !empty($this->cfg['active']);
     // check if ecl set
     $visible = empty($this->cfg['config']['check_ecl']) || !empty($this->cfg['config']['check_ecl']) && pmx_checkECL_Cookie(!empty($this->cfg['config']['check_eclbots']));
     if (!empty($visible)) {
         // hide on maintenance?
         if (!empty($maintenance) && !empty($this->cfg['config']['maintenance_mode'])) {
             $visible = false;
         }
         if (isset($this->cfg['config']['static_block'])) {
             $this->cfg['static_block'] = $this->cfg['config']['static_block'];
         }
         $this->startpage = 0;
         $this->inBlockCall = $this->cfg['side'] == 'bib';
         $this->cfg['uniID'] = 'blk' . $this->cfg['id'] . (!empty($this->inBlockCall) ? '-0' : '');
         // set the cache_key, cache time and trigger
         $this->cache_key = $this->cfg['blocktype'] . $this->cfg['id'];
         if (in_array($this->cfg['blocktype'], array_keys($context['pmx']['cache']['blocks']))) {
             $this->cache_mode = $context['pmx']['cache']['blocks'][$this->cfg['blocktype']]['mode'];
             $this->cache_time = $context['pmx']['cache']['blocks'][$this->cfg['blocktype']]['time'];
             if ($context['pmx']['cache']['blocks'][$this->cfg['blocktype']]['trigger'] == 'default') {
                 $this->cache_trigger = $context['pmx']['cache']['default']['trigger'];
             } else {
                 $this->cache_trigger = $context['pmx']['cache']['blocks'][$this->cfg['blocktype']]['trigger'];
             }
             // call cache trigger
             $this->cache_status = $this->pmxc_checkCacheStatus();
             if (!empty($this->cache_status['action'])) {
                 $visible = false;
             }
         } else {
             $this->cache_mode = false;
             $this->cache_time = 3600;
             $this->cache_trigger = '';
         }
         // check the block visible access if not a BIB block ($this->inBlockCall = true)
         if ($visible && empty($this->inBlockCall)) {
             // check group access only, if we not in admin section
             if (isset($_GET['area']) != 'pmx_blocks') {
                 if (isset($this->cfg['inherit_acs'])) {
                     $visible = !empty($this->cfg['inherit_acs']) || allowPmxGroup($this->cfg['acsgrp']);
                 } else {
                     $visible = allowPmxGroup($this->cfg['acsgrp']);
                 }
             }
             // Show "Home - Community" Buttons?
             if ($visible && $context['pmx']['settings']['frontpage'] != 'none' && $this->cfg['side'] == 'front') {
                 $context['pmx']['showhome'] += 1;
             }
             // hide block on request?
             if (!empty($context['pmx']['pageReq']) && $this->cfg['side'] == 'front' && $this->cfg['config']['frontplace'] == 'hide') {
                 $visible = false;
             }
             // disable frontpage blocks before init if the frontpage not shown
             if ($visible && $this->cfg['side'] == 'front' && empty($context['pmx']['pageReq']) && !empty($_GET)) {
                 $visible = false;
             }
             // hide frontblock on pagerequest?
             if ($visible && $this->cfg['side'] == 'front' && array_key_exists('spage', $context['pmx']['pageReq'])) {
                 $visible = empty($this->cfg['config']['frontplace']) || !empty($this->cfg['config']['frontplace']) && $this->cfg['config']['frontplace'] != 'hide';
             }
             // check page request
             if ($visible && $this->cfg['side'] == 'pages') {
                 $visible = !empty($context['pmx']['pageReq']) || empty($context['pmx']['forumReq']);
                 if (!empty($this->cfg['config']['static_block']) || !in_array($this->cfg['blocktype'], array('article', 'category'))) {
                     $this->cfg['config']['ext_opts']['pmxcust'] .= empty($this->cfg['config']['ext_opts']['pmxcust']) ? '@' : '';
                 }
             }
             // check dynamic visibility options
             if ($visible && !empty($this->cfg['config']['ext_opts'])) {
                 // check mobile / desktop devices
                 if (!empty($this->cfg['config']['ext_opts']['device'])) {
                     if (!empty($modSettings['pmx_isMobile']) && $this->cfg['config']['ext_opts']['device'] != '1') {
                         $visible = false;
                     }
                     if (empty($modSettings['pmx_isMobile']) && $this->cfg['config']['ext_opts']['device'] != '2') {
                         $visible = false;
                     }
                 }
                 // continue on other visibility options
                 if ($visible) {
                     $visible = pmx_checkExtOpts(true, $this->cfg['config']['ext_opts'], isset($this->cfg['config']['pagename']) ? $this->cfg['config']['pagename'] : '');
                 }
             }
             // continue if the block visible
             if ($visible) {
                 // if Page block and have a frontpage switch?
                 if (empty($context['pmx']['forumReq']) && $this->cfg['side'] == 'pages' && !empty($this->cfg['config']['frontmode'])) {
                     $context['pmx']['settings']['frontpage'] = $this->cfg['config']['frontmode'];
                 }
                 // check block display on frontpage mode
                 if (!empty($this->cfg['config']['frontview']) && !in_array($this->cfg['side'], array('front', 'pages'))) {
                     $visible = empty($context['pmx']['forumReq']) && $this->cfg['config']['frontview'] == $context['pmx']['settings']['frontpage'];
                 }
             }
         } else {
             if (!empty($visible)) {
                 $visible = pmx_checkExtOpts(true, $this->cfg['config']['ext_opts'], $this->cfg['config']['pagename']);
             }
         }
         // if visible check for a custom cssfile
         if (!empty($visible)) {
             $this->getCustomCSS($this->cfg);
         }
         if (!empty($visible) && $this->cfg['side'] == 'pages' && array_key_exists('spage', $context['pmx']['pageReq'])) {
             $context['pmx']['pagenames']['spage'] = $this->getUserTitle();
             if (empty($context['pmx']['pagenames']['spage'])) {
                 $context['pmx']['pagenames']['spage'] = htmlspecialchars($this->cfg['config']['pagename'], ENT_QUOTES);
             }
         }
     }
     $this->visible = $visible;
 }
    /**
     * InitContent.
     * Checks the cache status and create the content.
     */
    function pmxc_InitContent()
    {
        global $context, $smcFunc, $pmxCacheFunc;
        // if visible init the content
        if ($this->visible) {
            // called from static article block?
            if (!empty($this->cfg['config']['static_block'])) {
                $this->cfg['name'] = $this->cfg['config']['settings']['article'];
                $this->cfg['blocktype'] = 'artblock';
                if ($this->cfg['config']['settings']['usedframe'] == 'article') {
                    $this->cfg['config']['skip_outerframe'] = true;
                }
                $this->cfg['config']['visuals']['bodytext'] = '';
                if (!empty($this->cfg['cache'])) {
                    $this->articles = $pmxCacheFunc['get']($this->cache_key, $this->cache_mode);
                } else {
                    $this->articles = array();
                }
                $this->printID = 'artblk' . $this->cfg['id'];
            } else {
                $this->cache_key = 'req' . $this->cache_key;
                $this->articles = array();
                $this->cfg['config']['skip_outerframe'] = true;
                $this->cfg['config']['settings']['usedframe'] = 'article';
                $this->printID = 'artreq' . $this->cfg['id'];
            }
            // get the articles
            if (empty($this->articles)) {
                if (!empty($this->cfg['name'])) {
                    $request = $smcFunc['db_query']('', '
						SELECT a.id, a.name, a.acsgrp, a.ctype, a.config, a.owner, a.active, a.created, a.updated, a.content, CASE WHEN m.real_name = {string:empty} THEN m.member_name ELSE m.real_name END AS mem_name
						FROM {db_prefix}portamx_articles AS a
						LEFT JOIN {db_prefix}members AS m ON (a.owner = m.id_member)
						WHERE a.name = {string:art} AND a.active > 0 AND a.approved > 0
						ORDER BY a.id', array('art' => $this->cfg['name'], 'empty' => ''));
                    if ($smcFunc['db_num_rows']($request) > 0) {
                        while ($row = $smcFunc['db_fetch_assoc']($request)) {
                            $row['config'] = unserialize($row['config']);
                            if (!empty($this->cfg['config']['settings']['inherit_acs'])) {
                                $row['acsgrp'] = $this->cfg['acsgrp'];
                            }
                            if (allowPmxGroup($row['acsgrp'])) {
                                // have a custom cssfile, load
                                if (!empty($row['config']['cssfile'])) {
                                    $this->getCustomCSS($row);
                                } else {
                                    $row['customclass'] = '';
                                }
                                $row['side'] = $this->cfg['side'];
                                $row['blocktype'] = !empty($this->cfg['config']['static_block']) ? 'static_article' : 'article';
                                $row['member_name'] = $row['mem_name'];
                                $this->articles[] = $row;
                            }
                        }
                        $smcFunc['db_free_result']($request);
                    }
                    // static block?
                    if (!empty($this->cfg['config']['static_block']) && !empty($this->cfg['cache'])) {
                        $pmxCacheFunc['put']($this->cache_key, $this->articles, $this->cache_time, $this->cache_mode);
                    }
                }
            }
            // articles found?
            if (count($this->articles) > 0) {
                // ecl check
                foreach ($this->articles as $aKey => $aVal) {
                    if (!empty($this->articles[$aKey]['config']['check_ecl']) && !pmx_checkECL_Cookie(!empty($this->articles[$aKey]['config']['check_eclbots']))) {
                        unset($this->articles[$aKey]);
                    } else {
                        // static article block ?
                        if (!empty($this->cfg['config']['static_block'])) {
                            $this->cfg['blocktype'] = 'artblock';
                            if ($this->cfg['config']['settings']['usedframe'] == 'block') {
                                $this->articles[$aKey]['config']['visuals'] = $this->cfg['config']['visuals'];
                                $this->articles[$aKey]['config']['cssfile'] = $this->cfg['config']['cssfile'];
                            }
                        } else {
                            $context['pmx']['pagenames']['art'] = $this->getUserTitle($this->articles[0], $this->articles[0]['name']);
                        }
                    }
                }
            }
            $this->visible = count($this->articles) > 0;
            if (!empty($this->visible)) {
                // check for special php content
                foreach ($this->articles as $art) {
                    if ($art['ctype'] == 'php' && preg_match('~\\[\\?pmx_initphp(.*)pmx_initphp\\?\\]~is', $art['content'], $match)) {
                        eval($match[1]);
                    }
                }
            }
        }
        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);
        }
    }
}
/**
* Add menu to MenuContext
* Called from hook integrate_menu_buttons
**/
function PortaMx_MenuContext(&$menudata)
{
    global $txt, $context, $modSettings, $scripturl, $boarddir;
    if (empty($modSettings['pmxportal_disabled'])) {
        // Init the Portal if not loaded
        if (!defined('PortaMx')) {
            PortaMx(true);
        }
        // add community button after 'home'
        $fnd = array_search('home', array_keys($menudata)) + 1;
        if (!empty($context['pmx']['showhome'])) {
            $menudata = array_merge(array_slice($menudata, 0, $fnd), array('community' => array('title' => $txt['forum'], 'href' => $scripturl . '?action=community', 'icon' => '<span class="generic_icons community"></span>', 'active_button' => false, 'sub_buttons' => array())), array_slice($menudata, $fnd, count($menudata) - $fnd));
            $fnd++;
        }
        // add download button if enabled and accessible
        $dlact = array(0 => '', 1 => '');
        $dlactErr = array(0 => '', 1 => '');
        $dlaccess = isset($context['pmx']['settings']['dl_access']) ? $context['pmx']['settings']['dl_access'] : '';
        if (allowPmxGroup($dlaccess) && !empty($context['pmx']['settings']['download']) && preg_match('/(p:|c:|a:|)(.*)$/i', $context['pmx']['settings']['dl_action'], $match) > 0) {
            if ($match[1] == 'a:') {
                $dlact = array(0 => 'art', 1 => $match[2]);
            } elseif ($match[1] == 'c:') {
                $dlact = array(0 => 'cat', 1 => $match[2]);
            } elseif ($match[1] == 'p:') {
                $dlact = array(0 => 'spage', 1 => $match[2]);
            } else {
                $dlact = array(0 => 'action', 1 => $match[2]);
            }
            if (!empty($_REQUEST['pmxerror']) && in_array($_REQUEST['pmxerror'], array('acs', 'fail'))) {
                $dlactErr = array(0 => 'pmxerror', 1 => $_REQUEST['pmxerror']);
            }
            $menudata = array_merge(array_slice($menudata, 0, $fnd), array('download' => array('title' => $txt['download'], 'href' => $scripturl . '?' . $dlact[0] . '=' . $dlact[1], 'icon' => '<span class="generic_icons download"></span>', 'active_button' => false, 'sub_buttons' => array())), array_slice($menudata, $fnd, count($menudata) - $fnd));
            if (isset($_REQUEST[$dlact[0]]) && $_REQUEST[$dlact[0]] == $dlact[1] || isset($_REQUEST[$dlactErr[0]]) && $_REQUEST[$dlactErr[0]] == $dlactErr[1]) {
                $context['current_action'] = 'download';
            }
        }
        // add admin submenu before 'featuresettings'
        if (!empty($context['allow_admin'])) {
            $curract = pmx_http_build_query($_GET);
            $fnd = array_search('featuresettings', array_keys($menudata['admin']['sub_buttons']));
            $menudata['admin']['sub_buttons'] = array_merge(array_slice($menudata['admin']['sub_buttons'], 0, $fnd), array('pmx_center' => array('title' => $txt['pmx_extension'], 'href' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'show' => $context['allow_admin'], 'sub_buttons' => array('pmxcenter' => array('title' => $txt['pmx_admincenter'], 'href' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'show' => $context['allow_admin']), 'pmxsettings' => array('title' => $txt['pmx_settings'], 'href' => $scripturl . '?action=admin;area=pmx_settings;sa=globals;' . $context['session_var'] . '=' . $context['session_id'], 'show' => $context['allow_admin']), 'pmxblocks' => array('title' => $txt['pmx_blocks'], 'href' => $scripturl . '?action=admin;area=pmx_blocks;sa=all;' . $context['session_var'] . '=' . $context['session_id'], 'show' => $context['allow_admin']), 'pmxcategories' => array('title' => $txt['pmx_categories'], 'href' => $scripturl . '?action=admin;area=pmx_categories;' . $context['session_var'] . '=' . $context['session_id'], 'show' => $context['allow_admin']), 'pmxarticles' => array('title' => $txt['pmx_articles'], 'href' => $scripturl . '?action=admin;area=pmx_articles;' . $context['session_var'] . '=' . $context['session_id'], 'show' => $context['allow_admin']), 'pmxsefengine' => array('title' => $txt['pmx_sefengine'], 'href' => $scripturl . '?action=admin;area=pmx_sefengine;' . $context['session_var'] . '=' . $context['session_id'], 'show' => $context['allow_admin']), 'pmxlanguages' => array('title' => $txt['pmx_languages'], 'href' => $scripturl . '?action=admin;area=pmx_languages;' . $context['session_var'] . '=' . $context['session_id'], 'show' => $context['allow_admin']), 'pmxcache' => array('title' => $txt['pmx_cache'], 'href' => $scripturl . '?action=admin;area=pmx_cache;' . $context['session_var'] . '=' . $context['session_id'], 'show' => $context['allow_admin'] && is_dir($boarddir . '/cachepmx'))))), array_slice($menudata['admin']['sub_buttons'], $fnd, count($menudata['admin']['sub_buttons']) - $fnd));
            foreach ($menudata['admin']['sub_buttons']['pmx_center']['sub_buttons'] as $button => $value) {
                if (empty($value['show'])) {
                    unset($menudata['admin']['sub_buttons']['pmx_center']['sub_buttons'][$button]);
                }
            }
        } else {
            if (allowedTo('profile_view_own') && allowPmx('pmx_admin, pmx_blocks, pmx_articles, pmx_create', true)) {
                $fnd = array_search('mlist', array_keys($menudata));
                $menudata = array_merge(array_slice($menudata, 0, $fnd), array('portamx' => array('title' => $txt['pmx_extension'], 'icon' => '<span class="generic_icons adm_center"></span>', 'href' => '', 'active_button' => false, 'sub_buttons' => array('pmxcenter' => array('title' => $txt['pmx_admincenter'], 'href' => $scripturl . '?action=portamx;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'show' => allowPmx('pmx_admin', true)), 'pmxsettings' => array('title' => $txt['pmx_settings'], 'href' => $scripturl . '?action=portamx;area=pmx_settings;' . $context['session_var'] . '=' . $context['session_id'], 'show' => allowPmx('pmx_admin', true)), 'pmxblocks' => array('title' => $txt['pmx_blocks'], 'href' => $scripturl . '?action=portamx;area=pmx_blocks;' . $context['session_var'] . '=' . $context['session_id'], 'show' => allowPmx('pmx_admin, pmx_blocks', true)), 'pmxcategories' => array('title' => $txt['pmx_categories'], 'href' => $scripturl . '?action=portamx;area=pmx_categories;' . $context['session_var'] . '=' . $context['session_id'], 'show' => allowPmx('pmx_admin', true)), 'pmxarticles' => array('title' => $txt['pmx_articles'], 'href' => $scripturl . '?action=portamx;area=pmx_articles;' . $context['session_var'] . '=' . $context['session_id'], 'show' => allowPmx('pmx_admin, pmx_articles, pmx_create', true)), 'pmxsefengine' => array('title' => $txt['pmx_sefengine'], 'href' => $scripturl . '?action=portamx;area=pmx_sefengine;' . $context['session_var'] . '=' . $context['session_id'], 'show' => allowPmx('pmx_admin', true)), 'pmxcache' => array('title' => $txt['pmx_cache'], 'href' => $scripturl . '?action=portamx;area=pmx_cache;' . $context['session_var'] . '=' . $context['session_id'], 'show' => allowPmx('pmx_admin, pmx_blocks, pmx_articles, pmx_create', true) && is_dir($boarddir . '/cachepmx'))))), array_slice($menudata, $fnd, count($menudata) - $fnd));
                foreach ($menudata['portamx']['sub_buttons'] as $button => $value) {
                    if (empty($value['show'])) {
                        unset($menudata['portamx']['sub_buttons'][$button]);
                    }
                }
            }
        }
        /**
         * Highlight the active button
         **/
        // SimpleDesk stand alone mode ?
        if (!empty($context['pmx']['showhome'])) {
            if (isset($_REQUEST['board']) || isset($_REQUEST['topic'])) {
                $context['current_action'] = 'community';
            } elseif (!empty($_REQUEST['action']) && in_array($_REQUEST['action'], array('community', 'recent', 'unreadreplies', 'unread', 'who', 'collapse'))) {
                $context['current_action'] = 'community';
            }
        } elseif (!empty($context['pmx']['showhome'])) {
            if (empty($_REQUEST['action']) && empty($_REQUEST['board']) && empty($_REQUEST['topic'])) {
                $context['current_action'] = 'home';
            }
        }
        // Highlight the profile button on this..
        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'portamx' && allowPmx('pmx_admin, pmx_blocks, pmx_articles, pmx_create', true)) {
            $context['current_action'] = 'portamx';
        }
    }
}