Beispiel #1
0
function EditorMain()
{
    global $context, $smcFunc;
    checkSession('get');
    if (!isset($_REQUEST['view']) || !isset($_REQUEST['message'])) {
        fatal_lang_error('no_access', false);
    }
    $context['sub_template'] = 'sendbody';
    $context['view'] = (int) $_REQUEST['view'];
    // Return the right thing for the mode.
    if ($context['view']) {
        $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '<', '#smgt#' => '>', '#smamp#' => '&'));
        $context['message'] = bbc_to_html($_REQUEST['message']);
    } else {
        $_REQUEST['message'] = un_htmlspecialchars($_REQUEST['message']);
        $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '<', '#smgt#' => '>', '#smamp#' => '&'));
        $context['message'] = html_to_bbc($_REQUEST['message']);
    }
    $context['message'] = commonAPI::htmlspecialchars($context['message']);
}
Beispiel #2
0
function EditPost2()
{
    global $txt, $smcFunc, $sourcedir;
    checkSession('post');
    // Get the ID
    $id = (int) $_REQUEST['id'];
    if (empty($id)) {
        fatal_error($txt['postscheduler_nopostselected'], false);
    }
    // If we came from WYSIWYG then turn it back into BBC regardless.
    if (!empty($_REQUEST['message_mode']) && isset($_REQUEST['message'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_REQUEST['message'] = html_to_bbc($_REQUEST['message']);
        // We need to unhtml it now as it gets done shortly.
        $_REQUEST['message'] = un_htmlspecialchars($_REQUEST['message']);
    }
    $subject = $smcFunc['htmlspecialchars']($_REQUEST['subject'], ENT_QUOTES);
    $boardselect = (int) $_REQUEST['boardselect'];
    $postername = str_replace('"', '', $_REQUEST['postername']);
    $postername = str_replace("'", '', $postername);
    $postername = str_replace('\\', '', $postername);
    $postername = $smcFunc['htmlspecialchars']($postername, ENT_QUOTES);
    $msgicon = $smcFunc['htmlspecialchars']($_REQUEST['msgicon'], ENT_QUOTES);
    $message = $smcFunc['htmlspecialchars']($_REQUEST['message'], ENT_QUOTES);
    $topicid = (int) $_REQUEST['topicid'];
    if ($subject == '') {
        fatal_error($txt['postscheduler_err_subject'], false);
    }
    if ($postername == '') {
        fatal_error($txt['postscheduler_err_postername'], false);
    }
    if ($boardselect == 0) {
        fatal_error($txt['postscheduler_err_forum'], false);
    }
    if ($message == '') {
        fatal_error($txt['postscheduler_err_message'], false);
    }
    $topiclocked = isset($_REQUEST['topiclocked']) ? 1 : 0;
    $month = (int) $_REQUEST['month'];
    $day = (int) $_REQUEST['day'];
    $year = (int) $_REQUEST['year'];
    $hour = (int) $_REQUEST['hour'];
    $minute = (int) $_REQUEST['minute'];
    $ampm = $_REQUEST['ampm'];
    $minute = str_pad($minute, 2, "0", STR_PAD_LEFT);
    $time_in_24_hour_format = DATE("H", STRTOTIME("{$hour}:{$minute} {$ampm}"));
    if (!empty($month) && !empty($day) && !empty($year)) {
        $post_time = mktime($time_in_24_hour_format, $minute, 0, $month, $day, $year);
    } else {
        fatal_error($txt['postscheduler_err_date'], false);
    }
    // Lookup the Memeber ID of the postername
    $memid = 0;
    $dbresult = $smcFunc['db_query']('', "\n\tSELECT \n\t\treal_name, ID_MEMBER \n\tFROM {db_prefix}members \n\tWHERE real_name = '{$postername}' OR member_name = '{$postername}'  LIMIT 1");
    $row = $smcFunc['db_fetch_assoc']($dbresult);
    $smcFunc['db_free_result']($dbresult);
    if ($smcFunc['db_affected_rows']() != 0) {
        $memid = $row['ID_MEMBER'];
    }
    $smcFunc['db_query']('', "\n\t\tUPDATE {db_prefix}postscheduler \n\t\tSET \n\t\t\tID_BOARD = {$boardselect}, subject = '{$subject}', postername  = '{$postername}', ID_MEMBER = {$memid}, locked = '{$topiclocked}', \n\t\t\tbody = '{$message}',id_topic = '{$topicid}',post_time = '{$post_time}',\n\t\t\tmsgicon  = '{$msgicon}'\n\n\t    WHERE ID_POST = {$id} LIMIT 1");
    // Redirect to the Admin
    redirectexit('action=admin;area=postscheduler;sa=admin');
}
function TPortalDLAdmin()
{
    global $txt, $scripturl, $boarddir, $boardurl, $smcFunc, $context, $settings, $sourcedir;
    // check permissions
    if (isset($_POST['dl_useredit'])) {
        checkSession('post');
    } else {
        isAllowedTo('tp_dlmanager');
    }
    // add visual options to this section
    $dl_visual = explode(',', $context['TPortal']['dl_visual_options']);
    $dv = array('left', 'right', 'center', 'top', 'bottom', 'lower');
    foreach ($dv as $v => $val) {
        if (in_array($val, $dl_visual)) {
            $context['TPortal'][$val . 'panel'] = '1';
            $context['TPortal']['dl_' . $val] = '1';
        } else {
            $context['TPortal'][$val . 'panel'] = '0';
        }
    }
    if (in_array('showtop', $dl_visual)) {
        $context['TPortal']['showtop'] = true;
        $context['TPortal']['dl_top'] = true;
    } else {
        $context['TPortal']['showtop'] = false;
    }
    if ($context['TPortal']['hidebars_admin_only'] == '1') {
        tp_hidebars();
    }
    // fetch membergroups so we can quickly set permissions
    // dlmanager, dlupload, dlcreatetopic
    $context['TPortal']['perm_all_groups'] = get_grps();
    $context['TPortal']['perm_groups'] = tp_fetchpermissions(array('tp_dlmanager', 'tp_dlupload', 'tp_dlcreatetopic'));
    $context['TPortal']['boards'] = tp_fetchboards();
    $context['TPortal']['all_dlitems'] = array();
    $request = $smcFunc['db_query']('', '
		SELECT id, name	FROM {db_prefix}tp_dlmanager
		WHERE type = {string:type}
		ORDER BY name ASC', array('type' => 'dlitem'));
    if ($smcFunc['db_num_rows']($request) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $context['TPortal']['all_dlitems'][] = array('id' => $row['id'], 'name' => $row['name']);
        }
        $smcFunc['db_free_result']($request);
    }
    // Add in BBC editor before we call in template so the headers are there
    if ($context['TPortal']['dl_wysiwyg'] == 'bbc') {
        if ($context['TPortal']['dlsub'] == 'adminaddcat') {
            $context['TPortal']['editor_id'] = 'newdladmin_text';
            TP_prebbcbox($context['TPortal']['editor_id']);
        } else {
            $context['TPortal']['editor_id'] = 'tp_dl_introtext';
            TP_prebbcbox($context['TPortal']['editor_id'], $context['TPortal']['dl_introtext']);
        }
    }
    // any items from the ftp screen?
    if (!empty($_POST['ftpdlsend'])) {
        // new category?
        if (!empty($_POST['assign-ftp-newcat'])) {
            $newcat = true;
            $newcatname = $_POST['assign-ftp-newcat'];
            if (isset($_POST['assign-ftp-cat']) && $_POST['assign-ftp-cat'] > 0) {
                $newcatparent = $_POST['assign-ftp-cat'];
            } else {
                $newcatparent = 0;
            }
            if ($newcatname == '') {
                $newcatname = '-no name-';
            }
        } else {
            $newcat = false;
            $newcatname = '';
            $newcatnow = $_POST['assign-ftp-cat'];
            $newcatparent = 0;
        }
        // if new category create it first.
        if ($newcat) {
            $request = $smcFunc['db_insert']('INSERT', '{db_prefix}tp_dlmanager', array('name' => 'string', 'description' => 'string', 'icon' => 'string', 'category' => 'int', 'type' => 'string', 'downloads' => 'int', 'views' => 'int', 'file' => 'string', 'created' => 'int', 'last_access' => 'int', 'filesize' => 'int', 'parent' => 'int', 'access' => 'string', 'link' => 'string', 'author_id' => 'int', 'screenshot' => 'string', 'rating' => 'string', 'voters' => 'string', 'subitem' => 'int'), array($newcatname, '', '', 0, 'dlcat', 0, 0, '', 0, 0, 0, $newcatparent, '', '', $context['user']['id'], '', '', '', 0), array('id'));
            $newcatnow = $smcFunc['db_insert_id']($request);
        }
        // now go through each file and put it into the table.
        foreach ($_POST as $what => $value) {
            if (substr($what, 0, 19) == 'assign-ftp-checkbox') {
                $name = $value;
                $now = time();
                $fsize = filesize($boarddir . '/tp-downloads/' . $value);
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_dlmanager', array('name' => 'string', 'description' => 'string', 'icon' => 'string', 'category' => 'int', 'type' => 'string', 'downloads' => 'int', 'views' => 'int', 'file' => 'string', 'created' => 'int', 'last_access' => 'int', 'filesize' => 'int', 'parent' => 'int', 'access' => 'string', 'link' => 'string', 'author_id' => 'int', 'screenshot' => 'string', 'rating' => 'string', 'voters' => 'string', 'subitem' => 'int'), array($name, '', '', $newcatnow, 'dlitem', 1, 1, $value, $now, $now, $fsize, 0, '', '', $context['user']['id'], '', '', '', 0), array('id'));
            }
        }
        // done, set a value to make member aware of assigned category
        redirectexit('action=tpmod;dl=adminftp;ftpcat=' . $newcatnow);
    }
    // check for new category
    if (!empty($_POST['newdlsend'])) {
        // get the items
        $name = strip_tags($_POST['newdladmin_name']);
        // no html here
        if (empty($name)) {
            $name = $txt['tp-dlnotitle'];
        }
        $text = $_POST['newdladmin_text'];
        $parent = $_POST['newdladmin_parent'];
        $icon = $boardurl . '/tp-downloads/icons/' . $_POST['newdladmin_icon'];
        // special case, the access
        $dlgrp = array();
        foreach ($_POST as $what => $value) {
            if (substr($what, 0, 16) == 'newdladmin_group') {
                $vv = substr($what, 16);
                if ($vv != '-2') {
                    $dlgrp[] = $vv;
                }
            }
        }
        $access = implode(',', $dlgrp);
        // insert the category
        $request = $smcFunc['db_insert']('INSERT', '{db_prefix}tp_dlmanager', array('name' => 'string', 'description' => 'string', 'icon' => 'string', 'category' => 'int', 'type' => 'string', 'downloads' => 'int', 'views' => 'int', 'file' => 'string', 'created' => 'int', 'last_access' => 'int', 'filesize' => 'int', 'parent' => 'int', 'access' => 'string', 'link' => 'string', 'author_id' => 'int', 'screenshot' => 'string', 'rating' => 'string', 'voters' => 'string', 'subitem' => 'int'), array($name, $text, $icon, 0, 'dlcat', 0, 0, '', 0, 0, 0, $parent, $access, '', $context['user']['id'], '', '', '', 0), array('id'));
        $newcat = $smcFunc['db_insert_id']($request);
        redirectexit('action=tpmod;dl=admineditcat' . $newcat);
    }
    $myid = 0;
    // check if tag links are present
    if (isset($_POST['dladmin_itemtags'])) {
        $itemid = $_POST['dladmin_itemtags'];
        // get title
        $request = $smcFunc['db_query']('', '
			SELECT name FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:item} LIMIT 1', array('item' => $itemid));
        $title = $smcFunc['db_fetch_row']($request);
        // remove old ones first
        $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}tp_variables 
			WHERE value3 = {string:val3} 
			AND subtype2 = {int:sub}', array('val3' => 'dladmin_itemtags', 'sub' => $itemid));
        $alltags = array();
        foreach ($_POST as $what => $value) {
            // a tag from edit items
            if (substr($what, 0, 17) == 'dladmin_itemtags_') {
                $tag = substr($what, 17);
                $itemid = $value;
                // insert new one
                $href = '?action=tpmod;dl=item' . $itemid;
                $tg = '<span style="background: url(' . $settings['tp_images_url'] . '/glyph_download.png) no-repeat;" class="taglink">' . $title[0] . '</span>';
                if (!empty($tag)) {
                    $smcFunc['db_query']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype' => 'string', 'value7' => 'string', 'value8' => 'string', 'subtype2' => 'int'), array($href, $tg, 'dladmin_itemtags', '', 0, $tag, '', '', $itemid), array('id'));
                    $alltags[] = $tag;
                }
            }
        }
        $tg = implode(',', $alltags);
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}tp_dlmanager 
			SET global_tag = {string:tag} 
			WHERE id = {int:item}', array('tag' => $tg, 'item' => $itemid));
        $myid = $itemid;
        $go = 2;
        $newgo = 2;
    }
    // check if tag links are present -categories
    if (isset($_POST['dladmin_cattags'])) {
        $itemid = $_POST['dladmin_cattags'];
        // get title
        $request = $smcFunc['db_query']('', '
			SELECT name FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:item} LIMIT 1', array('item' => $itemid));
        $title = $smcFunc['db_fetch_row']($request);
        // remove old ones first
        $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}tp_variables 
			WHERE value3 = {string:val3} 
			AND subtype2 = {int:sub}', array('val3' => 'dladmin_cattags', 'sub' => $itemid));
        foreach ($_POST as $what => $value) {
            // a tag from edit category
            if (substr($what, 0, 16) == 'dladmin_cattags_') {
                $tag = substr($what, 16);
                $itemid = $value;
                // insert new one
                $href = '?action=tpmod;dl=cat' . $itemid;
                $title = $title[0] . ' [' . strtolower($txt['tp-downloads']) . '] ';
                $smcFunc['db_query']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype' => 'string', 'value7' => 'string', 'value8' => 'string', 'subtype2' => 'int'), array($href, $title, 'dladmin_cattags', '', 0, $tag, '', '', $itemid), array('id'));
            }
        }
        $myid = $itemid;
        $go = 3;
        $newgo = 3;
    }
    // check for access value
    if (!empty($_POST['dlsend'])) {
        $admgrp = array();
        $groupset = false;
        $dlgrp = array();
        $dlset = false;
        $visual = array();
        $visualset = false;
        $creategrp = array();
        $dlmanager_grp = array();
        $dlupload_grp = array();
        $dlcreatetopic_grp = array();
        // Our settings array to send to updateTPSettings();
        $changeArray = array();
        foreach ($_POST as $what => $value) {
            if (substr($what, 0, 13) == 'dladmin_group') {
                $val = substr($what, 13);
                if ($val != '-2') {
                    $admgrp[] = $val;
                }
                $groupset = true;
                $id = $value;
            } elseif (substr($what, 0, 8) == 'tp_group') {
                if ($value != '-2') {
                    $dlgrp[] = $value;
                }
                $dlset = true;
            } elseif (substr($what, 0, 20) == 'tp_dl_visual_options') {
                if ($value != 'not') {
                    $visual[] = $value;
                }
                $visualset = true;
            } elseif (substr($what, 0, 11) == 'tp_dlboards') {
                $creategrp[] = $value;
            }
        }
        if ($groupset) {
            $dlaccess = implode(',', $admgrp);
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET access = {string:access} 
				WHERE id = {int:item}', array('access' => $dlaccess, 'item' => $id));
        }
        if (!empty($_POST['dlsettings'])) {
            $changeArray['dl_createtopic_boards'] = implode(',', $creategrp);
        }
        if ($dlset) {
            $changeArray['dl_approve_groups'] = implode(',', $dlgrp);
        }
        if ($visualset) {
            $changeArray['dl_visual_options'] = implode(',', $visual);
        }
        $go = 0;
        if (!empty($_FILES['qup_dladmin_text']['tmp_name']) && (file_exists($_FILES['qup_dladmin_text']['tmp_name']) || is_uploaded_file($_FILES['qup_dladmin_text']['tmp_name']))) {
            $name = TPuploadpicture('qup_dladmin_text', $context['user']['id'] . 'uid');
            tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
        }
        if (!empty($_FILES['qup_blockbody']['tmp_name']) && (file_exists($_FILES['qup_dladmin_text']['tmp_name']) || is_uploaded_file($_FILES['qup_dladmin_text']['tmp_name']))) {
            $name = TPuploadpicture('qup_dladmin_text', $context['user']['id'] . 'uid');
            tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
        }
        // a screenshot from edit item screen?
        if (!empty($_FILES['tp_dluploadpic_edit']['tmp_name']) && (file_exists($_FILES['tp_dluploadpic_edit']['tmp_name']) || is_uploaded_file($_FILES['tp_dluploadpic_edit']['tmp_name']))) {
            $shot = true;
        } else {
            $shot = false;
        }
        if ($shot) {
            $sid = $_POST['tp_dluploadpic_editID'];
            $sfile = 'tp_dluploadpic_edit';
            $uid = $context['user']['id'] . 'uid';
            $dim = '1800';
            $suf = 'jpg,gif,png';
            $dest = 'tp-images/dlmanager';
            $sname = TPuploadpicture($sfile, $uid, $dim, $suf, $dest);
            $screenshot = $sname;
            tp_createthumb($dest . '/' . $sname, $context['TPortal']['dl_screenshotsize'][0], $context['TPortal']['dl_screenshotsize'][1], $dest . '/thumb/' . $sname);
            tp_createthumb($dest . '/' . $sname, $context['TPortal']['dl_screenshotsize'][2], $context['TPortal']['dl_screenshotsize'][3], $dest . '/listing/' . $sname);
            tp_createthumb($dest . '/' . $sname, $context['TPortal']['dl_screenshotsize'][4], $context['TPortal']['dl_screenshotsize'][5], $dest . '/single/' . $sname);
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET screenshot = {string:ss} 
				WHERE id = {int:item}', array('ss' => $screenshot, 'item' => $sid));
            $uploaded = true;
        } else {
            $screenshot = '';
            $uploaded = false;
        }
        if (isset($_POST['tp_dluploadpic_link']) && !$uploaded) {
            $sid = $_POST['tp_dluploadpic_editID'];
            $screenshot = $_POST['tp_dluploadpic_link'];
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET screenshot = {string:ss} 
				WHERE id = {int:item}', array('ss' => $screenshot, 'item' => $sid));
        } else {
            $screenshot = '';
        }
        // a new file uploaded?
        if (!empty($_FILES['tp_dluploadfile_edit']['tmp_name']) && is_uploaded_file($_FILES['tp_dluploadfile_edit']['tmp_name'])) {
            $shot = true;
        } else {
            $shot = false;
        }
        if ($shot) {
            $sid = $_POST['tp_dluploadfile_editID'];
            $shotname = $_FILES['tp_dluploadfile_edit']['name'];
            $sname = strtr($shotname, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ', 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy');
            $sname = strtr($sname, array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u'));
            $sname = preg_replace(array('/\\s/', '/[^\\w_\\.\\-]/'), array('_', ''), $sname);
            $sname = time() . $sname;
            // check the size
            $dlfilesize = filesize($_FILES['tp_dluploadfile_edit']['tmp_name']);
            if ($dlfilesize > 1000 * $context['TPortal']['dl_max_upload_size']) {
                unlink($_FILES['tp_dluploadfile_edit']['tmp_name']);
                $error = $txt['tp-dlmaxerror'] . ' ' . $context['TPortal']['dl_max_upload_size'] . ' Kb<br /><br />' . $txt['tp-dlmaxerror2'] . ': ' . ceil($dlfilesize / 1000) . ' Kb';
                fatal_error($error);
            }
            // check the extension
            $allowed = explode(',', $context['TPortal']['dl_allowed_types']);
            $match = false;
            foreach ($allowed as $extension => $value) {
                $ext = '.' . $value;
                $extlen = strlen($ext);
                if (substr($sname, strlen($sname) - $extlen, $extlen) == $ext) {
                    $match = true;
                }
            }
            if (!$match) {
                unlink($_FILES['tp_dluploadfile_edit']['tmp_name']);
                $error = $txt['tp-dlexterror'] . ':<b> <br />' . $context['TPortal']['dl_allowed_types'] . '</b><br /><br />' . $txt['tp-dlexterror2'] . ': <b>' . $sname . '</b>';
                fatal_error($error);
            }
            $success2 = move_uploaded_file($_FILES['tp_dluploadfile_edit']['tmp_name'], $boarddir . '/tp-downloads/' . $sname);
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET file = {string:file} 
				WHERE id = {int:item}', array('file' => $sname, 'item' => $sid));
            $new_upload = true;
            // update filesize as well
            $value = filesize($boarddir . '/tp-downloads/' . $sname);
            if (!is_numeric($value)) {
                $value = 0;
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET filesize = {int:size}
				WHERE id = {int:item}', array('size' => $value, 'item' => $sid));
            $myid = $sid;
            $go = 2;
        }
        // get all values from forms
        foreach ($_POST as $what => $value) {
            if (substr($what, 0, 12) == 'dladmin_name') {
                $id = substr($what, 12);
                // no html here
                $value = strip_tags($value);
                if (empty($value)) {
                    $value = '-no title-';
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET name = {string:name} 
					WHERE id = {int:item}', array('name' => $value, 'item' => $id));
            } elseif (substr($what, 0, 12) == 'dladmin_icon') {
                $id = substr($what, 12);
                if ($value != '') {
                    $val = $boardurl . '/tp-downloads/icons/' . $value;
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET icon = {string:icon} 
						WHERE id = {int:item}', array('icon' => $val, 'item' => $id));
                }
            } elseif (substr($what, 0, 12) == 'dladmin_text') {
                $id = substr($what, 12);
                if (is_numeric($id)) {
                    // If we came from WYSIWYG then turn it back into BBC regardless.
                    if (!empty($_REQUEST[$what . '_mode']) && isset($_REQUEST[$what])) {
                        require_once $sourcedir . '/Subs-Editor.php';
                        $_REQUEST[$what] = html_to_bbc($_REQUEST[$what]);
                        // We need to unhtml it now as it gets done shortly.
                        $_REQUEST[$what] = un_htmlspecialchars($_REQUEST[$what]);
                        // We need this for everything else.
                        $value = $_POST[$what] = $_REQUEST[$what];
                    }
                    if (isset($_POST['dladmin_text' . $id . '_pure']) && isset($_POST['dladmin_text' . $id . '_choice'])) {
                        if ($_POST['dladmin_text' . $id . '_choice'] == 1) {
                            $value = $_POST['dladmin_text' . $id];
                        } else {
                            $value = $_POST['dladmin_text' . $id . '_pure'];
                        }
                    }
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET description = {string:desc} 
						WHERE id = {int:item}', array('desc' => $value, 'item' => $id));
                }
            } elseif (substr($what, 0, 14) == 'dladmin_delete') {
                $id = substr($what, 14);
                $request = $smcFunc['db_query']('', '
						SELECT * FROM {db_prefix}tp_dlmanager 
						WHERE id = {int:item}', array('item' => $id));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_assoc']($request);
                    if ($row['type'] == 'dlitem') {
                        $category = $row['category'];
                        if ($category > 0) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_dlmanager 
									SET downloads = downloads - 1 
									WHERE id = {int:cat} LIMIT 1', array('cat' => $category));
                        }
                        // delete both screenshot and file
                        if (!empty($row['file']) && file_exists($boarddir . '/tp-downloads/' . $row['file'])) {
                            $succ = unlink($boarddir . '/tp-downloads/' . $row['file']);
                            if (!$succ) {
                                $err = $txt['tp-dlfilenotdel'] . ' (' . $row['file'] . ')';
                            }
                        }
                        if (!empty($row['screenshot']) && file_exists($boarddir . '/' . $row['screenshot'])) {
                            $succ2 = unlink($boarddir . '/' . $row['screenshot']);
                            if (!$succ2) {
                                $err .= '<br />' . $txt['tp-dlssnotdel'] . ' (' . $row['screenshot'] . ')';
                            }
                        }
                    }
                    $smcFunc['db_free_result']($request);
                }
                $smcFunc['db_query']('', '
					DELETE FROM {db_prefix}tp_dlmanager 
					WHERE id = {int:item}', array('item' => $id));
                if (isset($err)) {
                    fatal_error($err);
                }
                redirectexit('action=tpmod;dl=admincat' . $category);
            } elseif (substr($what, 0, 15) == 'dladmin_approve' && $value == 'ON') {
                $id = abs(substr($what, 15));
                $request = $smcFunc['db_query']('', '
					SELECT category FROM {db_prefix}tp_dlmanager 
					WHERE id = {int:item}', array('item' => $id));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_row']($request);
                    $newcat = abs($row[0]);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET category = {int:cat} 
						WHERE id = {int:item}', array('cat' => $newcat, 'item' => $id));
                    $smcFunc['db_query']('', '
						DELETE FROM {db_prefix}tp_variables 
						WHERE type = {string:type} 
						AND value5 = {int:val5}', array('type' => 'dl_not_approved', 'val5' => $id));
                    $smcFunc['db_free_result']($request);
                }
            } elseif (substr($what, 0, 16) == 'dl_admin_approve' && $value == 'ON') {
                $id = abs(substr($what, 16));
                $request = $smcFunc['db_query']('', '
					SELECT category FROM {db_prefix}tp_dlmanager 
					WHERE id = {int:item}', array('item' => $id));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_row']($request);
                    $newcat = abs($row[0]);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET category = {int:cat} 
						WHERE id = {int:item}', array('cat' => $newcat, 'item' => $id));
                    $smcFunc['db_query']('', '
						DELETE FROM {db_prefix}tp_variables 
						WHERE type = {string:type} 
						AND value5 = {int:val5}', array('type' => 'dl_not_approved', 'val5' => $id));
                    $smcFunc['db_free_result']($request);
                }
            } elseif (substr($what, 0, 16) == 'dladmin_category') {
                $id = substr($what, 16);
                // update, but not on negative values :)
                if ($value > 0) {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET category = {int:cat} 
						WHERE id = {int:item}', array('cat' => $value, 'item' => $id));
                }
            } elseif (substr($what, 0, 14) == 'dladmin_parent') {
                $id = substr($what, 14);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET parent = {int:parent}
					WHERE id = {int:item}', array('parent' => $value, 'item' => $id));
            } elseif (substr($what, 0, 15) == 'dladmin_subitem') {
                $id = substr($what, 15);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET subitem = {int:sub}
					WHERE id = {int:item}', array('sub' => $value, 'item' => $id));
            } elseif (substr($what, 0, 11) == 'tp_dlcatpos') {
                $id = substr($what, 11);
                if (!empty($_POST['admineditcatval'])) {
                    $myid = $_POST['admineditcatval'];
                    $go = 4;
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET downloads = {int:down}
					WHERE id = {int:item}', array('down' => $value, 'item' => $id));
            } elseif (substr($what, 0, 18) == 'dladmin_screenshot') {
                $id = substr($what, 18);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET screenshot = {string:ss} 
					WHERE id = {int:item}', array('ss' => $value, 'item' => $id));
            } elseif (substr($what, 0, 12) == 'dladmin_link') {
                $id = substr($what, 12);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET link = {string:link} 
					WHERE id = {int:item}', array('link' => $value, 'item' => $id));
            } elseif (substr($what, 0, 12) == 'dladmin_file' && !isset($new_upload)) {
                $id = substr($what, 12);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET file = {string:file}
					WHERE id = {int:item}', array('file' => $value, 'item' => $id));
                $myid = $id;
                $go = 2;
            } elseif (substr($what, 0, 12) == 'dladmin_size' && !isset($new_upload)) {
                $id = substr($what, 12);
                // check the actual size
                $name = $_POST['dladmin_file' . $id];
                $value = filesize($boarddir . '/tp-downloads/' . $name);
                if (!is_numeric($value)) {
                    $value = 0;
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET filesize = {int:size}
					WHERE id = {int:item}', array('size' => $value, 'item' => $id));
            } elseif ($what == 'tp_dl_allowed_types') {
                $changeArray['dl_allowed_types'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_usescreenshot') {
                $changeArray['dl_usescreenshot'] = $value;
                $go = 1;
            } elseif (substr($what, 0, 20) == 'tp_dl_screenshotsize') {
                // which one
                $who = substr($what, 20);
                $result = $smcFunc['db_query']('', '
					SELECT value FROM {db_prefix}tp_settings 
					WHERE name = {string:name} LIMIT 1', array('name' => 'dl_screenshotsizes'));
                $row = $smcFunc['db_fetch_assoc']($result);
                $smcFunc['db_free_result']($result);
                $all = explode(',', $row['value']);
                $all[$who] = $value;
                $changeArray['dl_screenshotsizes'] = implode(',', $all);
                $go = 1;
            } elseif ($what == 'tp_dl_showfeatured') {
                $changeArray['dl_showfeatured'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_wysiwyg') {
                $changeArray['dl_wysiwyg'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_showrecent') {
                $changeArray['dl_showlatest'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_showstats') {
                $changeArray['dl_showstats'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_showcategorytext') {
                $changeArray['dl_showcategorylist'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_featured') {
                $changeArray['dl_featured'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_introtext') {
                if ($context['TPortal']['dl_wysiwyg'] == 'bbc') {
                    // If we came from WYSIWYG then turn it back into BBC regardless.
                    if (!empty($_REQUEST['tp_dl_introtext']) && isset($_REQUEST['tp_dl_introtext'])) {
                        require_once $sourcedir . '/Subs-Editor.php';
                        $_REQUEST['tp_dl_introtext'] = html_to_bbc($_REQUEST['tp_dl_introtext']);
                        // We need to unhtml it now as it gets done shortly.
                        $_REQUEST['tp_dl_introtext'] = un_htmlspecialchars($_REQUEST['tp_dl_introtext']);
                        // We need this for everything else.
                        $value = $_POST['tp_dl_introtext'] = $_REQUEST['tp_dl_introtext'];
                    }
                }
                $changeArray['dl_introtext'] = trim($value);
                $go = 1;
            } elseif ($what == 'tp_dluploadsize') {
                $changeArray['dl_max_upload_size'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_approveonly') {
                $changeArray['dl_approve'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dlallowupload') {
                $changeArray['dl_allow_upload'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_fileprefix') {
                $changeArray['dl_fileprefix'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dltheme') {
                $changeArray['dlmanager_theme'] = $value;
                $go = 1;
            }
        }
        // Update all the changes settings finally
        updateTPSettings($changeArray);
        // if we came from useredit screen..
        if (isset($_POST['dl_useredit'])) {
            redirectexit('action=tpmod;dl=useredit' . $_POST['dl_useredit']);
        }
        if (!empty($newgo)) {
            $go = $newgo;
        }
        // guess not, admin screen then
        if ($go == 1) {
            redirectexit('action=tpmod;dl=adminsettings');
        } elseif ($go == 2) {
            redirectexit('action=tpmod;dl=adminitem' . $myid);
        } elseif ($go == 3) {
            redirectexit('action=tpmod;dl=admineditcat' . $myid);
        } elseif ($go == 4) {
            redirectexit('action=tpmod;dl=admincat' . $myid);
        }
    }
    // ****************
    TP_dlgeticons();
    // get all themes
    $context['TPthemes'] = array();
    $request = $smcFunc['db_query']('', '
		SELECT value AS name, id_theme as ID_THEME
		FROM {db_prefix}themes
		WHERE variable = {string:var}
		AND id_member = {int:id_mem}
		ORDER BY value ASC', array('var' => 'name', 'id_mem' => 0));
    if ($smcFunc['db_num_rows']($request) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $context['TPthemes'][] = array('id' => $row['ID_THEME'], 'name' => $row['name']);
        }
        $smcFunc['db_free_result']($request);
    }
    // fetch all files from tp-downloads
    $context['TPortal']['tp-downloads'] = array();
    $count = 1;
    if ($handle = opendir($boarddir . '/tp-downloads')) {
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..' && $file != '.htaccess' && $file != 'icons') {
                $size = floor(filesize($boarddir . '/tp-downloads/' . $file) / 102.4) / 10;
                $context['TPortal']['tp-downloads'][$count] = array('id' => $count, 'file' => $file, 'size' => $size);
                $count++;
            }
        }
        closedir($handle);
    }
    // get all membergroups for permissions
    $context['TPortal']['dlgroups'] = get_grps(true, true);
    //fetch all categories
    $sorted = array();
    $context['TPortal']['linkcats'] = array();
    $srequest = $smcFunc['db_query']('', '
		SELECT id, name, description, icon, access, parent 
		FROM {db_prefix}tp_dlmanager 
		WHERE type = {string:type} ORDER BY downloads ASC', array('type' => 'dlcat'));
    if ($smcFunc['db_num_rows']($srequest) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($srequest)) {
            // for the linktree
            $context['TPortal']['linkcats'][$row['id']] = array('id' => $row['id'], 'name' => $row['name'], 'parent' => $row['parent']);
            $sorted[$row['id']] = array('id' => $row['id'], 'parent' => $row['parent'], 'name' => $row['name'], 'text' => $row['description'], 'icon' => $row['icon']);
        }
        $smcFunc['db_free_result']($srequest);
    }
    // sort them
    if (count($sorted) > 1) {
        $context['TPortal']['admuploadcats'] = chain('id', 'parent', 'name', $sorted);
    } else {
        $context['TPortal']['admuploadcats'] = $sorted;
    }
    $context['TPortal']['dl_admcats'] = array();
    $context['TPortal']['dl_admcats2'] = array();
    $context['TPortal']['dl_admitems'] = array();
    $context['TPortal']['dl_admcount'] = array();
    $context['TPortal']['dl_admsubmitted'] = array();
    $context['TPortal']['dl_allitems'] = array();
    // count items in each category
    $request = $smcFunc['db_query']('', '
		SELECT file, category 
		FROM {db_prefix}tp_dlmanager 
		WHERE type = {string:type}', array('type' => 'dlitem'));
    if ($smcFunc['db_num_rows']($request) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            if ($row['category'] < 0) {
                if (isset($context['TPortal']['dl_admsubmitted'][abs($row['category'])])) {
                    $context['TPortal']['dl_admsubmitted'][abs($row['category'])]++;
                } else {
                    $context['TPortal']['dl_admsubmitted'][abs($row['category'])] = 1;
                }
            } else {
                if (isset($context['TPortal']['dl_admcount'][$row['category']])) {
                    $context['TPortal']['dl_admcount'][$row['category']]++;
                } else {
                    $context['TPortal']['dl_admcount'][$row['category']] = 1;
                }
            }
            $context['TPortal']['dl_allitems'][] = $row['file'];
        }
        $smcFunc['db_free_result']($request);
    }
    // fetch all categories
    $admsub = substr($context['TPortal']['dlsub'], 5);
    if ($admsub == '') {
        $context['TPortal']['dl_title'] = $txt['tp-dladmin'];
        // fetch all categories with subcats
        $req = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_dlmanager 
			WHERE type = {string:type} 
			ORDER BY downloads ASC', array('type' => 'dlcat'));
        if ($smcFunc['db_num_rows']($req) > 0) {
            while ($brow = $smcFunc['db_fetch_assoc']($req)) {
                if (isset($context['TPortal']['dl_admcount'][$brow['id']])) {
                    $items = $context['TPortal']['dl_admcount'][$brow['id']];
                } else {
                    $items = 0;
                }
                if (isset($context['TPortal']['dl_admsubmitted'][$brow['id']])) {
                    $sitems = $context['TPortal']['dl_admsubmitted'][$brow['id']];
                } else {
                    $sitems = 0;
                }
                $context['TPortal']['admcats'][] = array('id' => $brow['id'], 'name' => $brow['name'], 'icon' => $brow['icon'], 'access' => $brow['access'], 'parent' => $brow['parent'], 'description' => $brow['description'], 'shortname' => $brow['link'], 'items' => $items, 'submitted' => $sitems, 'total' => $items + $sitems, 'href' => $scripturl . '?action=tpmod;dl=admincat' . $brow['id'], 'href2' => $scripturl . '?action=tpmod;dl=admineditcat' . $brow['id'], 'href3' => $scripturl . '?action=tpmod;dl=admindelcat' . $brow['id'], 'pos' => $brow['downloads']);
            }
            $smcFunc['db_free_result']($req);
        }
    } elseif (substr($admsub, 0, 3) == 'cat') {
        $cat = substr($admsub, 3);
        // get the parent first
        $request = $smcFunc['db_query']('', '
			SELECT parent, name, link 
			FROM {db_prefix}tp_dlmanager 
			WHERE type = {string:type}
			AND id = {int:item}', array('type' => 'dlcat', 'item' => $cat));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_assoc']($request);
            $catparent = abs($row['parent']);
            $catname = $row['name'];
            $catshortname = $row['link'];
            $smcFunc['db_free_result']($request);
        }
        // fetch items within a category
        $request = $smcFunc['db_query']('', '
			SELECT dl.*, dl.author_id as authorID,m.real_name as realName
			FROM ({db_prefix}tp_dlmanager AS dl, {db_prefix}members AS m)
			WHERE abs(dl.category) = {int:cat}
			AND dl.type = {string:type}
			AND dl.subitem = {int:sub}
			AND dl.author_id = m.id_member
			ORDER BY dl.id DESC', array('cat' => $cat, 'type' => 'dlitem', 'sub' => 0));
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['dl_admitems'][] = array('id' => $row['id'], 'name' => $row['name'], 'icon' => $row['icon'], 'category' => abs($row['category']), 'file' => $row['file'], 'filesize' => floor($row['filesize'] / 1024), 'views' => $row['views'], 'authorID' => $row['authorID'], 'author' => '<a href="' . $scripturl . '?action=profile;u=' . $row['authorID'] . '">' . $row['realName'] . '</a>', 'created' => timeformat($row['created']), 'last_access' => timeformat($row['last_access']), 'description' => $row['description'], 'downloads' => $row['downloads'], 'sshot' => $row['screenshot'], 'link' => $row['link'], 'href' => $scripturl . '?action=tpmod;dl=adminitem' . $row['id'], 'approved' => $row['category'] < 0 ? '0' : '1', 'approve' => $scripturl . '?action=tpmod;dl=adminapprove' . $row['id']);
            }
            $smcFunc['db_free_result']($request);
        }
        // fetch all categories with subcats
        $request = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_dlmanager 
			WHERE type = {string:type}
			ORDER BY name ASC', array('type' => 'dlcat'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                if (isset($context['TPortal']['dl_admcount'][$row['id']])) {
                    $items = $context['TPortal']['dl_admcount'][$row['id']];
                } else {
                    $items = 0;
                }
                if (isset($context['TPortal']['dl_admsubmitted'][$row['id']])) {
                    $sitems = $context['TPortal']['dl_admsubmitted'][$row['id']];
                } else {
                    $sitems = 0;
                }
                $context['TPortal']['admcats'][] = array('id' => $row['id'], 'name' => $row['name'], 'pos' => $row['downloads'], 'icon' => $row['icon'], 'shortname' => $row['link'], 'access' => $row['access'], 'parent' => $row['parent'], 'description' => $row['description'], 'items' => $items, 'submitted' => $sitems, 'total' => $items + $sitems, 'href' => $scripturl . '?action=tpmod;dl=admincat' . $row['id'], 'href2' => $scripturl . '?action=tpmod;dl=admineditcat' . $row['id'], 'href3' => $scripturl . '?action=tpmod;dl=admindelcat' . $row['id']);
            }
            $smcFunc['db_free_result']($request);
        }
        // check to see if its child
        $parents = array();
        while ($catparent > 0) {
            $parents[$catparent] = array('id' => $catparent, 'name' => $context['TPortal']['linkcats'][$catparent]['name'], 'parent' => $context['TPortal']['linkcats'][$catparent]['parent']);
            $catparent = $context['TPortal']['linkcats'][$catparent]['parent'];
        }
        // make the linktree
        TPadd_linktree($scripturl . '?action=tpmod;dl=admin', $txt['tp-dladmin']);
        if (isset($parents)) {
            $parts = array_reverse($parents, TRUE);
            // add to the linktree
            foreach ($parts as $parent) {
                TPadd_linktree($scripturl . '?action=tpmod;dl=admincat' . $parent['id'], $parent['name']);
            }
        }
        // add to the linktree
        TPadd_linktree($scripturl . '?action=tpmod;dl=admincat' . $cat, $catname);
    } elseif ($context['TPortal']['dlsub'] == 'adminsubmission') {
        // check any submissions if admin
        $submitted = array();
        isAllowedTo('tp_dlmanager');
        $context['TPortal']['dl_admitems'] = array();
        $request = $smcFunc['db_query']('', '
			SELECT dl.id, dl.name, dl.file, dl.created, dl.filesize, dl.author_id as authorID, m.real_name as realName
			FROM ({db_prefix}tp_dlmanager AS dl, {db_prefix}members AS m)
			WHERE dl.type = {string:type}
			AND dl.category < 0
			AND dl.author_id = m.id_member', array('type' => 'dlitem'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $rows = $smcFunc['db_num_rows']($request);
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['dl_admitems'][] = array('id' => $row['id'], 'name' => $row['name'], 'file' => $row['file'], 'filesize' => floor($row['filesize'] / 1024), 'href' => $scripturl . '?action=tpmod;dl=adminitem' . $row['id'], 'author' => '<a href="' . $scripturl . '?action=profile;u=' . $row['authorID'] . '">' . $row['realName'] . '</a>', 'date' => timeformat($row['created']));
                $submitted[] = $row['id'];
            }
            $smcFunc['db_free_result']($request);
        }
        // check that submissions link to downloads
        $request = $smcFunc['db_query']('', '
			SELECT id,value5 FROM {db_prefix}tp_variables 
			WHERE type = {string:type}', array('type' => 'dl_not_approved'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $what = $row['id'];
                if (!in_array($row['value5'], $submitted)) {
                    $smcFunc['db_query']('', '
						DELETE FROM {db_prefix}tp_variables 
						WHERE id = {int:item}', array('item' => $what));
                }
            }
            $smcFunc['db_free_result']($request);
        }
    } elseif (substr($admsub, 0, 7) == 'editcat') {
        $context['TPortal']['dl_title'] = '<a href="' . $scripturl . '?action=tpmod;dl=admin">' . $txt['tp-dladmin'] . '</a>';
        $cat = substr($admsub, 7);
        // edit category
        $request = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:item} 
			AND type = {string:type} LIMIT 1', array('item' => $cat, 'type' => 'dlcat'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['admcats'][] = array('id' => $row['id'], 'name' => $row['name'], 'access' => $row['access'], 'shortname' => $row['link'], 'description' => $row['description'], 'icon' => $row['icon'], 'parent' => $row['parent']);
            }
            $smcFunc['db_free_result']($request);
        }
        if ($context['TPortal']['dl_wysiwyg'] == 'bbc') {
            $context['TPortal']['editor_id'] = 'dladmin_text' . $context['TPortal']['admcats'][0]['id'];
            TP_prebbcbox($context['TPortal']['editor_id'], $context['TPortal']['admcats'][0]['description']);
        }
    } elseif (substr($admsub, 0, 6) == 'delcat') {
        $context['TPortal']['dl_title'] = '<a href="' . $scripturl . '?action=tpmod;dl=admin">' . $txt['tp-dladmin'] . '</a>';
        $cat = substr($admsub, 6);
        // delete category and all item it's in
        $request = $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}tp_dlmanager 
			WHERE type = {string:type}
			AND category = {int:cat}', array('type' => 'dlitem', 'cat' => $cat));
        $request = $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:cat} LIMIT 1', array('cat' => $cat));
        redirectexit('action=tpmod;dl=admin');
    } elseif (substr($admsub, 0, 8) == 'settings') {
        $context['TPortal']['dl_title'] = $txt['tp-dlsettings'];
    } elseif (substr($admsub, 0, 4) == 'item') {
        $item = substr($admsub, 4);
        $request = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:item} 
			AND type = {string:type} LIMIT 1', array('item' => $item, 'type' => 'dlitem'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_assoc']($request);
            // is it actually a subitem?
            if ($row['subitem'] > 0) {
                redirectexit('action=tpmod;dl=adminitem' . $row['subitem']);
            }
            // Add in BBC editor before we call in template so the headers are there
            if ($context['TPortal']['dl_wysiwyg'] == 'bbc') {
                $context['TPortal']['editor_id'] = 'dladmin_text' . $item;
                TP_prebbcbox($context['TPortal']['editor_id'], $row['description']);
            }
            // get all items for a list
            $context['TPortal']['admitems'] = array();
            $itemlist = $smcFunc['db_query']('', '
				SELECT id, name FROM {db_prefix}tp_dlmanager 
				WHERE id != {int:item} 
				AND type = {string:type} 
				AND subitem = 0 
				ORDER BY name ASC', array('item' => $item, 'type' => 'dlitem'));
            if ($smcFunc['db_num_rows']($itemlist) > 0) {
                while ($ilist = $smcFunc['db_fetch_assoc']($itemlist)) {
                    $context['TPortal']['admitems'][] = array('id' => $ilist['id'], 'name' => $ilist['name']);
                }
            }
            // Any additional files then..?
            $subitem = $row['id'];
            $fdata = array();
            $fetch = $smcFunc['db_query']('', '
				SELECT id, name, file, downloads, filesize, created
				FROM {db_prefix}tp_dlmanager
				WHERE type = {string:type}
				AND subitem = {int:sub}', array('type' => 'dlitem', 'sub' => $subitem));
            if ($smcFunc['db_num_rows']($fetch) > 0) {
                while ($frow = $smcFunc['db_fetch_assoc']($fetch)) {
                    if ($context['TPortal']['dl_fileprefix'] == 'K') {
                        $ffs = ceil($row['filesize'] / 1000) . ' Kb';
                    } elseif ($context['TPortal']['dl_fileprefix'] == 'M') {
                        $ffs = ceil($row['filesize'] / 1000) / 1000 . ' Mb';
                    } elseif ($context['TPortal']['dl_fileprefix'] == 'G') {
                        $ffs = ceil($row['filesize'] / 1000000) / 1000 . ' Gb';
                    }
                    $fdata[] = array('id' => $frow['id'], 'name' => $frow['name'], 'file' => $frow['file'], 'href' => $scripturl . '?action=tpmod;dl=item' . $frow['id'], 'downloads' => $frow['downloads'], 'created' => $frow['created'], 'filesize' => $ffs);
                }
                $smcFunc['db_free_result']($fetch);
            }
            if (!empty($row['screenshot'])) {
                if (substr($row['screenshot'], 0, 10) == 'tp-images/') {
                    $sshot = $boardurl . '/' . $row['screenshot'];
                } else {
                    $sshot = $boardurl . '/tp-images/dlmanager/listing/' . $row['screenshot'];
                }
            }
            $context['TPortal']['dl_admitems'][] = array('id' => $row['id'], 'name' => $row['name'], 'icon' => $row['icon'], 'category' => $row['category'], 'file' => $row['file'], 'views' => $row['views'], 'authorID' => $row['author_id'], 'description' => $row['description'], 'created' => timeformat($row['created']), 'last_access' => timeformat($row['last_access']), 'filesize' => substr($row['file'], 14) != '- empty item -' ? floor(filesize($boarddir . '/tp-downloads/' . $row['file']) / 1024) : '0', 'downloads' => $row['downloads'], 'sshot' => !empty($sshot) ? $sshot : '', 'screenshot' => $row['screenshot'], 'link' => $row['link'], 'href' => $scripturl . '?action=tpmod;dl=adminitem' . $row['id'], 'approved' => $row['category'] < 0 ? '0' : '1', 'approve' => $scripturl . '?action=tpmod;dl=adminitem' . $row['id'], 'subitem' => $fdata);
            $authorID = $row['author_id'];
            $catparent = $row['category'];
            $itemname = $row['name'];
            $smcFunc['db_free_result']($request);
            $request = $smcFunc['db_query']('', '
				SELECT mem.real_name as realName 
				FROM {db_prefix}members as mem 
				WHERE mem.id_member = {int:id_mem}', array('id_mem' => $authorID));
            if ($smcFunc['db_num_rows']($request) > 0) {
                $row = $smcFunc['db_fetch_assoc']($request);
                $context['TPortal']['admcurrent']['member'] = $row['realName'];
                $smcFunc['db_free_result']($request);
            } else {
                $context['TPortal']['admcurrent']['member'] = '-' . $txt['guest_title'] . '-';
            }
        }
        // check to see if its child
        $parents = array();
        while ($catparent > 0) {
            $parents[$catparent] = array('id' => $catparent, 'name' => $context['TPortal']['linkcats'][$catparent]['name'], 'parent' => $context['TPortal']['linkcats'][$catparent]['parent']);
            $catparent = $context['TPortal']['linkcats'][$catparent]['parent'];
        }
        // make the linktree
        TPadd_linktree($scripturl . '?action=tpmod;dl=admin', $txt['tp-dldownloads']);
        if (isset($parents)) {
            $parts = array_reverse($parents, TRUE);
            // add to the linktree
            foreach ($parts as $parent) {
                TPadd_linktree($scripturl . '?action=tpmod;dl=admincat' . $parent['id'], $parent['name']);
            }
        }
        // add to the linktree
        TPadd_linktree($scripturl . '?action=tpmod;dl=adminitem' . $item, $itemname);
    }
    loadTemplate('TPdladmin');
    if (loadLanguage('TPmodules') == false) {
        loadLanguage('TPmodules', 'english');
    }
    if (loadLanguage('TPortalAdmin') == false) {
        loadLanguage('TPortalAdmin', 'english');
    }
    // setup admin tabs according to subaction
    $context['admin_area'] = 'tp_dlmanager';
    $context['admin_tabs'] = array('title' => $txt['tp-dlheader1'], 'help' => $txt['tp-dlheader2'], 'description' => $txt['tp-dlheader3'], 'tabs' => array());
    if (allowedTo('tp_dlmanager')) {
        $context['TPortal']['subtabs'] = array('admin' => array('text' => 'tp-dltabs4', 'url' => $scripturl . '?action=tpmod;dl=admin', 'active' => substr($context['TPortal']['dlsub'], 0, 5) == 'admin' && $context['TPortal']['dlsub'] != 'adminsettings' && $context['TPortal']['dlsub'] != 'adminaddcat' && $context['TPortal']['dlsub'] != 'adminftp' && $context['TPortal']['dlsub'] != 'adminsubmission'), 'settings' => array('text' => 'tp-dltabs1', 'url' => $scripturl . '?action=tpmod;dl=adminsettings', 'active' => $context['TPortal']['dlsub'] == 'adminsettings'), 'addcategory' => array('text' => 'tp-dltabs2', 'url' => $scripturl . '?action=tpmod;dl=adminaddcat', 'active' => $context['TPortal']['dlsub'] == 'adminaddcat'), 'upload' => array('text' => 'tp-dltabs3', 'url' => $scripturl . '?action=tpmod;dl=upload', 'active' => $context['TPortal']['dlsub'] == 'upload'), 'submissions' => array('text' => 'tp-dlsubmissions', 'url' => $scripturl . '?action=tpmod;dl=adminsubmission', 'active' => $context['TPortal']['dlsub'] == 'adminsubmission'), 'ftp' => array('text' => 'tp-dlftp', 'url' => $scripturl . '?action=tpmod;dl=adminftp', 'active' => $context['TPortal']['dlsub'] == 'adminftp'));
    }
    $context['template_layers'][] = 'tpadm';
    $context['template_layers'][] = 'subtab';
    TPadminIndex('');
    $context['current_action'] = 'admin';
}
Beispiel #4
0
function Post2()
{
    global $board, $topic, $txt, $modSettings, $sourcedir, $context;
    global $user_info, $board_info, $options, $smcFunc;
    // Sneaking off, are we?
    if (empty($_POST) && empty($topic)) {
        redirectexit('action=post;board=' . $board . '.0');
    } elseif (empty($_POST) && !empty($topic)) {
        redirectexit('action=post;topic=' . $topic . '.0');
    }
    // No need!
    $context['robot_no_index'] = true;
    // If we came from WYSIWYG then turn it back into BBC regardless.
    if (!empty($_REQUEST['message_mode']) && isset($_REQUEST['message'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_REQUEST['message'] = html_to_bbc($_REQUEST['message']);
        // We need to unhtml it now as it gets done shortly.
        $_REQUEST['message'] = un_htmlspecialchars($_REQUEST['message']);
        // We need this for everything else.
        $_POST['message'] = $_REQUEST['message'];
    }
    // Previewing? Go back to start.
    if (isset($_REQUEST['preview'])) {
        return Post();
    }
    // Prevent double submission of this form.
    checkSubmitOnce('check');
    // No errors as yet.
    $post_errors = array();
    // If the session has timed out, let the user re-submit their form.
    if (checkSession('post', '', false) != '') {
        $post_errors[] = 'session_timeout';
    }
    // Wrong verification code?
    if (!$user_info['is_admin'] && !$user_info['is_mod'] && !empty($modSettings['posts_require_captcha']) && ($user_info['posts'] < $modSettings['posts_require_captcha'] || $user_info['is_guest'] && $modSettings['posts_require_captcha'] == -1)) {
        require_once $sourcedir . '/Subs-Editor.php';
        $verificationOptions = array('id' => 'post');
        $context['require_verification'] = create_control_verification($verificationOptions, true);
        if (is_array($context['require_verification'])) {
            $post_errors = array_merge($post_errors, $context['require_verification']);
        }
    }
    require_once $sourcedir . '/Subs-Post.php';
    loadLanguage('Post');
    // If this isn't a new topic load the topic info that we need.
    if (!empty($topic)) {
        $request = $smcFunc['db_query']('', '
			SELECT locked, is_sticky, id_poll, approved, id_first_msg, id_last_msg, id_member_started, id_board
			FROM {db_prefix}topics
			WHERE id_topic = {int:current_topic}
			LIMIT 1', array('current_topic' => $topic));
        $topic_info = $smcFunc['db_fetch_assoc']($request);
        $smcFunc['db_free_result']($request);
        // Though the topic should be there, it might have vanished.
        if (!is_array($topic_info)) {
            fatal_lang_error('topic_doesnt_exist');
        }
        // Did this topic suddenly move? Just checking...
        if ($topic_info['id_board'] != $board) {
            fatal_lang_error('not_a_topic');
        }
    }
    // Replying to a topic?
    if (!empty($topic) && !isset($_REQUEST['msg'])) {
        // Don't allow a post if it's locked.
        if ($topic_info['locked'] != 0 && !allowedTo('moderate_board')) {
            fatal_lang_error('topic_locked', false);
        }
        // Sorry, multiple polls aren't allowed... yet.  You should stop giving me ideas :P.
        if (isset($_REQUEST['poll']) && $topic_info['id_poll'] > 0) {
            unset($_REQUEST['poll']);
        }
        // Do the permissions and approval stuff...
        $becomesApproved = true;
        if ($topic_info['id_member_started'] != $user_info['id']) {
            if ($modSettings['postmod_active'] && allowedTo('post_unapproved_replies_any') && !allowedTo('post_reply_any')) {
                $becomesApproved = false;
            } else {
                isAllowedTo('post_reply_any');
            }
        } elseif (!allowedTo('post_reply_any')) {
            if ($modSettings['postmod_active'] && allowedTo('post_unapproved_replies_own') && !allowedTo('post_reply_own')) {
                $becomesApproved = false;
            } else {
                isAllowedTo('post_reply_own');
            }
        }
        if (isset($_POST['lock'])) {
            // Nothing is changed to the lock.
            if (empty($topic_info['locked']) && empty($_POST['lock']) || !empty($_POST['lock']) && !empty($topic_info['locked'])) {
                unset($_POST['lock']);
            } elseif (!allowedTo(array('lock_any', 'lock_own')) || !allowedTo('lock_any') && $user_info['id'] != $topic_info['id_member_started']) {
                unset($_POST['lock']);
            } elseif (!allowedTo('lock_any')) {
                // You cannot override a moderator lock.
                if ($topic_info['locked'] == 1) {
                    unset($_POST['lock']);
                } else {
                    $_POST['lock'] = empty($_POST['lock']) ? 0 : 2;
                }
            } else {
                $_POST['lock'] = empty($_POST['lock']) ? 0 : 1;
            }
        }
        // So you wanna (un)sticky this...let's see.
        if (isset($_POST['sticky']) && (empty($modSettings['enableStickyTopics']) || $_POST['sticky'] == $topic_info['is_sticky'] || !allowedTo('make_sticky'))) {
            unset($_POST['sticky']);
        }
        // If the number of replies has changed, if the setting is enabled, go back to Post() - which handles the error.
        if (empty($options['no_new_reply_warning']) && isset($_POST['last_msg']) && $topic_info['id_last_msg'] > $_POST['last_msg']) {
            $_REQUEST['preview'] = true;
            return Post();
        }
        $posterIsGuest = $user_info['is_guest'];
    } elseif (empty($topic)) {
        // Now don't be silly, new topics will get their own id_msg soon enough.
        unset($_REQUEST['msg'], $_POST['msg'], $_GET['msg']);
        // Do like, the permissions, for safety and stuff...
        $becomesApproved = true;
        if ($modSettings['postmod_active'] && !allowedTo('post_new') && allowedTo('post_unapproved_topics')) {
            $becomesApproved = false;
        } else {
            isAllowedTo('post_new');
        }
        if (isset($_POST['lock'])) {
            // New topics are by default not locked.
            if (empty($_POST['lock'])) {
                unset($_POST['lock']);
            } elseif (!allowedTo(array('lock_any', 'lock_own'))) {
                unset($_POST['lock']);
            } else {
                $_POST['lock'] = allowedTo('lock_any') ? 1 : 2;
            }
        }
        if (isset($_POST['sticky']) && (empty($modSettings['enableStickyTopics']) || empty($_POST['sticky']) || !allowedTo('make_sticky'))) {
            unset($_POST['sticky']);
        }
        $posterIsGuest = $user_info['is_guest'];
    } elseif (isset($_REQUEST['msg']) && !empty($topic)) {
        $_REQUEST['msg'] = (int) $_REQUEST['msg'];
        $request = $smcFunc['db_query']('', '
			SELECT id_member, poster_name, poster_email, poster_time, approved
			FROM {db_prefix}messages
			WHERE id_msg = {int:id_msg}
			LIMIT 1', array('id_msg' => $_REQUEST['msg']));
        if ($smcFunc['db_num_rows']($request) == 0) {
            fatal_lang_error('cant_find_messages', false);
        }
        $row = $smcFunc['db_fetch_assoc']($request);
        $smcFunc['db_free_result']($request);
        if (!empty($topic_info['locked']) && !allowedTo('moderate_board')) {
            fatal_lang_error('topic_locked', false);
        }
        if (isset($_POST['lock'])) {
            // Nothing changes to the lock status.
            if (empty($_POST['lock']) && empty($topic_info['locked']) || !empty($_POST['lock']) && !empty($topic_info['locked'])) {
                unset($_POST['lock']);
            } elseif (!allowedTo(array('lock_any', 'lock_own')) || !allowedTo('lock_any') && $user_info['id'] != $topic_info['id_member_started']) {
                unset($_POST['lock']);
            } elseif (!allowedTo('lock_any')) {
                // You're not allowed to break a moderator's lock.
                if ($topic_info['locked'] == 1) {
                    unset($_POST['lock']);
                } else {
                    $_POST['lock'] = empty($_POST['lock']) ? 0 : 2;
                }
            } else {
                $_POST['lock'] = empty($_POST['lock']) ? 0 : 1;
            }
        }
        // Change the sticky status of this topic?
        if (isset($_POST['sticky']) && (!allowedTo('make_sticky') || $_POST['sticky'] == $topic_info['is_sticky'])) {
            unset($_POST['sticky']);
        }
        if ($row['id_member'] == $user_info['id'] && !allowedTo('modify_any')) {
            if ((!$modSettings['postmod_active'] || $row['approved']) && !empty($modSettings['edit_disable_time']) && $row['poster_time'] + ($modSettings['edit_disable_time'] + 5) * 60 < time()) {
                fatal_lang_error('modify_post_time_passed', false);
            } elseif ($topic_info['id_member_started'] == $user_info['id'] && !allowedTo('modify_own')) {
                isAllowedTo('modify_replies');
            } else {
                isAllowedTo('modify_own');
            }
        } elseif ($topic_info['id_member_started'] == $user_info['id'] && !allowedTo('modify_any')) {
            isAllowedTo('modify_replies');
            // If you're modifying a reply, I say it better be logged...
            $moderationAction = true;
        } else {
            isAllowedTo('modify_any');
            // Log it, assuming you're not modifying your own post.
            if ($row['id_member'] != $user_info['id']) {
                $moderationAction = true;
            }
        }
        $posterIsGuest = empty($row['id_member']);
        // Can they approve it?
        $can_approve = allowedTo('approve_posts');
        $becomesApproved = $modSettings['postmod_active'] ? $can_approve && !$row['approved'] ? !empty($_REQUEST['approve']) ? 1 : 0 : $row['approved'] : 1;
        $approve_has_changed = $row['approved'] != $becomesApproved;
        if (!allowedTo('moderate_forum') || !$posterIsGuest) {
            $_POST['guestname'] = $row['poster_name'];
            $_POST['email'] = $row['poster_email'];
        }
    }
    // If the poster is a guest evaluate the legality of name and email.
    if ($posterIsGuest) {
        $_POST['guestname'] = !isset($_POST['guestname']) ? '' : trim($_POST['guestname']);
        $_POST['email'] = !isset($_POST['email']) ? '' : trim($_POST['email']);
        if ($_POST['guestname'] == '' || $_POST['guestname'] == '_') {
            $post_errors[] = 'no_name';
        }
        if ($smcFunc['strlen']($_POST['guestname']) > 25) {
            $post_errors[] = 'long_name';
        }
        if (empty($modSettings['guest_post_no_email'])) {
            // Only check if they changed it!
            if (!isset($row) || $row['poster_email'] != $_POST['email']) {
                if (!allowedTo('moderate_forum') && (!isset($_POST['email']) || $_POST['email'] == '')) {
                    $post_errors[] = 'no_email';
                }
                if (!allowedTo('moderate_forum') && preg_match('~^[0-9A-Za-z=_+\\-/][0-9A-Za-z=_\'+\\-/\\.]*@[\\w\\-]+(\\.[\\w\\-]+)*(\\.[\\w]{2,6})$~', $_POST['email']) == 0) {
                    $post_errors[] = 'bad_email';
                }
            }
            // Now make sure this email address is not banned from posting.
            isBannedEmail($_POST['email'], 'cannot_post', sprintf($txt['you_are_post_banned'], $txt['guest_title']));
        }
        // In case they are making multiple posts this visit, help them along by storing their name.
        if (empty($post_errors)) {
            $_SESSION['guest_name'] = $_POST['guestname'];
            $_SESSION['guest_email'] = $_POST['email'];
        }
    }
    // Check the subject and message.
    if (!isset($_POST['subject']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['subject'])) === '') {
        $post_errors[] = 'no_subject';
    }
    if (!isset($_POST['message']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['message']), ENT_QUOTES) === '') {
        $post_errors[] = 'no_message';
    } elseif (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_POST['message']) > $modSettings['max_messageLength']) {
        $post_errors[] = 'long_message';
    } else {
        // Prepare the message a bit for some additional testing.
        $_POST['message'] = $smcFunc['htmlspecialchars']($_POST['message'], ENT_QUOTES);
        // Preparse code. (Zef)
        if ($user_info['is_guest']) {
            $user_info['name'] = $_POST['guestname'];
        }
        preparsecode($_POST['message']);
        // Let's see if there's still some content left without the tags.
        if ($smcFunc['htmltrim'](strip_tags(parse_bbc($_POST['message'], false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($_POST['message'], '[html]') === false)) {
            $post_errors[] = 'no_message';
        }
    }
    if (isset($_POST['calendar']) && !isset($_REQUEST['deleteevent']) && $smcFunc['htmltrim']($_POST['evtitle']) === '') {
        $post_errors[] = 'no_event';
    }
    // You are not!
    if (isset($_POST['message']) && strtolower($_POST['message']) == 'i am the administrator.' && !$user_info['is_admin']) {
        fatal_error('Knave! Masquerader! Charlatan!', false);
    }
    // Validate the poll...
    if (isset($_REQUEST['poll']) && $modSettings['pollMode'] == '1') {
        if (!empty($topic) && !isset($_REQUEST['msg'])) {
            fatal_lang_error('no_access', false);
        }
        // This is a new topic... so it's a new poll.
        if (empty($topic)) {
            isAllowedTo('poll_post');
        } elseif ($user_info['id'] == $topic_info['id_member_started'] && !allowedTo('poll_add_any')) {
            isAllowedTo('poll_add_own');
        } else {
            isAllowedTo('poll_add_any');
        }
        if (!isset($_POST['question']) || trim($_POST['question']) == '') {
            $post_errors[] = 'no_question';
        }
        $_POST['options'] = empty($_POST['options']) ? array() : htmltrim__recursive($_POST['options']);
        // Get rid of empty ones.
        foreach ($_POST['options'] as $k => $option) {
            if ($option == '') {
                unset($_POST['options'][$k], $_POST['options'][$k]);
            }
        }
        // What are you going to vote between with one choice?!?
        if (count($_POST['options']) < 2) {
            $post_errors[] = 'poll_few';
        }
    }
    if ($posterIsGuest) {
        // If user is a guest, make sure the chosen name isn't taken.
        require_once $sourcedir . '/Subs-Members.php';
        if (isReservedName($_POST['guestname'], 0, true, false) && (!isset($row['poster_name']) || $_POST['guestname'] != $row['poster_name'])) {
            $post_errors[] = 'bad_name';
        }
    } elseif (!isset($_REQUEST['msg'])) {
        $_POST['guestname'] = $user_info['username'];
        $_POST['email'] = $user_info['email'];
    }
    // Any mistakes?
    if (!empty($post_errors)) {
        loadLanguage('Errors');
        // Previewing.
        $_REQUEST['preview'] = true;
        $context['post_error'] = array('messages' => array());
        foreach ($post_errors as $post_error) {
            $context['post_error'][$post_error] = true;
            if ($post_error == 'long_message') {
                $txt['error_' . $post_error] = sprintf($txt['error_' . $post_error], $modSettings['max_messageLength']);
            }
            $context['post_error']['messages'][] = $txt['error_' . $post_error];
        }
        return Post();
    }
    // Make sure the user isn't spamming the board.
    if (!isset($_REQUEST['msg'])) {
        spamProtection('post');
    }
    // At about this point, we're posting and that's that.
    ignore_user_abort(true);
    @set_time_limit(300);
    // Add special html entities to the subject, name, and email.
    $_POST['subject'] = strtr($smcFunc['htmlspecialchars']($_POST['subject']), array("\r" => '', "\n" => '', "\t" => ''));
    $_POST['guestname'] = htmlspecialchars($_POST['guestname']);
    $_POST['email'] = htmlspecialchars($_POST['email']);
    // At this point, we want to make sure the subject isn't too long.
    if ($smcFunc['strlen']($_POST['subject']) > 100) {
        $_POST['subject'] = $smcFunc['substr']($_POST['subject'], 0, 100);
    }
    // Make the poll...
    if (isset($_REQUEST['poll'])) {
        // Make sure that the user has not entered a ridiculous number of options..
        if (empty($_POST['poll_max_votes']) || $_POST['poll_max_votes'] <= 0) {
            $_POST['poll_max_votes'] = 1;
        } elseif ($_POST['poll_max_votes'] > count($_POST['options'])) {
            $_POST['poll_max_votes'] = count($_POST['options']);
        } else {
            $_POST['poll_max_votes'] = (int) $_POST['poll_max_votes'];
        }
        $_POST['poll_expire'] = (int) $_POST['poll_expire'];
        $_POST['poll_expire'] = $_POST['poll_expire'] > 9999 ? 9999 : ($_POST['poll_expire'] < 0 ? 0 : $_POST['poll_expire']);
        // Just set it to zero if it's not there..
        if (!isset($_POST['poll_hide'])) {
            $_POST['poll_hide'] = 0;
        } else {
            $_POST['poll_hide'] = (int) $_POST['poll_hide'];
        }
        $_POST['poll_change_vote'] = isset($_POST['poll_change_vote']) ? 1 : 0;
        $_POST['poll_guest_vote'] = isset($_POST['poll_guest_vote']) ? 1 : 0;
        // Make sure guests are actually allowed to vote generally.
        if ($_POST['poll_guest_vote']) {
            require_once $sourcedir . '/Subs-Members.php';
            $allowedVoteGroups = groupsAllowedTo('poll_vote', $board);
            if (!in_array(-1, $allowedVoteGroups['allowed'])) {
                $_POST['poll_guest_vote'] = 0;
            }
        }
        // If the user tries to set the poll too far in advance, don't let them.
        if (!empty($_POST['poll_expire']) && $_POST['poll_expire'] < 1) {
            fatal_lang_error('poll_range_error', false);
        } elseif (empty($_POST['poll_expire']) && $_POST['poll_hide'] == 2) {
            $_POST['poll_hide'] = 1;
        }
        // Clean up the question and answers.
        $_POST['question'] = htmlspecialchars($_POST['question']);
        $_POST['question'] = $smcFunc['truncate']($_POST['question'], 255);
        $_POST['question'] = preg_replace('~&amp;#(\\d{4,5}|[2-9]\\d{2,4}|1[2-9]\\d);~', '&#$1;', $_POST['question']);
        $_POST['options'] = htmlspecialchars__recursive($_POST['options']);
    }
    // Check if they are trying to delete any current attachments....
    if (isset($_REQUEST['msg'], $_POST['attach_del']) && (allowedTo('post_attachment') || $modSettings['postmod_active'] && allowedTo('post_unapproved_attachments'))) {
        $del_temp = array();
        foreach ($_POST['attach_del'] as $i => $dummy) {
            $del_temp[$i] = (int) $dummy;
        }
        require_once $sourcedir . '/ManageAttachments.php';
        $attachmentQuery = array('attachment_type' => 0, 'id_msg' => (int) $_REQUEST['msg'], 'not_id_attach' => $del_temp);
        removeAttachments($attachmentQuery);
    }
    // ...or attach a new file...
    if (isset($_FILES['attachment']['name']) || !empty($_SESSION['temp_attachments']) && empty($_POST['from_qr'])) {
        // Verify they can post them!
        if (!$modSettings['postmod_active'] || !allowedTo('post_unapproved_attachments')) {
            isAllowedTo('post_attachment');
        }
        // Make sure we're uploading to the right place.
        if (!empty($modSettings['currentAttachmentUploadDir'])) {
            if (!is_array($modSettings['attachmentUploadDir'])) {
                $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
            }
            // The current directory, of course!
            $current_attach_dir = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
        } else {
            $current_attach_dir = $modSettings['attachmentUploadDir'];
        }
        // If this isn't a new post, check the current attachments.
        if (isset($_REQUEST['msg'])) {
            $request = $smcFunc['db_query']('', '
				SELECT COUNT(*), SUM(size)
				FROM {db_prefix}attachments
				WHERE id_msg = {int:id_msg}
					AND attachment_type = {int:attachment_type}', array('id_msg' => (int) $_REQUEST['msg'], 'attachment_type' => 0));
            list($quantity, $total_size) = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
        } else {
            $quantity = 0;
            $total_size = 0;
        }
        if (!empty($_SESSION['temp_attachments'])) {
            foreach ($_SESSION['temp_attachments'] as $attachID => $name) {
                if (preg_match('~^post_tmp_' . $user_info['id'] . '_\\d+$~', $attachID) == 0) {
                    continue;
                }
                if (!empty($_POST['attach_del']) && !in_array($attachID, $_POST['attach_del'])) {
                    unset($_SESSION['temp_attachments'][$attachID]);
                    @unlink($current_attach_dir . '/' . $attachID);
                    continue;
                }
                $_FILES['attachment']['tmp_name'][] = $attachID;
                $_FILES['attachment']['name'][] = $name;
                $_FILES['attachment']['size'][] = filesize($current_attach_dir . '/' . $attachID);
                list($_FILES['attachment']['width'][], $_FILES['attachment']['height'][]) = @getimagesize($current_attach_dir . '/' . $attachID);
                unset($_SESSION['temp_attachments'][$attachID]);
            }
        }
        if (!isset($_FILES['attachment']['name'])) {
            $_FILES['attachment']['tmp_name'] = array();
        }
        $attachIDs = array();
        foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy) {
            if ($_FILES['attachment']['name'][$n] == '') {
                continue;
            }
            // Have we reached the maximum number of files we are allowed?
            $quantity++;
            if (!empty($modSettings['attachmentNumPerPostLimit']) && $quantity > $modSettings['attachmentNumPerPostLimit']) {
                checkSubmitOnce('free');
                fatal_lang_error('attachments_limit_per_post', false, array($modSettings['attachmentNumPerPostLimit']));
            }
            // Check the total upload size for this post...
            $total_size += $_FILES['attachment']['size'][$n];
            if (!empty($modSettings['attachmentPostLimit']) && $total_size > $modSettings['attachmentPostLimit'] * 1024) {
                checkSubmitOnce('free');
                fatal_lang_error('file_too_big', false, array($modSettings['attachmentPostLimit']));
            }
            $attachmentOptions = array('post' => isset($_REQUEST['msg']) ? $_REQUEST['msg'] : 0, 'poster' => $user_info['id'], 'name' => $_FILES['attachment']['name'][$n], 'tmp_name' => $_FILES['attachment']['tmp_name'][$n], 'size' => $_FILES['attachment']['size'][$n], 'approved' => !$modSettings['postmod_active'] || allowedTo('post_attachment'));
            if (createAttachment($attachmentOptions)) {
                $attachIDs[] = $attachmentOptions['id'];
                if (!empty($attachmentOptions['thumb'])) {
                    $attachIDs[] = $attachmentOptions['thumb'];
                }
            } else {
                if (in_array('could_not_upload', $attachmentOptions['errors'])) {
                    checkSubmitOnce('free');
                    fatal_lang_error('attach_timeout', 'critical');
                }
                if (in_array('too_large', $attachmentOptions['errors'])) {
                    checkSubmitOnce('free');
                    fatal_lang_error('file_too_big', false, array($modSettings['attachmentSizeLimit']));
                }
                if (in_array('bad_extension', $attachmentOptions['errors'])) {
                    checkSubmitOnce('free');
                    fatal_error($attachmentOptions['name'] . '.<br />' . $txt['cant_upload_type'] . ' ' . $modSettings['attachmentExtensions'] . '.', false);
                }
                if (in_array('directory_full', $attachmentOptions['errors'])) {
                    checkSubmitOnce('free');
                    fatal_lang_error('ran_out_of_space', 'critical');
                }
                if (in_array('bad_filename', $attachmentOptions['errors'])) {
                    checkSubmitOnce('free');
                    fatal_error(basename($attachmentOptions['name']) . '.<br />' . $txt['restricted_filename'] . '.', 'critical');
                }
                if (in_array('taken_filename', $attachmentOptions['errors'])) {
                    checkSubmitOnce('free');
                    fatal_lang_error('filename_exists');
                }
                if (in_array('bad_attachment', $attachmentOptions['errors'])) {
                    checkSubmitOnce('free');
                    fatal_lang_error('bad_attachment');
                }
            }
        }
    }
    // Make the poll...
    if (isset($_REQUEST['poll'])) {
        // Create the poll.
        $smcFunc['db_insert']('', '{db_prefix}polls', array('question' => 'string-255', 'hide_results' => 'int', 'max_votes' => 'int', 'expire_time' => 'int', 'id_member' => 'int', 'poster_name' => 'string-255', 'change_vote' => 'int', 'guest_vote' => 'int'), array($_POST['question'], $_POST['poll_hide'], $_POST['poll_max_votes'], empty($_POST['poll_expire']) ? 0 : time() + $_POST['poll_expire'] * 3600 * 24, $user_info['id'], $_POST['guestname'], $_POST['poll_change_vote'], $_POST['poll_guest_vote']), array('id_poll'));
        $id_poll = $smcFunc['db_insert_id']('{db_prefix}polls', 'id_poll');
        // Create each answer choice.
        $i = 0;
        $pollOptions = array();
        foreach ($_POST['options'] as $option) {
            $pollOptions[] = array($id_poll, $i, $option);
            $i++;
        }
        $smcFunc['db_insert']('insert', '{db_prefix}poll_choices', array('id_poll' => 'int', 'id_choice' => 'int', 'label' => 'string-255'), $pollOptions, array('id_poll', 'id_choice'));
    } else {
        $id_poll = 0;
    }
    // Creating a new topic?
    $newTopic = empty($_REQUEST['msg']) && empty($topic);
    $_POST['icon'] = !empty($attachIDs) && $_POST['icon'] == 'xx' ? 'clip' : $_POST['icon'];
    // Collect all parameters for the creation or modification of a post.
    $msgOptions = array('id' => empty($_REQUEST['msg']) ? 0 : (int) $_REQUEST['msg'], 'subject' => $_POST['subject'], 'body' => $_POST['message'], 'icon' => preg_replace('~[\\./\\\\*:"\'<>]~', '', $_POST['icon']), 'smileys_enabled' => !isset($_POST['ns']), 'attachments' => empty($attachIDs) ? array() : $attachIDs, 'approved' => $becomesApproved);
    $topicOptions = array('id' => empty($topic) ? 0 : $topic, 'board' => $board, 'poll' => isset($_REQUEST['poll']) ? $id_poll : null, 'lock_mode' => isset($_POST['lock']) ? (int) $_POST['lock'] : null, 'sticky_mode' => isset($_POST['sticky']) && !empty($modSettings['enableStickyTopics']) ? (int) $_POST['sticky'] : null, 'mark_as_read' => true, 'is_approved' => !$modSettings['postmod_active'] || empty($topic) || !empty($board_info['cur_topic_approved']));
    $posterOptions = array('id' => $user_info['id'], 'name' => $_POST['guestname'], 'email' => $_POST['email'], 'update_post_count' => !$user_info['is_guest'] && !isset($_REQUEST['msg']) && $board_info['posts_count']);
    // This is an already existing message. Edit it.
    if (!empty($_REQUEST['msg'])) {
        // Have admins allowed people to hide their screwups?
        if (time() - $row['poster_time'] > $modSettings['edit_wait_time'] || $user_info['id'] != $row['id_member']) {
            $msgOptions['modify_time'] = time();
            $msgOptions['modify_name'] = $user_info['name'];
        }
        // This will save some time...
        if (empty($approve_has_changed)) {
            unset($msgOptions['approved']);
        }
        modifyPost($msgOptions, $topicOptions, $posterOptions);
    } else {
        createPost($msgOptions, $topicOptions, $posterOptions);
        if (isset($topicOptions['id'])) {
            $topic = $topicOptions['id'];
        }
    }
    // Editing or posting an event?
    if (isset($_POST['calendar']) && (!isset($_REQUEST['eventid']) || $_REQUEST['eventid'] == -1)) {
        require_once $sourcedir . '/Subs-Calendar.php';
        // Make sure they can link an event to this post.
        canLinkEvent();
        // Insert the event.
        $eventOptions = array('board' => $board, 'topic' => $topic, 'title' => $_POST['evtitle'], 'member' => $user_info['id'], 'start_date' => sprintf('%04d-%02d-%02d', $_POST['year'], $_POST['month'], $_POST['day']), 'span' => isset($_POST['span']) && $_POST['span'] > 0 ? min((int) $modSettings['cal_maxspan'], (int) $_POST['span'] - 1) : 0);
        insertEvent($eventOptions);
    } elseif (isset($_POST['calendar'])) {
        $_REQUEST['eventid'] = (int) $_REQUEST['eventid'];
        // Validate the post...
        require_once $sourcedir . '/Subs-Calendar.php';
        validateEventPost();
        // If you're not allowed to edit any events, you have to be the poster.
        if (!allowedTo('calendar_edit_any')) {
            // Get the event's poster.
            $request = $smcFunc['db_query']('', '
				SELECT id_member
				FROM {db_prefix}calendar
				WHERE id_event = {int:id_event}', array('id_event' => $_REQUEST['eventid']));
            $row2 = $smcFunc['db_fetch_assoc']($request);
            $smcFunc['db_free_result']($request);
            // Silly hacker, Trix are for kids. ...probably trademarked somewhere, this is FAIR USE! (parody...)
            isAllowedTo('calendar_edit_' . ($row2['id_member'] == $user_info['id'] ? 'own' : 'any'));
        }
        // Delete it?
        if (isset($_REQUEST['deleteevent'])) {
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}calendar
				WHERE id_event = {int:id_event}', array('id_event' => $_REQUEST['eventid']));
        } else {
            $span = !empty($modSettings['cal_allowspan']) && !empty($_REQUEST['span']) ? min((int) $modSettings['cal_maxspan'], (int) $_REQUEST['span'] - 1) : 0;
            $start_time = mktime(0, 0, 0, (int) $_REQUEST['month'], (int) $_REQUEST['day'], (int) $_REQUEST['year']);
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}calendar
				SET end_date = {date:end_date},
					start_date = {date:start_date},
					title = {string:title}
				WHERE id_event = {int:id_event}', array('end_date' => strftime('%Y-%m-%d', $start_time + $span * 86400), 'start_date' => strftime('%Y-%m-%d', $start_time), 'id_event' => $_REQUEST['eventid'], 'title' => $smcFunc['htmlspecialchars']($_REQUEST['evtitle'], ENT_QUOTES)));
        }
        updateSettings(array('calendar_updated' => time()));
    }
    // Marking read should be done even for editing messages....
    // Mark all the parents read.  (since you just posted and they will be unread.)
    if (!$user_info['is_guest'] && !empty($board_info['parent_boards'])) {
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}log_boards
			SET id_msg = {int:id_msg}
			WHERE id_member = {int:current_member}
				AND id_board IN ({array_int:board_list})', array('current_member' => $user_info['id'], 'board_list' => array_keys($board_info['parent_boards']), 'id_msg' => $modSettings['maxMsgID']));
    }
    // Turn notification on or off.  (note this just blows smoke if it's already on or off.)
    if (!empty($_POST['notify']) && allowedTo('mark_any_notify')) {
        $smcFunc['db_insert']('ignore', '{db_prefix}log_notify', array('id_member' => 'int', 'id_topic' => 'int', 'id_board' => 'int'), array($user_info['id'], $topic, 0), array('id_member', 'id_topic', 'id_board'));
    } elseif (!$newTopic) {
        $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}log_notify
			WHERE id_member = {int:current_member}
				AND id_topic = {int:current_topic}', array('current_member' => $user_info['id'], 'current_topic' => $topic));
    }
    // Log an act of moderation - modifying.
    if (!empty($moderationAction)) {
        logAction('modify', array('topic' => $topic, 'message' => (int) $_REQUEST['msg'], 'member' => $row['id_member'], 'board' => $board));
    }
    if (isset($_POST['lock']) && $_POST['lock'] != 2) {
        logAction('lock', array('topic' => $topicOptions['id'], 'board' => $topicOptions['board']));
    }
    if (isset($_POST['sticky']) && !empty($modSettings['enableStickyTopics'])) {
        logAction('sticky', array('topic' => $topicOptions['id'], 'board' => $topicOptions['board']));
    }
    // Notify any members who have notification turned on for this topic - only do this if it's going to be approved(!)
    if ($becomesApproved) {
        if ($newTopic) {
            $notifyData = array('body' => $_POST['message'], 'subject' => $_POST['subject'], 'name' => $user_info['name'], 'poster' => $user_info['id'], 'msg' => $msgOptions['id'], 'board' => $board, 'topic' => $topic);
            notifyMembersBoard($notifyData);
        } elseif (empty($_REQUEST['msg'])) {
            // Only send it to everyone if the topic is approved, otherwise just to the topic starter if they want it.
            if ($topic_info['approved']) {
                sendNotifications($topic, 'reply');
            } else {
                sendNotifications($topic, 'reply', array(), $topic_info['id_member_started']);
            }
        }
    }
    // Returning to the topic?
    if (!empty($_REQUEST['goback'])) {
        // Mark the board as read.... because it might get confusing otherwise.
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}log_boards
			SET id_msg = {int:maxMsgID}
			WHERE id_member = {int:current_member}
				AND id_board = {int:current_board}', array('current_board' => $board, 'current_member' => $user_info['id'], 'maxMsgID' => $modSettings['maxMsgID']));
    }
    if ($board_info['num_topics'] == 0) {
        cache_put_data('board-' . $board, null, 120);
    }
    if (!empty($_POST['announce_topic'])) {
        redirectexit('action=announce;sa=selectgroup;topic=' . $topic . (!empty($_POST['move']) && allowedTo('move_any') ? ';move' : '') . (empty($_REQUEST['goback']) ? '' : ';goback'));
    }
    if (!empty($_POST['move']) && allowedTo('move_any')) {
        redirectexit('action=movetopic;topic=' . $topic . '.0' . (empty($_REQUEST['goback']) ? '' : ';goback'));
    }
    // Return to post if the mod is on.
    if (isset($_REQUEST['msg']) && !empty($_REQUEST['goback'])) {
        redirectexit('topic=' . $topic . '.msg' . $_REQUEST['msg'] . '#msg' . $_REQUEST['msg'], $context['browser']['is_ie']);
    } elseif (!empty($_REQUEST['goback'])) {
        redirectexit('topic=' . $topic . '.new#new', $context['browser']['is_ie']);
    } else {
        redirectexit('board=' . $board . '.0');
    }
}
function cleanEditor()
{
    global $sourcedir;
    if (!empty($_REQUEST['descript_mode']) && isset($_REQUEST['descript'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_REQUEST['descript'] = html_to_bbc($_REQUEST['descript']);
        // We need to unhtml it now as it gets done shortly.
        $_REQUEST['descript'] = un_CleanAdkStrings($_REQUEST['descript']);
    }
}
Beispiel #6
0
function EditLink2()
{
    global $smcFunc, $txt, $user_info, $sourcedir;
    is_not_guest();
    checkSession('post');
    // Link ID; Required
    if (!empty($_REQUEST['id'])) {
        $id = (int) $_REQUEST['id'];
    }
    if (empty($id)) {
        fatal_error($txt['smflinks_nolinkselected']);
    }
    // Attempt to get the member id for this link.
    $dbresult = $smcFunc['db_query']('', '
		SELECT ID_MEMBER
		FROM {db_prefix}links
		WHERE ID_LINK = {int:this_id}
		LIMIT 1', array('this_id' => $id));
    // If we didn't get a row, it's an invalid ID.
    if ($smcFunc['db_num_rows']($dbresult) == 0) {
        fatal_error($txt['smflinks_nolinkselected'], false);
    } else {
        $row = $smcFunc['db_fetch_assoc']($dbresult);
    }
    // Free the result.
    $smcFunc['db_free_result']($dbresult);
    // If we can't edit this for some reason...
    if (!allowedTo('edit_links_any') && (!allowedTo('edit_links_own') || $row['ID_MEMBER'] != $user_info['id'])) {
        fatal_error($txt['smflinks_perm_link_no_edit']);
    }
    // If we came from WYSIWYG then turn it back into BBC regardless.
    if (!empty($_REQUEST['descript_mode']) && isset($_REQUEST['descript'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_REQUEST['descript'] = un_htmlspecialchars(html_to_bbc($_REQUEST['descript']));
    }
    // Category ID; Required
    if (!empty($_REQUEST['catid'])) {
        $catid = (int) $_REQUEST['catid'];
    }
    if (empty($catid)) {
        fatal_error($txt['smflinks_nocatselected'], false);
    }
    // Link Title; Required
    if (!empty($_POST['title'])) {
        $title = $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['title'], ENT_QUOTES));
    }
    if (empty($title)) {
        fatal_error($txt['smflinks_nolinktitle'], false);
    }
    // Link Description; Optional
    if (!empty($_REQUEST['descript'])) {
        $description = $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_REQUEST['descript'], ENT_QUOTES));
    }
    if (empty($description)) {
        fatal_error($txt['smflinks_nolinkdesc'], false);
    }
    // Link URL; Required
    if (!empty($_POST['url'])) {
        $url = addslashes($smcFunc['htmltrim']($_POST['url']));
    }
    if (empty($url)) {
        fatal_error($txt['smflinks_nolinkurl'], false);
    }
    // Pull our link information.
    $dbresult = $smcFunc['db_query']('', '
		SELECT ID_CAT, title, description, image, ID_PARENT 
		FROM {db_prefix}links_cat 
		WHERE ID_CAT = {int:this_cat}', array('this_cat' => $catid));
    // Invalid ID, huh? Tryin' to be sneaky.
    if ($smcFunc['db_num_rows']($dbresult) == 0) {
        fatal_error($txt['smflinks_nocatselected'], false);
    } else {
        $row = $smcFunc['db_fetch_assoc']($dbresult);
    }
    GetCatPermission($catid, 'editlink');
    $alexa = 0;
    $pagerank = 0;
    // Update the link
    $smcFunc['db_query']('', '
		UPDATE {db_prefix}links
		SET
			title = {string:title},
			url = {string:url},
			description = {string:description},
			alexa = {int:alexa},
			pagerank = {int:pagerank},
			ID_CAT = {int:this_cat}
		WHERE ID_LINK = {int:this_id}
		LIMIT 1', array('title' => $title, 'url' => $url, 'description' => $description, 'alexa' => $alexa, 'pagerank' => $pagerank, 'this_cat' => $catid, 'this_id' => $id));
    // Redirect back to category
    redirectexit('action=links;cat=' . $catid);
}
/**
 *	Loads any custom fields that are active
 *
 *	@param bool $is_ticket (default true) Whether to load custom fields based on editing a ticket or a message.
 *	@param int $ticketContext The appropriate value to load for; if editing a ticket this represents the ticket id, if editing a reply this represents the message id, if empty this is a new instance of either so no need to attempt loading data.
 *
 *	@since 2.0
*/
function shd_load_custom_fields($is_ticket = true, $ticketContext = 0, $dept = 0)
{
    global $sourcedir, $context, $smcFunc;
    $field_values = array();
    if (!empty($ticketContext)) {
        $query = shd_db_query('', '
			SELECT cfv.id_field, cfv.value
			FROM {db_prefix}helpdesk_custom_fields_values AS cfv
			WHERE cfv.id_post = {int:ticketContext}
				AND cfv.post_type = {int:field_type}', array('ticketContext' => $ticketContext, 'field_type' => $is_ticket ? CFIELD_TICKET : CFIELD_REPLY));
        while ($row = $smcFunc['db_fetch_assoc']($query)) {
            $field_values[$row['id_field']] = $row['value'];
        }
        $smcFunc['db_free_result']($query);
    }
    // Load up our custom field defintions from the database
    $custom_fields = shd_db_query('', '
		SELECT cf.id_field, cf.active, cf.field_order, cf.field_name, cf.field_desc, cf.field_loc, cf.icon,
			cf.field_type, cf.field_options, cf.default_value, cf.bbc, cf.can_see, cf.can_edit, cf.field_length,
			cf.display_empty, cfd.required, cf.placement, cfd.id_dept
		FROM {db_prefix}helpdesk_custom_fields AS cf
			INNER JOIN {db_prefix}helpdesk_custom_fields_depts AS cfd ON (cf.id_field = cfd.id_field' . (!empty($dept) ? ' AND cfd.id_dept = {int:dept}' : '') . ')
		WHERE cf.active = 1
			AND cf.field_loc IN ({array_int:visibility})
		ORDER BY cf.field_order', array('visibility' => $is_ticket ? array(CFIELD_TICKET, CFIELD_REPLY | CFIELD_TICKET) : array(CFIELD_REPLY, CFIELD_REPLY | CFIELD_TICKET), 'dept' => $dept));
    $context['ticket_form']['custom_fields'] = array();
    $loc = $is_ticket ? 'ticket' : $ticketContext;
    $is_staff = shd_allowed_to('shd_staff', $dept);
    $is_admin = shd_allowed_to('admin_helpdesk', $dept);
    // this includes forum admins
    // Loop through all fields and figure out where they should be.
    while ($row = $smcFunc['db_fetch_assoc']($custom_fields)) {
        // Can the user even see this field? If we can't see the field, it doesn't exist to us for posting purposes.
        list($user_see, $staff_see) = explode(',', $row['can_see']);
        list($user_edit, $staff_edit) = explode(',', $row['can_edit']);
        if ($is_admin) {
            $editable = true;
        } elseif ($is_staff) {
            if ($staff_see == 0) {
                continue;
            }
            $editable = $staff_edit == 1;
        } elseif ($user_see == 1) {
            $editable = $user_edit == 1;
        } else {
            continue;
        }
        // Load up the fields and do some extra parsing
        if (!isset($context['ticket_form']['custom_fields'][$loc][$row['id_field']])) {
            $context['ticket_form']['custom_fields'][$loc][$row['id_field']] = array('id' => $row['id_field'], 'order' => $row['field_order'], 'location' => $row['field_loc'], 'length' => $row['field_length'], 'name' => $row['field_name'], 'desc' => parse_bbc($row['field_desc'], false), 'icon' => $row['icon'], 'options' => !empty($row['field_options']) ? unserialize($row['field_options']) : array(), 'type' => $row['field_type'], 'default_value' => $row['field_type'] == CFIELD_TYPE_LARGETEXT ? explode(',', $row['default_value']) : $row['default_value'], 'display_empty' => !empty($row['required']) ? 1 : $row['display_empty'], 'bbc' => !empty($row['bbc']), 'is_required' => $row['field_type'] == CFIELD_TYPE_MULTI ? (int) $row['required'] : !empty($row['required']), 'visible' => array($user_see, $staff_see), 'editable' => !empty($editable), 'depts' => array());
            if ($row['field_type'] == CFIELD_TYPE_RADIO || $row['field_type'] == CFIELD_TYPE_MULTI) {
                foreach ($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options'] as $k => $v) {
                    if ($k != 'inactive') {
                        $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options'][$k] = strpos($v, '[') !== false ? parse_bbc($v) : $v;
                    }
                }
            } elseif ($row['field_type'] == CFIELD_TYPE_SELECT) {
                foreach ($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options'] as $k => $v) {
                    if ($k != 'inactive') {
                        $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options'][$k] = strpos($v, '[') !== false ? trim(strip_tags(parse_bbc($v))) : trim($v);
                    }
                }
            }
        }
        $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['depts'][] = $row['id_dept'];
        if (!empty($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options']) && empty($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options']['inactive'])) {
            $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options']['inactive'] = array();
        }
        if (isset($field_values[$row['id_field']])) {
            if ($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['type'] == CFIELD_TYPE_MULTI) {
                $field_values[$row['id_field']] = explode(',', $field_values[$row['id_field']]);
            }
            // Large text boxes may need fixing.
            if ($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['type'] == CFIELD_TYPE_LARGETEXT) {
                require_once $sourcedir . '/Subs-Editor.php';
                $field_values[$row['id_field']] = html_to_bbc($field_values[$row['id_field']]);
            }
            $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['value'] = $field_values[$row['id_field']];
        }
    }
    $context['ticket_form']['custom_fields_context'] = $loc;
}
Beispiel #8
0
function EditLink2()
{
    global $smcFunc, $txt, $user_info, $sourcedir;
    is_not_guest();
    checkSession('post');
    $id = (int) $_REQUEST['id'];
    $dbresult = $smcFunc['db_query']('', "\n\tSELECT\n\t\tID_MEMBER\n\tFROM {db_prefix}links\n\tWHERE ID_LINK = {$id} LIMIT 1");
    $row = $smcFunc['db_fetch_assoc']($dbresult);
    $smcFunc['db_free_result']($dbresult);
    if (!allowedTo('edit_links_any') && (!allowedTo('edit_links_own') || $row['ID_MEMBER'] != $user_info['id'])) {
        fatal_error($txt['smflinks_perm_link_no_edit']);
    }
    // If we came from WYSIWYG then turn it back into BBC regardless.
    if (!empty($_REQUEST['descript_mode']) && isset($_REQUEST['descript'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_REQUEST['descript'] = html_to_bbc($_REQUEST['descript']);
        // We need to unhtml it now as it gets done shortly.
        $_REQUEST['descript'] = un_htmlspecialchars($_REQUEST['descript']);
    }
    // Clean the input
    $title = $smcFunc['htmlspecialchars'](trim($_POST['title']), ENT_QUOTES);
    $description = $smcFunc['htmlspecialchars']($_REQUEST['descript'], ENT_QUOTES);
    $url = addslashes(trim($_POST['url']));
    $catid = (int) $_REQUEST['catid'];
    $dbresult = $smcFunc['db_query']('', "\n\tSELECT \n\t\tID_CAT, title, description, image, ID_PARENT \n\tFROM {db_prefix}links_cat \n\tWHERE ID_CAT = {$catid}");
    $row = $smcFunc['db_fetch_assoc']($dbresult);
    if (empty($row['ID_CAT'])) {
        fatal_error($txt['smflinks_nocatselected'], false);
    }
    GetCatPermission($catid, 'editlink');
    if ($title == '') {
        fatal_error($txt['smflinks_nolinktitle'], false);
    }
    if ($url == '') {
        fatal_error($txt['smflinks_nolinkurl'], false);
    }
    $alexa = 0;
    $pagerank = 0;
    // Update the link
    $smcFunc['db_query']('', "UPDATE {db_prefix}links\n\t\tSET title = '{$title}',url= '{$url}', description = '{$description}', alexa = {$alexa}, pagerank = {$pagerank}, ID_CAT = {$catid} WHERE ID_LINK = {$id} LIMIT 1");
    // Redirect back to category
    redirectexit('action=links');
}
Beispiel #9
0
function EditLink2()
{
    global $smcFunc, $txt, $user_info, $sourcedir;
    is_not_guest();
    checkSession('post');
    if (!empty($_REQUEST['id'])) {
        $id = (int) $_REQUEST['id'];
    }
    if (empty($_REQUEST['id'])) {
        fatal_error($txt['smflinks_nolinkselected']);
    }
    $dbresult = $smcFunc['db_query']('', '
		SELECT ID_MEMBER
		FROM {db_prefix}links
		WHERE ID_LINK = {int:this_id}
		LIMIT 1', array('this_id' => $id));
    $row = $smcFunc['db_fetch_assoc']($dbresult);
    $smcFunc['db_free_result']($dbresult);
    if (!allowedTo('edit_links_any') && (!allowedTo('edit_links_own') || $row['ID_MEMBER'] != $user_info['id'])) {
        fatal_error($txt['smflinks_perm_link_no_edit']);
    }
    // If we came from WYSIWYG then turn it back into BBC regardless.
    if (!empty($_REQUEST['descript_mode']) && isset($_REQUEST['descript'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_REQUEST['descript'] = un_htmlspecialchars(html_to_bbc($_REQUEST['descript']));
    }
    // Clean the input
    if (!empty($_POST['title'])) {
        $title = $smcFunc['htmlspecialchars'](trim($_POST['title']), ENT_QUOTES);
    } else {
        $title = '';
    }
    if (!empty($_REQUEST['descript'])) {
        $description = $smcFunc['htmlspecialchars']($_REQUEST['descript'], ENT_QUOTES);
    } else {
        $description = '';
    }
    if (!empty($_POST['url'])) {
        $url = addslashes(trim($_POST['url']));
    } else {
        $url = '';
    }
    if (!empty($_REQUEST['catid'])) {
        $catid = (int) $_REQUEST['catid'];
    } else {
        $catid = 0;
    }
    if (empty($catid)) {
        fatal_error($txt['smflinks_nocatselected']);
    }
    $dbresult = $smcFunc['db_query']('', '
		SELECT ID_CAT, title, description, image, ID_PARENT 
		FROM {db_prefix}links_cat 
		WHERE ID_CAT = {int:this_cat}', array('this_cat' => $catid));
    $row = $smcFunc['db_fetch_assoc']($dbresult);
    if (empty($row['ID_CAT'])) {
        fatal_error($txt['smflinks_nocatselected'], false);
    }
    GetCatPermission($catid, 'editlink');
    if (empty($title)) {
        fatal_error($txt['smflinks_nolinktitle'], false);
    } elseif (empty($url)) {
        fatal_error($txt['smflinks_nolinkurl'], false);
    }
    $alexa = 0;
    $pagerank = 0;
    // Update the link
    $smcFunc['db_query']('', '
		UPDATE {db_prefix}links
		SET
			title = {string:title},
			url = {string:url},
			description = {string:description},
			alexa = {int:alexa},
			pagerank = {int:pagerank},
			ID_CAT = {int:this_cat}
		WHERE ID_LINK = {int:this_id}
		LIMIT 1', array('title' => $title, 'url' => $url, 'description' => $description, 'alexa' => $alexa, 'pagerank' => $pagerank, 'this_cat' => $catid, 'this_id' => $id));
    // Redirect back to category
    redirectexit('action=links');
}
function sportal_admin_block_edit()
{
    global $txt, $context, $modSettings, $smcFunc, $sourcedir, $boarddir, $boards;
    // Just in case, the admin could be doing something silly like editing a SP block while SP it disabled. ;)
    require_once $sourcedir . '/PortalBlocks.php';
    $context['SPortal']['is_new'] = empty($_REQUEST['block_id']);
    // BBC Fix move the parameter to the correct position.
    if (!empty($_POST['bbc_name'])) {
        $_POST['parameters'][$_POST['bbc_name']] = !empty($_POST[$_POST['bbc_parameter']]) ? $_POST[$_POST['bbc_parameter']] : '';
        // If we came from WYSIWYG then turn it back into BBC regardless.
        if (!empty($_REQUEST['bbc_' . $_POST['bbc_name'] . '_mode']) && isset($_POST['parameters'][$_POST['bbc_name']])) {
            require_once $sourcedir . '/Subs-Editor.php';
            $_POST['parameters'][$_POST['bbc_name']] = html_to_bbc($_POST['parameters'][$_POST['bbc_name']]);
            // We need to unhtml it now as it gets done shortly.
            $_POST['parameters'][$_POST['bbc_name']] = un_htmlspecialchars($_POST['parameters'][$_POST['bbc_name']]);
            // We need this for everything else.
            $_POST['parameters'][$_POST['bbc_name']] = $_POST['parameters'][$_POST['bbc_name']];
        }
    }
    // Passing the selected type via $_GET instead of $_POST?
    $start_parameters = array();
    if (!empty($_GET['selected_type']) && empty($_POST['selected_type'])) {
        $_POST['selected_type'] = array($_GET['selected_type']);
        if (!empty($_GET['parameters'])) {
            foreach ($_GET['parameters'] as $param) {
                if (isset($_GET[$param])) {
                    $start_parameters[$param] = $_GET[$param];
                }
            }
        }
    }
    if ($context['SPortal']['is_new'] && empty($_POST['selected_type']) && empty($_POST['add_block'])) {
        $context['SPortal']['block_types'] = getFunctionInfo();
        if (!empty($_REQUEST['col'])) {
            $context['SPortal']['block']['column'] = $_REQUEST['col'];
        }
        $context['sub_template'] = 'block_select_type';
        $context['page_title'] = $txt['sp-blocksAdd'];
    } elseif ($context['SPortal']['is_new'] && !empty($_POST['selected_type'])) {
        $context['SPortal']['block'] = array('id' => 0, 'label' => $txt['sp-blocksDefaultLabel'], 'type' => $_POST['selected_type'][0], 'type_text' => !empty($txt['sp_function_' . $_POST['selected_type'][0] . '_label']) ? $txt['sp_function_' . $_POST['selected_type'][0] . '_label'] : $txt['sp_function_unknown_label'], 'column' => !empty($_POST['block_column']) ? $_POST['block_column'] : 0, 'row' => 0, 'permission_set' => 3, 'groups_allowed' => array(), 'groups_denied' => array(), 'state' => 1, 'force_view' => 0, 'display' => '', 'display_custom' => '', 'style' => '', 'parameters' => !empty($start_parameters) ? $start_parameters : array(), 'options' => $_POST['selected_type'][0](array(), false, true), 'list_blocks' => !empty($_POST['block_column']) ? getBlockInfo($_POST['block_column']) : array());
    } elseif (!$context['SPortal']['is_new'] && empty($_POST['add_block'])) {
        $_REQUEST['block_id'] = (int) $_REQUEST['block_id'];
        $context['SPortal']['block'] = current(getBlockInfo(null, $_REQUEST['block_id']));
        $context['SPortal']['block'] += array('options' => $context['SPortal']['block']['type'](array(), false, true), 'list_blocks' => getBlockInfo($context['SPortal']['block']['column']));
    }
    if (!empty($_POST['preview_block'])) {
        // Just in case, the admin could be doing something silly like editing a SP block while SP it disabled. ;)
        require_once $boarddir . '/SSI.php';
        sportal_init_headers();
        loadTemplate('Portal');
        $type_parameters = $_POST['block_type'](array(), 0, true);
        if (!empty($_POST['parameters']) && is_array($_POST['parameters']) && !empty($type_parameters)) {
            foreach ($type_parameters as $name => $type) {
                if (isset($_POST['parameters'][$name])) {
                    if ($type == 'bbc') {
                        $parameter['value'] = $_POST['parameters'][$name];
                        require_once $sourcedir . '/Subs-Post.php';
                        $parameter['value'] = $smcFunc['htmlspecialchars']($parameter['value'], ENT_QUOTES);
                        preparsecode($parameter['value']);
                        $_POST['parameters'][$name] = $parameter['value'];
                    } elseif ($type == 'boards' || $type == 'board_select') {
                        $_POST['parameters'][$name] = is_array($_POST['parameters'][$name]) ? implode('|', $_POST['parameters'][$name]) : $_POST['parameters'][$name];
                    } elseif ($type == 'int' || $type == 'select') {
                        $_POST['parameters'][$name] = (int) $_POST['parameters'][$name];
                    } elseif ($type == 'text' || $type == 'textarea' || is_array($type)) {
                        $_POST['parameters'][$name] = $smcFunc['htmlspecialchars']($_POST['parameters'][$name], ENT_QUOTES);
                    } elseif ($type == 'check') {
                        $_POST['parameters'][$name] = !empty($_POST['parameters'][$name]) ? 1 : 0;
                    }
                }
            }
        } else {
            $_POST['parameters'] = array();
        }
        if (empty($_POST['display_advanced'])) {
            if (!empty($_POST['display_simple']) && in_array($_POST['display_simple'], array('all', 'sportal', 'sforum', 'allaction', 'allboard', 'allpages'))) {
                $display = $_POST['display_simple'];
            } else {
                $display = '';
            }
            $custom = '';
        } else {
            $display = array();
            $custom = array();
            if (!empty($_POST['display_actions'])) {
                foreach ($_POST['display_actions'] as $action) {
                    $display[] = $smcFunc['htmlspecialchars']($action, ENT_QUOTES);
                }
            }
            if (!empty($_POST['display_boards'])) {
                foreach ($_POST['display_boards'] as $board) {
                    $display[] = 'b' . (int) substr($board, 1);
                }
            }
            if (!empty($_POST['display_pages'])) {
                foreach ($_POST['display_pages'] as $page) {
                    $display[] = 'p' . (int) substr($page, 1);
                }
            }
            if (!empty($_POST['display_custom'])) {
                $temp = explode(',', $_POST['display_custom']);
                foreach ($temp as $action) {
                    $custom[] = $smcFunc['htmlspecialchars']($smcFunc['htmltrim']($action), ENT_QUOTES);
                }
            }
            $display = empty($display) ? '' : implode(',', $display);
            $custom = empty($custom) ? '' : implode(',', $custom);
        }
        $permission_set = 0;
        $groups_allowed = $groups_denied = array();
        if (!empty($_POST['permission_set'])) {
            $permission_set = (int) $_POST['permission_set'];
        } elseif (!empty($_POST['membergroups']) && is_array($_POST['membergroups'])) {
            foreach ($_POST['membergroups'] as $id => $value) {
                if ($value == 1) {
                    $groups_allowed[] = (int) $id;
                } elseif ($value == -1) {
                    $groups_denied[] = (int) $id;
                }
            }
        }
        $context['SPortal']['block'] = array('id' => $_POST['block_id'], 'label' => $smcFunc['htmlspecialchars']($_POST['block_name'], ENT_QUOTES), 'type' => $_POST['block_type'], 'type_text' => !empty($txt['sp_function_' . $_POST['block_type'] . '_label']) ? $txt['sp_function_' . $_POST['block_type'] . '_label'] : $txt['sp_function_unknown_label'], 'column' => $_POST['block_column'], 'row' => !empty($_POST['block_row']) ? $_POST['block_row'] : 0, 'permission_set' => $permission_set, 'groups_allowed' => $groups_allowed, 'groups_denied' => $groups_denied, 'state' => !empty($_POST['block_active']), 'force_view' => !empty($_POST['block_force']), 'display' => $display, 'display_custom' => $custom, 'style' => sportal_parse_style('implode'), 'parameters' => !empty($_POST['parameters']) ? $_POST['parameters'] : array(), 'options' => $_POST['block_type'](array(), false, true), 'list_blocks' => getBlockInfo($_POST['block_column']), 'collapsed' => false);
        if (strpos($modSettings['leftwidth'], '%') !== false || strpos($modSettings['leftwidth'], 'px') !== false) {
            $context['widths'][1] = $modSettings['leftwidth'];
        } else {
            $context['widths'][1] = $modSettings['leftwidth'] . 'px';
        }
        if (strpos($modSettings['rightwidth'], '%') !== false || strpos($modSettings['rightwidth'], 'px') !== false) {
            $context['widths'][4] = $modSettings['rightwidth'];
        } else {
            $context['widths'][4] = $modSettings['rightwidth'] . 'px';
        }
        if (strpos($context['widths'][1], '%') !== false) {
            $context['widths'][2] = $context['widths'][3] = 100 - ($context['widths'][1] + $context['widths'][4]) . '%';
        } elseif (strpos($context['widths'][1], 'px') !== false) {
            $context['widths'][2] = $context['widths'][3] = 960 - ($context['widths'][1] + $context['widths'][4]) . 'px';
        }
        if (strpos($context['widths'][1], '%') !== false) {
            $context['widths'][2] = $context['widths'][3] = 100 - ($context['widths'][1] + $context['widths'][4]) . '%';
            $context['widths'][5] = $context['widths'][6] = '100%';
        } elseif (strpos($context['widths'][1], 'px') !== false) {
            $context['widths'][2] = $context['widths'][3] = 960 - ($context['widths'][1] + $context['widths'][4]) . 'px';
            $context['widths'][5] = $context['widths'][6] = '960px';
        }
        $context['SPortal']['preview'] = true;
    }
    if (!empty($_POST['selected_type']) || !empty($_POST['preview_block']) || !$context['SPortal']['is_new'] && empty($_POST['add_block'])) {
        if ($context['SPortal']['block']['type'] == 'sp_php' && !allowedTo('admin_forum')) {
            fatal_lang_error('cannot_admin_forum', false);
        }
        $context['html_headers'] .= '
	<script language="JavaScript" type="text/javascript"><!-- // --><![CDATA[
		function sp_collapseObject(id)
		{
			mode = document.getElementById("sp_object_" + id).style.display == "" ? 0 : 1;
			document.getElementById("sp_collapse_" + id).src = smf_images_url + (mode ? "/collapse.gif" : "/expand.gif");
			document.getElementById("sp_object_" + id).style.display = mode ? "" : "none";
		}
	// ]]></script>';
        loadLanguage('SPortalHelp', sp_languageSelect('SPortalHelp'));
        $context['SPortal']['block']['groups'] = sp_load_membergroups();
        $context['simple_actions'] = array('sportal' => $txt['sp-portal'], 'sforum' => $txt['sp-forum'], 'allaction' => $txt['sp-blocksOptionAllActions'], 'allboard' => $txt['sp-blocksOptionAllBoards'], 'allpages' => $txt['sp-blocksOptionAllPages'], 'all' => $txt['sp-blocksOptionEverywhere']);
        $context['display_actions'] = array('portal' => $txt['sp-portal'], 'forum' => $txt['sp-forum'], 'recent' => $txt['recent_posts'], 'unread' => $txt['unread_topics_visit'], 'unreadreplies' => $txt['unread_replies'], 'profile' => $txt['profile'], 'pm' => $txt['pm_short'], 'calendar' => $txt['calendar'], 'admin' => $txt['admin'], 'login' => $txt['login'], 'register' => $txt['register'], 'post' => $txt['post'], 'stats' => $txt['forum_stats'], 'search' => $txt['search'], 'mlist' => $txt['members_list'], 'moderate' => $txt['moderate'], 'help' => $txt['help'], 'who' => $txt['who_title']);
        $request = $smcFunc['db_query']('', '
			SELECT id_board, name
			FROM {db_prefix}boards
			ORDER BY name DESC');
        $context['display_boards'] = array();
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $context['display_boards']['b' . $row['id_board']] = $row['name'];
        }
        $smcFunc['db_free_result']($request);
        $request = $smcFunc['db_query']('', '
			SELECT id_page, title
			FROM {db_prefix}sp_pages
			ORDER BY title DESC');
        $context['display_pages'] = array();
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $context['display_pages']['p' . $row['id_page']] = $row['title'];
        }
        $smcFunc['db_free_result']($request);
        if (empty($context['SPortal']['block']['display'])) {
            $context['SPortal']['block']['display'] = array('0');
        } else {
            $context['SPortal']['block']['display'] = explode(',', $context['SPortal']['block']['display']);
        }
        if (in_array($context['SPortal']['block']['display'][0], array('all', 'sportal', 'sforum', 'allaction', 'allboard', 'allpages')) || $context['SPortal']['is_new'] || empty($context['SPortal']['block']['display'][0]) && empty($context['SPortal']['block']['display_custom'])) {
            $context['SPortal']['block']['display_type'] = 0;
        } else {
            $context['SPortal']['block']['display_type'] = 1;
        }
        $context['SPortal']['block']['style'] = sportal_parse_style('explode', $context['SPortal']['block']['style'], !empty($context['SPortal']['preview']));
        // Prepare the Textcontent for BBC, only the first bbc will be correct detected! (SMF Support only 1 per page with the standard function)
        $firstBBCFound = false;
        foreach ($context['SPortal']['block']['options'] as $name => $type) {
            // Selectable Boards :D
            if ($type == 'board_select' || $type == 'boards') {
                if (empty($boards)) {
                    require_once $sourcedir . '/Subs-Boards.php';
                    getBoardTree();
                }
                // Merge the array ;). (Only in 2.0 needed)
                if (!isset($context['SPortal']['block']['parameters'][$name])) {
                    $context['SPortal']['block']['parameters'][$name] = array();
                } elseif (!empty($context['SPortal']['block']['parameters'][$name]) && is_array($context['SPortal']['block']['parameters'][$name])) {
                    $context['SPortal']['block']['parameters'][$name] = implode('|', $context['SPortal']['block']['parameters'][$name]);
                }
                $context['SPortal']['block']['board_options'][$name] = array();
                $config_variable = !empty($context['SPortal']['block']['parameters'][$name]) ? $context['SPortal']['block']['parameters'][$name] : array();
                $config_variable = !is_array($config_variable) ? explode('|', $config_variable) : $config_variable;
                $context['SPortal']['block']['board_options'][$name] = array();
                // Create the list for this Item
                foreach ($boards as $board) {
                    if (!empty($board['redirect'])) {
                        // Ignore the redirected boards :)
                        continue;
                    }
                    $context['SPortal']['block']['board_options'][$name][$board['id']] = array('value' => $board['id'], 'text' => $board['name'], 'selected' => in_array($board['id'], $config_variable));
                }
            } elseif ($type == 'bbc') {
                // SMF support only one bbc correct, multiple bbc do not work at the moment
                if (!$firstBBCFound) {
                    $firstBBCFound = true;
                    // Start SMF BBC Sytem :)
                    require_once $sourcedir . '/Subs-Editor.php';
                    // Prepare the output :D
                    $form_message = !empty($context['SPortal']['block']['parameters'][$name]) ? $context['SPortal']['block']['parameters'][$name] : '';
                    // But if it's in HTML world, turn them into htmlspecialchar's so they can be edited!
                    if (strpos($form_message, '[html]') !== false) {
                        $parts = preg_split('~(\\[/code\\]|\\[code(?:=[^\\]]+)?\\])~i', $form_message, -1, PREG_SPLIT_DELIM_CAPTURE);
                        for ($i = 0, $n = count($parts); $i < $n; $i++) {
                            // It goes 0 = outside, 1 = begin tag, 2 = inside, 3 = close tag, repeat.
                            if ($i % 4 == 0) {
                                $parts[$i] = preg_replace('~\\[html\\](.+?)\\[/html\\]~ise', '\'[html]\' . preg_replace(\'~<br\\s?/?>~i\', \'&lt;br /&gt;<br />\', \'$1\') . \'[/html]\'', $parts[$i]);
                            }
                        }
                        $form_message = implode('', $parts);
                    }
                    $form_message = preg_replace('~<br(?: /)?' . '>~i', "\n", $form_message);
                    // Prepare the data before i want them inside the textarea
                    $form_message = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), $form_message);
                    $context['SPortal']['bbc'] = 'bbc_' . $name;
                    $message_data = array('id' => $context['SPortal']['bbc'], 'width' => '95%', 'height' => '200px', 'value' => $form_message, 'form' => 'sp_block');
                    // Run the SMF bbc editor rutine
                    create_control_richedit($message_data);
                    // Store the updated data on the parameters
                    $context['SPortal']['block']['parameters'][$name] = $form_message;
                } else {
                    $context['SPortal']['block']['options'][$name] = 'textarea';
                }
            }
        }
        $context['sub_template'] = 'block_edit';
        $context['page_title'] = $context['SPortal']['is_new'] ? $txt['sp-blocksAdd'] : $txt['sp-blocksEdit'];
    }
    if (!empty($_POST['add_block'])) {
        if ($_POST['block_type'] == 'sp_php' && !allowedTo('admin_forum')) {
            fatal_lang_error('cannot_admin_forum', false);
        }
        if (!isset($_POST['block_name']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['block_name']), ENT_QUOTES) === '') {
            fatal_lang_error('error_sp_name_empty', false);
        }
        if ($_POST['block_type'] == 'sp_php' && !empty($_POST['parameters']['content']) && empty($modSettings['sp_disable_php_validation'])) {
            $error = sp_validate_php($_POST['parameters']['content']);
            if ($error) {
                fatal_lang_error('error_sp_php_' . $error, false);
            }
        }
        if (!empty($_REQUEST['block_id'])) {
            $current_data = current(getBlockInfo(null, $_REQUEST['block_id']));
        }
        if (!empty($_POST['placement']) && ($_POST['placement'] == 'before' || $_POST['placement'] == 'after')) {
            if (!empty($current_data)) {
                $current_row = $current_data['row'];
            } else {
                $current_row = null;
            }
            if ($_POST['placement'] == 'before') {
                $row = (int) $_POST['block_row'];
            } else {
                $row = (int) $_POST['block_row'] + 1;
            }
            if (!empty($current_row) && $row > $current_row) {
                $row = $row - 1;
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}sp_blocks
					SET row = row - 1
					WHERE col = {int:col}
						AND row > {int:start}
						AND row <= {int:end}', array('col' => (int) $_POST['block_column'], 'start' => $current_row, 'end' => $row));
            } else {
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}sp_blocks
					SET row = row + 1
					WHERE col = {int:col}
						AND row >= {int:start}' . (!empty($current_row) ? '
						AND row < {int:end}' : ''), array('col' => (int) $_POST['block_column'], 'start' => $row, 'end' => !empty($current_row) ? $current_row : 0));
            }
        } elseif (!empty($_POST['placement']) && $_POST['placement'] == 'nochange') {
            $row = 0;
        } else {
            $request = $smcFunc['db_query']('', '
				SELECT row
				FROM {db_prefix}sp_blocks
				WHERE col = {int:col}' . (!empty($_REQUEST['block_id']) ? '
					AND id_block != {int:current_id}' : '') . '
				ORDER BY row DESC
				LIMIT 1', array('col' => $_POST['block_column'], 'current_id' => $_REQUEST['block_id']));
            list($row) = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
            $row = $row + 1;
        }
        $type_parameters = $_POST['block_type'](array(), 0, true);
        if (!empty($_POST['parameters']) && is_array($_POST['parameters']) && !empty($type_parameters)) {
            foreach ($type_parameters as $name => $type) {
                if (isset($_POST['parameters'][$name])) {
                    // Prepare BBC Content for SMF 2 special case =D
                    if ($type == 'bbc') {
                        $parameter['value'] = $_POST['parameters'][$name];
                        require_once $sourcedir . '/Subs-Post.php';
                        // Prepare the message a bit for some additional testing.
                        $parameter['value'] = $smcFunc['htmlspecialchars']($parameter['value'], ENT_QUOTES);
                        preparsecode($parameter['value']);
                        //Store now the correct and fixed value ;)
                        $_POST['parameters'][$name] = $parameter['value'];
                    } elseif ($type == 'boards' || $type == 'board_select') {
                        $_POST['parameters'][$name] = is_array($_POST['parameters'][$name]) ? implode('|', $_POST['parameters'][$name]) : $_POST['parameters'][$name];
                    } elseif ($type == 'int' || $type == 'select') {
                        $_POST['parameters'][$name] = (int) $_POST['parameters'][$name];
                    } elseif ($type == 'text' || $type == 'textarea' || is_array($type)) {
                        $_POST['parameters'][$name] = $smcFunc['htmlspecialchars']($_POST['parameters'][$name], ENT_QUOTES);
                    } elseif ($type == 'check') {
                        $_POST['parameters'][$name] = !empty($_POST['parameters'][$name]) ? 1 : 0;
                    }
                }
            }
        } else {
            $_POST['parameters'] = array();
        }
        $permission_set = 0;
        $groups_allowed = $groups_denied = '';
        if (!empty($_POST['permission_set'])) {
            $permission_set = (int) $_POST['permission_set'];
        } elseif (!empty($_POST['membergroups']) && is_array($_POST['membergroups'])) {
            $groups_allowed = $groups_denied = array();
            foreach ($_POST['membergroups'] as $id => $value) {
                if ($value == 1) {
                    $groups_allowed[] = (int) $id;
                } elseif ($value == -1) {
                    $groups_denied[] = (int) $id;
                }
            }
            $groups_allowed = implode(',', $groups_allowed);
            $groups_denied = implode(',', $groups_denied);
        }
        if (empty($_POST['display_advanced'])) {
            if (!empty($_POST['display_simple']) && in_array($_POST['display_simple'], array('all', 'sportal', 'sforum', 'allaction', 'allboard', 'allpages'))) {
                $display = $_POST['display_simple'];
            } else {
                $display = '';
            }
            $custom = '';
        } else {
            $display = array();
            if (!empty($_POST['display_actions'])) {
                foreach ($_POST['display_actions'] as $action) {
                    $display[] = $smcFunc['htmlspecialchars']($action, ENT_QUOTES);
                }
            }
            if (!empty($_POST['display_boards'])) {
                foreach ($_POST['display_boards'] as $board) {
                    $display[] = 'b' . (int) substr($board, 1);
                }
            }
            if (!empty($_POST['display_pages'])) {
                foreach ($_POST['display_pages'] as $page) {
                    $display[] = 'p' . (int) substr($page, 1);
                }
            }
            if (!empty($_POST['display_custom'])) {
                $temp = explode(',', $_POST['display_custom']);
                foreach ($temp as $action) {
                    $custom[] = $smcFunc['htmlspecialchars']($smcFunc['htmltrim']($action), ENT_QUOTES);
                }
            }
            $display = empty($display) ? '' : implode(',', $display);
            if (!allowedTo('admin_forum') && isset($current_data['display_custom']) && substr($current_data['display_custom'], 0, 4) === '$php') {
                $custom = $current_data['display_custom'];
            } elseif (!empty($_POST['display_custom'])) {
                if (allowedTo('admin_forum') && substr($_POST['display_custom'], 0, 4) === '$php') {
                    $custom = $smcFunc['htmlspecialchars']($_POST['display_custom'], ENT_QUOTES);
                } else {
                    $custom = array();
                    $temp = explode(',', $_POST['display_custom']);
                    foreach ($temp as $action) {
                        $custom[] = $smcFunc['htmlspecialchars']($action, ENT_QUOTES);
                    }
                    $custom = empty($custom) ? '' : implode(',', $custom);
                }
            } else {
                $custom = '';
            }
        }
        $blockInfo = array('id' => (int) $_POST['block_id'], 'label' => $smcFunc['htmlspecialchars']($_POST['block_name'], ENT_QUOTES), 'type' => $_POST['block_type'], 'col' => $_POST['block_column'], 'row' => $row, 'permission_set' => $permission_set, 'groups_allowed' => $groups_allowed, 'groups_denied' => $groups_denied, 'state' => !empty($_POST['block_active']) ? 1 : 0, 'force_view' => !empty($_POST['block_force']) ? 1 : 0, 'display' => $display, 'display_custom' => $custom, 'style' => sportal_parse_style('implode'));
        if ($context['SPortal']['is_new']) {
            unset($blockInfo['id']);
            $smcFunc['db_insert']('', '{db_prefix}sp_blocks', array('label' => 'string', 'type' => 'string', 'col' => 'int', 'row' => 'int', 'permission_set' => 'int', 'groups_allowed' => 'string', 'groups_denied' => 'string', 'state' => 'int', 'force_view' => 'int', 'display' => 'string', 'display_custom' => 'string', 'style' => 'string'), $blockInfo, array('id_block'));
            $blockInfo['id'] = $smcFunc['db_insert_id']('{db_prefix}sp_blocks', 'id_block');
        } else {
            $block_fields = array("label = {string:label}", "permission_set = {int:permission_set}", "groups_allowed = {string:groups_allowed}", "groups_denied = {string:groups_denied}", "state = {int:state}", "force_view = {int:force_view}", "display = {string:display}", "display_custom = {string:display_custom}", "style = {string:style}");
            if (!empty($blockInfo['row'])) {
                $block_fields[] = "row = {int:row}";
            } else {
                unset($blockInfo['row']);
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}sp_blocks
				SET ' . implode(', ', $block_fields) . '
				WHERE id_block = {int:id}', $blockInfo);
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}sp_parameters
				WHERE id_block = {int:id}', array('id' => $blockInfo['id']));
        }
        if (!empty($_POST['parameters'])) {
            $parameters = array();
            foreach ($_POST['parameters'] as $variable => $value) {
                $parameters[] = array('id_block' => $blockInfo['id'], 'variable' => $variable, 'value' => $value);
            }
            $smcFunc['db_insert']('', '{db_prefix}sp_parameters', array('id_block' => 'int', 'variable' => 'string', 'value' => 'string'), $parameters, array());
        }
        redirectexit('action=admin;area=portalblocks');
    }
}
Beispiel #11
0
function TPmodules()
{
    global $settings, $context, $scripturl, $txt, $user_info, $sourcedir, $boarddir, $smcFunc;
    $ID_MEMBER = $context['user']['id'];
    if (loadLanguage('TPmodules') == false) {
        loadLanguage('TPmodules', 'english');
    }
    if (loadLanguage('TPortalAdmin') == false) {
        loadLanguage('TPortalAdmin', 'english');
    }
    // get subaction
    $tpsub = '';
    if (isset($_GET['sa'])) {
        $context['TPortal']['subaction'] = $_GET['sa'];
        $tpsub = $_GET['sa'];
    } elseif (isset($_GET['sub'])) {
        $context['TPortal']['subaction'] = $_GET['sub'];
        $tpsub = $_GET['sub'];
    }
    // for help pages
    if (isset($_GET['p'])) {
        $helpOptions = array('introduction', 'articles', 'frontpage', 'panels', 'blocks', 'modules', 'plugins');
        if (in_array($_GET['p'], $helpOptions)) {
            $context['TPortal']['helpsection'] = $_GET['p'];
        } else {
            $context['TPortal']['helpsection'] = 'introduction';
        }
    } else {
        $context['TPortal']['helpsection'] = 'introduction';
    }
    // a switch to make it clear what is "forum" and not
    $context['TPortal']['not_forum'] = true;
    // call the editor setup
    TPwysiwyg_setup();
    require_once $sourcedir . '/TPcommon.php';
    // download manager?
    if (isset($_GET['dl'])) {
        $context['TPortal']['dlsub'] = $_GET['dl'] == '' ? '0' : $_GET['dl'];
    }
    // fetch all extensions and compare
    $result = $smcFunc['db_query']('', '
        SELECT modulename, autoload_run, subquery 
        FROM {db_prefix}tp_modules WHERE active = {int:active}', array('active' => 1));
    if ($smcFunc['db_num_rows']($result) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($result)) {
            if (isset($_GET[$row['subquery']])) {
                $tpmodule = $boarddir . '/tp-files/tp-modules/' . $row['modulename'] . '/Sources/' . $row['autoload_run'];
            }
        }
        $smcFunc['db_free_result']($result);
    }
    // clear the linktree first
    TPstrip_linktree();
    // include source files in case of modules
    if (isset($context['TPortal']['dlsub'])) {
        require_once $sourcedir . '/TPdlmanager.php';
        TPdlmanager_init();
    } elseif (!empty($tpmodule)) {
        require_once $tpmodule;
    } elseif (isset($_GET['getsnippets'])) {
        get_snippets_xml();
    } elseif (isset($_GET['upshrink']) && isset($_GET['state'])) {
        $blockid = $_GET['upshrink'];
        $state = $_GET['state'];
        if (isset($_COOKIE['tp-upshrinks'])) {
            $shrinks = explode(',', $_COOKIE['tp-upshrinks']);
            if ($state == 0 && !in_array($blockid, $shrinks)) {
                $shrinks[] = $blockid;
            } elseif ($state == 1 && in_array($blockid, $shrinks)) {
                $spos = array_search($blockid, $shrinks);
                if ($spos > -1) {
                    unset($shrinks[$spos]);
                }
            }
            $newshrink = implode(',', $shrinks);
            setcookie('tp-upshrinks', $newshrink, time() + 7776000);
        } else {
            if ($state == 0) {
                setcookie('tp-upshrinks', $blockid, time() + 7776000);
            }
        }
        // Don't output anything...
        $tid = time();
        redirectexit($settings['images_url'] . '/blank.gif?ti=' . $tid);
    } elseif ($tpsub == 'comment' && isset($_POST['tp_article_type']) && $_POST['tp_article_type'] == 'article_comment') {
        // check the session
        checkSession('post');
        if (!allowedTo('tp_artcomment')) {
            fatal_error($txt['tp-nocomments']);
        }
        $commenter = $context['user']['id'];
        $article = $_POST['tp_article_id'];
        // check if the article indeed exists
        $request = $smcFunc['db_query']('', '
            SELECT comments FROM {db_prefix}tp_articles 
            WHERE id = {int:artid}', array('artid' => $article));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_row']($request);
            $num_comments = $row[0] + 1;
            $smcFunc['db_free_result']($request);
            $title = strip_tags($_POST['tp_article_comment_title']);
            $comment = substr($smcFunc['htmlspecialchars']($_POST['tp_article_bodytext']), 0, 65536);
            require_once $sourcedir . '/Subs-Post.php';
            preparsecode($comment);
            $time = time();
            // insert the comment
            $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int'), array($title, $comment, $ID_MEMBER, 'article_comment', $time, $article), array('id'));
            // count and increase the number of comments
            $smcFunc['db_query']('', '
                UPDATE {db_prefix}tp_articles 
                SET comments = {int:com} 
                WHERE id = {int:artid}', array('com' => $num_comments, 'artid' => $article));
            // go back to the article
            redirectexit('page=' . $article . '#tp-comment');
        }
    } elseif ($tpsub == 'updatelog') {
        $context['TPortal']['subaction'] = 'updatelog';
        $request = $smcFunc['db_query']('', '
            SELECT value1 FROM {db_prefix}tp_variables 
            WHERE type = {string:type} ORDER BY id DESC', array('type' => 'updatelog'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $check = $smcFunc['db_fetch_assoc']($request);
            $context['TPortal']['updatelog'] = $check['value1'];
            $smcFunc['db_free_result']($request);
        } else {
            $context['TPortal']['updatelog'] = "";
        }
        loadtemplate('TPmodules');
        $context['sub_template'] = 'updatelog';
    } elseif ($tpsub == 'showcomments') {
        if (!empty($_GET['tpstart']) && is_numeric($_GET['tpstart'])) {
            $tpstart = $_GET['tpstart'];
        } else {
            $tpstart = 0;
        }
        $mylast = 0;
        $mylast = $user_info['last_login'];
        $showall = false;
        if (isset($_GET['showall'])) {
            $showall = true;
        }
        $request = $smcFunc['db_query']('', '
        	SELECT COUNT(var.value1)
        	FROM ({db_prefix}tp_variables as var, {db_prefix}tp_articles as art)
			WHERE var.type = {string:type}
			' . (!$showall || $mylast == 0 ? 'AND var.value4 > ' . $mylast : '') . '
			AND art.id = var.value5', array('type' => 'article_comment'));
        $check = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
        $request = $smcFunc['db_query']('', '
			SELECT art.subject, memb.real_name as author, art.author_id as authorID, var.value1, var.value3, 
			var.value5, var.value4, mem.real_name as realName,
			' . ($user_info['is_guest'] ? '1' : '(IFNULL(log.item, 0) >= var.value4)') . ' AS isRead
			FROM ({db_prefix}tp_variables as var, {db_prefix}tp_articles as art)
			LEFT JOIN {db_prefix}members as memb ON (art.author_id = memb.id_member)
			LEFT JOIN {db_prefix}members as mem ON (var.value3 = mem.id_member)
			LEFT JOIN {db_prefix}tp_data as log ON (log.value = art.id AND log.type = 1 AND log.id_member = ' . $context['user']['id'] . ')
			WHERE var.type = {string:type}
			AND art.id = var.value5
			' . (!$showall || $mylast == 0 ? 'AND var.value4 > {int:last}' : '') . '
			ORDER BY var.value4 DESC LIMIT {int:start}, 15', array('type' => 'article_comment', 'last' => $mylast, 'start' => $tpstart));
        $context['TPortal']['artcomments']['new'] = array();
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['artcomments']['new'][] = array('page' => $row['value5'], 'subject' => $row['subject'], 'title' => $row['value1'], 'membername' => $row['realName'], 'time' => timeformat($row['value4']), 'author' => $row['author'], 'authorID' => $row['authorID'], 'member_id' => $row['value3'], 'is_read' => $row['isRead'], 'replies' => $check[0]);
            }
            $smcFunc['db_free_result']($request);
        }
        // construct the pages
        $context['TPortal']['pageindex'] = TPageIndex($scripturl . '?action=tpmod;sa=showcomments', $tpstart, $check[0], 15);
        $context['TPortal']['unreadcomments'] = true;
        $context['TPortal']['showall'] = $showall;
        $context['TPortal']['subaction'] = 'showcomments';
        TPadd_linktree($scripturl . '?action=tpmod;sa=showcomments' . ($showall ? ';showall' : ''), $txt['tp-showcomments']);
        loadtemplate('TPmodules');
    } elseif ($tpsub == 'savesettings') {
        // check the session
        checkSession('post');
        if (isset($_POST['item'])) {
            $item = $_POST['item'];
        } else {
            $item = 0;
        }
        if (isset($_POST['memberid'])) {
            $mem = $_POST['memberid'];
        } else {
            $mem = 0;
        }
        if (!isset($mem) || isset($mem) && !is_numeric($mem)) {
            fatalerror('Member doesn\'t exist.');
        }
        foreach ($_POST as $what => $value) {
            if ($what == 'tpwysiwyg' && $item > 0) {
                $smcFunc['db_query']('', '
				 UPDATE {db_prefix}tp_data 
				 SET value = {int:val} WHERE id = {int:id}', array('val' => $value, 'id' => $item));
            } elseif ($what == 'tpwysiwyg' && $item == 0) {
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_data', array('type' => 'int', 'id_member' => 'int', 'value' => 'int'), array(2, $mem, $value), array('id'));
            }
        }
        // go back to profile page
        redirectexit('action=profile;u=' . $mem . ';area=tparticles;sa=settings');
    } elseif ((substr($tpsub, 0, 11) == 'killcomment' || substr($tpsub, 0, 11) == 'editcomment') && $context['user']['is_logged']) {
        // check that you indeed can edit or delete
        $comment = substr($tpsub, 11);
        if (!is_numeric($comment)) {
            fatal_error($txt['tp-noadmincomments']);
        }
        $request = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_variables 
			WHERE id = {int:varid} LIMIT 1', array('varid' => $comment));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_assoc']($request);
            $smcFunc['db_free_result']($request);
            if (allowedTo('tp_articles') || $row['value3'] == $ID_MEMBER) {
                // deleting the comment
                if (substr($tpsub, 0, 11) == 'killcomment') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value5 = -value5 
						WHERE id = {int:varid}', array('varid' => $comment));
                    redirectexit('page=' . $row['value5']);
                } elseif (substr($tpsub, 0, 11) == 'editcomment') {
                    $context['TPortal']['comment_edit'] = array('id' => $row['id'], 'title' => $row['value1'], 'body' => $row['value2']);
                    $context['TPortal']['subaction'] = 'editcomment';
                    loadtemplate('TPmodules');
                }
            }
            fatal_error($txt['tp-notallowed']);
        }
    } elseif ($tpsub == 'rate_article' && isset($_POST['tp_article_rating_submit']) && $_POST['tp_article_type'] == 'article_rating') {
        // check the session
        checkSession('post');
        $commenter = $context['user']['id'];
        $article = $_POST['tp_article_id'];
        // check if the article indeed exists
        $request = $smcFunc['db_query']('', '
			SELECT rating, voters FROM {db_prefix}tp_articles 
			WHERE id = {int:artid}', array('artid' => $article));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
            $voters = array();
            $ratings = array();
            $voters = explode(',', $row[1]);
            $ratings = explode(',', $row[0]);
            // check if we haven't rated anyway
            if (!in_array($ID_MEMBER, $voters)) {
                if ($row[0] != '') {
                    $new_voters = $row[1] . ',' . $ID_MEMBER;
                    $new_ratings = $row[0] . ',' . $_POST['tp_article_rating'];
                } else {
                    $new_voters = $ID_MEMBER;
                    $new_ratings = $_POST['tp_article_rating'];
                }
                // update ratings and raters
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_articles 
					SET rating = {string:rate} WHERE id = {int:artid}', array('rate' => $new_ratings, 'artid' => $article));
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_articles 
					SET voters = {string:vote} 
					WHERE id = {int:artid}', array('vote' => $new_voters, 'artid' => $article));
            }
            // go back to the article
            redirectexit('page=' . $article);
        }
    } elseif ($tpsub == 'rate_dlitem' && isset($_POST['tp_dlitem_rating_submit']) && $_POST['tp_dlitem_type'] == 'dlitem_rating') {
        // check the session
        checkSession('post');
        $commenter = $context['user']['id'];
        $dl = $_POST['tp_dlitem_id'];
        // check if the download indeed exists
        $request = $smcFunc['db_query']('', '
			SELECT rating, voters FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:dlid}', array('dlid' => $dl));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
            $voters = array();
            $ratings = array();
            $voters = explode(',', $row[1]);
            $ratings = explode(',', $row[0]);
            // check if we haven't rated anyway
            if (!in_array($ID_MEMBER, $voters)) {
                if ($row[0] != '') {
                    $new_voters = $row[1] . ',' . $ID_MEMBER;
                    $new_ratings = $row[0] . ',' . $_POST['tp_dlitem_rating'];
                } else {
                    $new_voters = $ID_MEMBER;
                    $new_ratings = $_POST['tp_dlitem_rating'];
                }
                // update ratings and raters
                $smcFunc['db_query']('', '
				 	UPDATE {db_prefix}tp_dlmanager 
					SET rating = {string:rate} 
					WHERE id = {int:dlid}', array('rate' => $new_ratings, 'dlid' => $dl));
                $smcFunc['db_query']('', '
				 	UPDATE {db_prefix}tp_dlmanager 
				 	SET voters = {string:vote}
				 	WHERE id = {int:dlid}', array('vote' => $new_voters, 'dlid' => $dl));
            }
            // go back to the download
            redirectexit('action=tpmod;dl=item' . $dl);
        }
    } elseif ($tpsub == 'help') {
        $context['current_action'] = 'help';
        require_once $sourcedir . '/TPhelp.php';
        TPhelp_init();
    } elseif ($tpsub == 'searcharticle') {
        TPadd_linktree($scripturl . '?action=tpmod;sa=searcharticle', $txt['tp-searcharticles2']);
        loadtemplate('TPmodules');
    } elseif ($tpsub == 'tpattach') {
        tpattach();
    } elseif ($tpsub == 'searcharticle2') {
        $start = 0;
        checkSession('post');
        // any parameters then?
        // nothing to search for?
        if (empty($_POST['tpsearch_what'])) {
            fatal_error($txt['tp-nosearchentered']);
        }
        // clean the search
        $what = strip_tags($_POST['tpsearch_what']);
        if (!empty($_POST['tpsearch_title'])) {
            $usetitle = true;
        } else {
            $usetitle = false;
        }
        if (!empty($_POST['tpsearch_body'])) {
            $usebody = true;
        } else {
            $usebody = false;
        }
        if ($usetitle && !$usebody) {
            $query = 'a.subject LIKE \'%' . $what . '%\'';
        } elseif (!$usetitle && $usebody) {
            $query = 'a.body LIKE \'%' . $what . '%\'';
        } elseif ($usetitle && $usebody) {
            $query = 'a.subject LIKE \'%' . $what . '%\' OR a.body LIKE \'%' . $what . '%\'';
        } else {
            $query = 'a.subject LIKE \'%' . $what . '%\'';
        }
        $context['TPortal']['searchresults'] = array();
        $context['TPortal']['searchterm'] = $what;
        $now = forum_time();
        $request = $smcFunc['db_query']('', '
			SELECT a.id, a.date, a.views, a.subject, LEFT(a.body, 100) as body, a.author_id as authorID, a.type, m.real_name as realName
			FROM {db_prefix}tp_articles AS a
			LEFT JOIN {db_prefix}members as m ON a.author_id = m.id_member
			WHERE {raw:query}
			AND ((a.pub_start = 0 AND a.pub_end = 0) 
			OR (a.pub_start != 0 AND a.pub_start < ' . $now . ' AND a.pub_end = 0) 
			OR (a.pub_start = 0 AND a.pub_end != 0 AND a.pub_end > ' . $now . ') 
			OR (a.pub_start != 0 AND a.pub_end != 0 AND a.pub_end > ' . $now . ' AND a.pub_start < ' . $now . '))
			AND a.off = 0 
			ORDER BY a.date DESC LIMIT 20', array('query' => $query));
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                if ($row['type'] == 'bbc') {
                    $row['body'] = parse_bbc($row['body']);
                } elseif ($row['type'] == 'php') {
                    $row['body'] = '[PHP]';
                } else {
                    $row['body'] = strip_tags($row['body']);
                }
                $row['subject'] = preg_replace('/' . $what . '/', '<span class="highlight">' . $what . '</span>', $row['subject']);
                $row['body'] = preg_replace('/' . $what . '/', '<span class="highlight">' . $what . '</span>', $row['body']);
                $context['TPortal']['searchresults'][] = array('id' => $row['id'], 'date' => $row['date'], 'views' => $row['views'], 'subject' => $row['subject'], 'body' => $row['body'], 'author' => '<a href="' . $scripturl . '?action=profile;u=' . $row['authorID'] . '">' . $row['realName'] . '</a>');
            }
            $smcFunc['db_free_result']($request);
        }
        TPadd_linktree($scripturl . '?action=tpmod;sa=searcharticle', $txt['tp-searcharticles2']);
        loadtemplate('TPmodules');
    } elseif (substr($tpsub, 0, 11) == 'editarticle') {
        $what = substr($tpsub, 11);
        if (!is_numeric($what)) {
            fatal_error($txt['tp-notanarticle']);
        }
        // get one article
        $context['TPortal']['subaction'] = 'editarticle';
        $context['TPortal']['editarticle'] = array();
        $request = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_articles 
			WHERE id = {int:artid} LIMIT 1', array('artid' => $what));
        if ($smcFunc['db_num_rows']($request)) {
            $row = $smcFunc['db_fetch_assoc']($request);
            // check permission
            if (!allowedTo('tp_articles') && $ID_MEMBER != $row['author_id']) {
                fatal_error($txt['tp-articlenotallowed']);
            }
            // can you edit your own then..?
            isAllowedTo('tp_editownarticle');
            if ($row['locked'] == 1) {
                fatal_error($txt['tp-articlelocked']);
            }
            // Add in BBC editor before we call in template so the headers are there
            if ($row['type'] == 'bbc') {
                $context['TPortal']['editor_id'] = 'tp_article_body' . $row['id'];
                TP_prebbcbox($context['TPortal']['editor_id'], strip_tags($row['body']));
            }
            $context['TPortal']['editarticle'] = array('id' => $row['id'], 'date' => array('timestamp' => $row['date'], 'day' => date("j", $row['date']), 'month' => date("m", $row['date']), 'year' => date("Y", $row['date']), 'hour' => date("G", $row['date']), 'minute' => date("i", $row['date'])), 'body' => $row['body'], 'intro' => $row['intro'], 'useintro' => $row['useintro'], 'category' => $row['category'], 'frontpage' => $row['frontpage'], 'subject' => $row['subject'], 'authorID' => $row['author_id'], 'author' => $row['author'], 'frame' => !empty($row['frame']) ? $row['frame'] : 'theme', 'approved' => $row['approved'], 'off' => $row['off'], 'options' => $row['options'], 'ID_THEME' => $row['id_theme'], 'shortname' => $row['shortname'], 'sticky' => $row['sticky'], 'locked' => $row['locked'], 'fileimport' => $row['fileimport'], 'topic' => $row['topic'], 'illustration' => $row['illustration'], 'headers' => $row['headers'], 'articletype' => $row['type']);
            $smcFunc['db_free_result']($request);
        } else {
            fatal_error($txt['tp-notanarticlefound']);
        }
        if (loadLanguage('TPortalAdmin') == false) {
            loadLanguage('TPortalAdmin', 'english');
        }
        loadtemplate('TPmodules');
    } elseif ($tpsub == 'myarticles') {
        // not for guests
        if ($context['user']['is_guest']) {
            fatal_error($txt['tp-noarticlesfound']);
        }
        // get all articles
        $request = $smcFunc['db_query']('', '
			SELECT COUNT(*) FROM {db_prefix}tp_articles 
			WHERE author_id = {int:author}', array('author' => $context['user']['id']));
        $row = $smcFunc['db_fetch_row']($request);
        $allmy = $row[0];
        $mystart = !empty($_GET['p']) && is_numeric($_GET['p']) ? $_GET['p'] : 0;
        // sorting?
        $sort = $context['TPortal']['sort'] = !empty($_GET['sort']) && in_array($_GET['sort'], array('date', 'id', 'subject')) ? $_GET['sort'] : 'date';
        $context['TPortal']['pageindex'] = TPageIndex($scripturl . '?action=tpmod;sa=myarticles;sort=' . $sort, $mystart, $allmy, 15);
        $context['TPortal']['subaction'] = 'myarticles';
        $context['TPortal']['myarticles'] = array();
        $request2 = $smcFunc['db_query']('', '
			SELECT id, subject, date, locked, approved, off FROM {db_prefix}tp_articles 
			WHERE author_id = {int:author} 
			ORDER BY {string:sort} DESC LIMIT {int:start}, 15', array('author' => $context['user']['id'], 'sort' => $sort, 'start' => $mystart));
        if ($smcFunc['db_num_rows']($request2) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request2)) {
                $context['TPortal']['myarticles'][] = $row;
            }
            $smcFunc['db_free_result']($request2);
        }
        if (loadLanguage('TPortalAdmin') == false) {
            loadLanguage('TPortalAdmin', 'english');
        }
        loadtemplate('TPmodules');
    } elseif (in_array($tpsub, array('submitarticle', 'addarticle_html', 'addarticle_bbc'))) {
        global $sourcedir, $settings;
        require_once $sourcedir . '/TPcommon.php';
        // a BBC article?
        if (isset($_GET['bbc']) || $tpsub == 'addarticle_bbc') {
            isAllowedTo('tp_submitbbc');
            $context['TPortal']['submitbbc'] = 1;
            $context['html_headers'] .= '
				<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/editor.js?rc1"></script>';
            // Add in BBC editor before we call in template so the headers are there
            $context['TPortal']['editor_id'] = 'tp_article_body';
            TP_prebbcbox($context['TPortal']['editor_id']);
        } else {
            isAllowedTo('tp_submithtml');
        }
        $context['TPortal']['subaction'] = 'submitarticle';
        loadtemplate('TPmodules');
        $context['sub_template'] = 'submitarticle';
    } elseif ($tpsub == 'submitsuccess') {
        $context['TPortal']['subaction'] = 'submitsuccess';
        loadtemplate('TPmodules');
        $context['sub_template'] = 'submitsuccess';
    } elseif ($tpsub == 'dlsubmitsuccess') {
        $context['TPortal']['subaction'] = 'dlsubmitsuccess';
        loadtemplate('TPmodules');
        $context['sub_template'] = 'dlsubmitsuccess';
    } elseif ($tpsub == 'submitarticle2') {
        require_once $sourcedir . '/TPcommon.php';
        if (isset($_POST['tp_article_approved']) || allowedTo('tp_alwaysapproved')) {
            $artpp = '0';
        } else {
            $artpp = '1';
        }
        $arttype = isset($_POST['submittedarticle']) ? $_POST['submittedarticle'] : '';
        $arts = strip_tags($_POST['tp_article_title']);
        $artd = $_POST['tp_article_date'];
        $artimp = isset($_POST['tp_article_fileimport']) ? $_POST['tp_article_fileimport'] : '';
        $artbb = $_POST['tp_article_body'];
        $artu = isset($_POST['tp_article_useintro']) ? $_POST['tp_article_useintro'] : 0;
        $arti = isset($_POST['tp_article_intro']) ? $_POST['tp_article_intro'] : '';
        $artc = !empty($_POST['tp_article_category']) ? $_POST['tp_article_category'] : 0;
        $artf = $_POST['tp_article_frontpage'];
        $artframe = 'theme';
        $artoptions = 'date,title,author,linktree,top,cblock,rblock,lblock,tblock,lbblock,views,rating,ratingallow,avatar';
        $name = $user_info['name'];
        $nameb = $ID_MEMBER;
        if ($arts == '') {
            $arts = $txt['tp-no_title'];
        }
        // escape any php code
        if ($artu == -1 && !get_magic_quotes_gpc()) {
            $artbb = addslashes($artbb);
        }
        $request = $smcFunc['db_insert']('INSERT', '{db_prefix}tp_articles', array('date' => 'int', 'body' => 'string', 'intro' => 'string', 'useintro' => 'int', 'category' => 'int', 'frontpage' => 'int', 'subject' => 'string', 'author_id' => 'int', 'author' => 'string', 'frame' => 'string', 'approved' => 'int', 'off' => 'int', 'options' => 'string', 'parse' => 'int', 'comments' => 'int', 'comments_var' => 'string', 'views' => 'int', 'rating' => 'string', 'voters' => 'string', 'id_theme' => 'int', 'shortname' => 'string', 'fileimport' => 'string', 'type' => 'string'), array($artd, $artbb, $arti, $artu, $artc, $artf, $arts, $nameb, $name, $artframe, $artpp, '0', $artoptions, 0, 0, '', 0, '', '', 0, '', $artimp, $arttype), array('id'));
        $newitem = $smcFunc['db_insert_id']('{db_prefix}tp_articles', 'id');
        // put this into submissions - id and type
        $title = $arts;
        $now = $artd;
        if ($artpp == '0') {
            $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int'), array($title, $now, '', 'art_not_approved', '', $newitem), array('id'));
        }
        if (isset($_POST['pre_approved'])) {
            redirectexit('action=tpmod;sa=addsuccess');
        }
        if (allowedTo('tp_editownarticle') && !allowedTo('tp_articles')) {
            // did we get a picture as well?
            if (isset($_FILES['qup_tp_article_body']) && file_exists($_FILES['qup_tp_article_body']['tmp_name'])) {
                $name = TPuploadpicture('qup_tp_article_body', $context['user']['id'] . 'uid');
                tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
            }
            redirectexit('action=tpmod;sa=editarticle' . $newitem);
        } elseif (allowedTo('tp_articles')) {
            // did we get a picture as well?
            if (isset($_FILES['qup_tp_article_body']) && file_exists($_FILES['qup_tp_article_body']['tmp_name'])) {
                $name = TPuploadpicture('qup_tp_article_body', $context['user']['id'] . 'uid');
                tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
            }
            redirectexit('action=tpadmin;sa=editarticle' . $newitem);
        } else {
            redirectexit('action=tpmod;sa=submitsuccess');
        }
    } elseif (substr($tpsub, 0, 9) == 'editblock') {
        $what = substr($tpsub, 9);
        if (!is_numeric($what)) {
            fatal_error($txt['tp-notablock']);
        }
        // get one block
        $context['TPortal']['subaction'] = 'editblock';
        $context['TPortal']['blockedit'] = array();
        $request = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_blocks 
			WHERE id = {int:blockid} LIMIT 1', array('blockid' => $what));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_assoc']($request);
            $can_edit = !empty($row['editgroups']) ? get_perm($row['editgroups'], '') : false;
            // check permission
            if (allowedTo('tp_blocks') || $can_edit) {
                $ok = true;
            } else {
                fatal_error($txt['tp-blocknotallowed']);
            }
            $context['TPortal']['editblock'] = array();
            $context['TPortal']['blockedit']['id'] = $row['id'];
            $context['TPortal']['blockedit']['title'] = $row['title'];
            $context['TPortal']['blockedit']['body'] = $row['body'];
            $context['TPortal']['blockedit']['frame'] = $row['frame'];
            $context['TPortal']['blockedit']['type'] = $row['type'];
            $context['TPortal']['blockedit']['var1'] = $row['var1'];
            $context['TPortal']['blockedit']['var2'] = $row['var2'];
            $context['TPortal']['blockedit']['visible'] = $row['visible'];
            $context['TPortal']['blockedit']['editgroups'] = $row['editgroups'];
            $smcFunc['db_free_result']($request);
        } else {
            fatal_error($txt['tp-notablock']);
        }
        // Add in BBC editor before we call in template so the headers are there
        if ($context['TPortal']['blockedit']['type'] == '5') {
            $context['TPortal']['editor_id'] = 'blockbody' . $context['TPortal']['blockedit']['id'];
            TP_prebbcbox($context['TPortal']['editor_id'], strip_tags($context['TPortal']['blockedit']['body']));
        }
        if (loadLanguage('TPortalAdmin') == false) {
            loadLanguage('TPortalAdmin', 'english');
        }
        loadtemplate('TPmodules');
    } elseif ($tpsub == 'publish') {
        if (!isset($_GET['t'])) {
            redirectexit('action=forum');
        }
        $t = is_numeric($_GET['t']) ? $_GET['t'] : 0;
        if (empty($t)) {
            redirectexit('action=forum');
        }
        isAllowedTo('tp_settings');
        $existing = explode(',', $context['TPortal']['frontpage_topics']);
        if (in_array($t, $existing)) {
            unset($existing[array_search($t, $existing)]);
        } else {
            $existing[] = $t;
        }
        $newstring = implode(',', $existing);
        if (substr($newstring, 0, 1) == ',') {
            $newstring = substr($newstring, 1);
        }
        updateTPSettings(array('frontpage_topics' => $newstring));
        redirectexit('topic=' . $t . '.0');
    } elseif (substr($tpsub, 0, 9) == 'saveblock') {
        $whatID = substr($tpsub, 9);
        if (!is_numeric($whatID)) {
            fatal_error($txt['tp-notablock']);
        }
        $request = $smcFunc['db_query']('', '
			SELECT editgroups FROM {db_prefix}tp_blocks 
			WHERE id = {int:blockid} LIMIT 1', array('blockid' => $whatID));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_assoc']($request);
            // check permission
            if (allowedTo('tp_blocks') || get_perm($row['editgroups'])) {
                $ok = true;
            } else {
                fatal_error($txt['tp-blocknotallowed']);
            }
            $smcFunc['db_free_result']($request);
            // loop through the values and save them
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 10) == 'blocktitle') {
                    // make sure special charachters can't be done
                    $value = strip_tags($value);
                    $value = preg_replace('~&#\\d+$~', '', $value);
                    $val = substr($what, 10);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET title = {string:title} 
						WHERE id = {int:blockid}', array('title' => $value, 'blockid' => $val));
                } elseif (substr($what, 0, 9) == 'blockbody' && substr($what, -4) != 'mode') {
                    // If we came from WYSIWYG then turn it back into BBC regardless.
                    if (!empty($_REQUEST[$what . '_mode']) && isset($_REQUEST[$what])) {
                        require_once $sourcedir . '/Subs-Editor.php';
                        $_REQUEST[$what] = html_to_bbc($_REQUEST[$what]);
                        // We need to unhtml it now as it gets done shortly.
                        $_REQUEST[$what] = un_htmlspecialchars($_REQUEST[$what]);
                        // We need this for everything else.
                        $value = $_POST[$what] = $_REQUEST[$what];
                    }
                    $val = (int) substr($what, 9);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET body = {string:body} 
						WHERE id = {int:blockid}', array('body' => $value, 'blockid' => $val));
                } elseif (substr($what, 0, 10) == 'blockframe') {
                    $val = substr($what, 10);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET frame = {string:frame}
						WHERE id = {int:blockid}', array('frame' => $value, 'blockid' => $val));
                } elseif (substr($what, 0, 12) == 'blockvisible') {
                    $val = substr($what, 12);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET visible = {string:vis}
						WHERE id = {int:blockid}', array('vis' => $value, 'blockid' => $val));
                } elseif (substr($what, 0, 9) == 'blockvar1') {
                    $val = substr($what, 9);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET var1 = {string:var1}
						WHERE id = {int:blockid}', array('var1' => $value, 'blockid' => $val));
                } elseif (substr($what, 0, 9) == 'blockvar2') {
                    $val = substr($what, 9);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET var2 = {string:var2}
						WHERE id = {int:blockid}', array('var2' => $value, 'blockid' => $val));
                }
            }
            redirectexit('action=tpmod;sa=editblock' . $whatID);
        } else {
            fatal_error($txt['tp-notablock']);
        }
    } elseif ($tpsub == 'savearticle') {
        if (isset($_REQUEST['send'])) {
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 16) == 'tp_article_title') {
                    $val = substr($what, 16);
                    if (is_numeric($val) && $val > 0) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET subject = {string:subject}
							WHERE id = {int:artid}', array('subject' => $value, 'artid' => $val));
                    }
                } elseif (substr($what, 0, 15) == 'tp_article_body' && substr($what, -4) != 'mode') {
                    // If we came from WYSIWYG then turn it back into BBC regardless.
                    if (!empty($_REQUEST[$what . '_mode']) && isset($_REQUEST[$what])) {
                        require_once $sourcedir . '/Subs-Editor.php';
                        $_REQUEST[$what] = html_to_bbc($_REQUEST[$what]);
                        // We need to unhtml it now as it gets done shortly.
                        $_REQUEST[$what] = un_htmlspecialchars($_REQUEST[$what]);
                        // We need this for everything else.
                        $value = $_POST[$what] = $_REQUEST[$what];
                    }
                    $val = substr($what, 15);
                    if (is_numeric($val) && $val > 0) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET body = {string:body}
							WHERE id = {int:artid}', array('body' => $value, 'artid' => $val));
                    }
                } elseif (substr($what, 0, 19) == 'tp_article_useintro') {
                    $val = substr($what, 19);
                    if (is_numeric($val) && $val > 0) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET useintro = {string:useintro}
							WHERE id = {int:artid}', array('useintro' => $value, 'artid' => $val));
                    }
                } elseif (substr($what, 0, 16) == 'tp_article_intro') {
                    $val = (int) substr($what, 16);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_articles 
						SET intro = {string:intro}
						WHERE id = {int:artid}', array('intro' => $value, 'artid' => $val));
                } elseif ($what == 'tp_wysiwyg') {
                    $result = $smcFunc['db_query']('', '
						SELECT id FROM {db_prefix}tp_data 
						WHERE type = {int:type} 
						AND id_member = {int:id_mem}', array('type' => 2, 'id_mem' => $ID_MEMBER));
                    if ($smcFunc['db_num_rows']($result) > 0) {
                        $row = $smcFunc['db_fetch_assoc']($result);
                        $wysid = $row['id'];
                        $smcFunc['db_free_result']($result);
                    }
                    if (isset($wysid)) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_data 
							SET value = {int:val} 
							WHERE id = {int:dataid}', array('val' => $value, 'dataid' => $wysid));
                    } else {
                        $smcFunc['db_query']('INSERT', '{db_prefix}tp_data}', array('type' => 'int', 'id_member' => 'int', 'value' => 'int', 'item' => 'int'), array(2, $ID_MEMBER, $value, 0), array('id'));
                    }
                }
            }
            if (allowedTo('tp_editownarticle') && !allowedTo('tp_articles')) {
                // did we get a picture as well?
                if (isset($_FILES['qup_tp_article_body']) && file_exists($_FILES['qup_tp_article_body']['tmp_name'])) {
                    $name = TPuploadpicture('qup_tp_article_body', $context['user']['id'] . 'uid');
                    tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
                }
                redirectexit('action=tpmod;sa=editarticle' . $val);
            } elseif (allowedTo('tp_articles')) {
                // did we get a picture as well?
                if (isset($_FILES['qup_tp_article_body']) && file_exists($_FILES['qup_tp_article_body']['tmp_name'])) {
                    $name = TPuploadpicture('qup_tp_article_body', $context['user']['id'] . 'uid');
                    tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
                }
                redirectexit('action=tpadmin;sa=editarticle' . $val);
            } else {
                fatal_error($txt['tp-notallowed']);
            }
        }
    } elseif ($tpsub == 'credits') {
        require_once $sourcedir . '/TPhelp.php';
        TPCredits();
    } else {
        redirectexit('action=forum');
    }
}
Beispiel #12
0
function EditTopic2()
{
    global $smcFunc, $txt, $sourcedir;
    $id = (int) $_REQUEST['id'];
    // If we came from WYSIWYG then turn it back into BBC regardless.
    if (!empty($_REQUEST['topicbody_mode']) && isset($_REQUEST['topicbody'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_REQUEST['topicbody'] = html_to_bbc($_REQUEST['topicbody']);
        // We need to unhtml it now as it gets done shortly.
        $_REQUEST['topicbody'] = un_htmlspecialchars($_REQUEST['topicbody']);
    }
    $topicsubject = $smcFunc['htmlspecialchars']($_REQUEST['topicsubject'], ENT_QUOTES);
    $topicbody = $smcFunc['htmlspecialchars']($_REQUEST['topicbody'], ENT_QUOTES);
    if ($topicsubject == '') {
        fatal_error($txt['welcome_err_nosubject'], false);
    }
    if ($topicbody == '') {
        fatal_error($txt['welcome_err_nobody'], false);
    }
    // Update the Topic
    $smcFunc['db_query']('', "UPDATE {db_prefix}welcome \n\t\tSET welcomesubject = {string:topicsubject}, welcomebody = {string:topicbody} \n\t\tWHERE ID = {$id} LIMIT 1", array('topicsubject' => $topicsubject, 'topicbody' => $topicbody));
    // Redirect to the main settings
    redirectexit('action=admin;area=welcome;sa=admin');
}
/**
* 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);
        }
    }
}
Beispiel #14
0
function KB_wysig_descript()
{
    global $sourcedir;
    require_once $sourcedir . '/Subs-Editor.php';
    if (!empty($_REQUEST['description_mode']) && isset($_REQUEST['description'])) {
        $_REQUEST['description'] = html_to_bbc($_REQUEST['description']);
        $_REQUEST['description'] = un_htmlspecialchars($_REQUEST['description']);
        $_POST['description'] = $_REQUEST['description'];
    }
}
function do_postchecks()
{
    global $context, $txt, $settings, $boarddir, $smcFunc, $sourcedir;
    // If we have any setting changes add them to this array
    $updateArray = array();
    // which screen do we come frm?
    if (!empty($_POST['tpadmin_form'])) {
        // get it
        $from = $_POST['tpadmin_form'];
        //news
        if ($from == 'news') {
            return 'news';
        } elseif ($from == 'blockoverview') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $block = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 5, 7) == 'tpblock') {
                    // get the id
                    $bid = substr($what, 12);
                    if (!isset($block[$bid])) {
                        $block[$bid] = array();
                    }
                    if ($value != 'control' && !in_array($value, $block[$bid])) {
                        $block[$bid][] = $value;
                    }
                }
            }
            foreach ($block as $bl => $blo) {
                $request = $smcFunc['db_query']('', '
					SELECT access FROM {db_prefix}tp_blocks 
					WHERE id = {int:blockid}', array('blockid' => $bl));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $smcFunc['db_free_result']($request);
                    $request = $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET access = {string:access} WHERE id = {int:blockid}', array('access' => implode(',', $blo), 'blockid' => $bl));
                }
            }
            return 'blocks;overview';
        } elseif (in_array($from, array('settings', 'frontpage', 'artsettings', 'panels'))) {
            checkSession('post');
            isAllowedTo('tp_settings');
            $w = array();
            $ssi = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 3) == 'tp_') {
                    $where = substr($what, 3);
                    $clean = $value;
                    // for frontpage, do some extra
                    if ($from == 'frontpage') {
                        if (substr($what, 0, 20) == 'tp_frontpage_visual_') {
                            $w[] = substr($what, 20);
                            unset($clean);
                        } elseif (substr($what, 0, 21) == 'tp_frontpage_usorting') {
                            $w[] = 'sort_' . $value;
                            unset($clean);
                        } elseif (substr($what, 0, 26) == 'tp_frontpage_sorting_order') {
                            $w[] = 'sortorder_' . $value;
                            unset($clean);
                        } elseif (substr($what, 0, 11) == 'tp_ssiboard') {
                            if ($value != 0) {
                                $ssi[$value] = $value;
                            }
                        }
                    }
                    if ($from == 'settings' && $what == 'tp_frontpage_title') {
                        $updateArray['frontpage_title'] = $clean;
                    } else {
                        if (isset($clean)) {
                            $updateArray[$where] = $clean;
                        }
                    }
                }
            }
            // check the frontpage visual setting..
            if ($from == 'frontpage') {
                $updateArray['frontpage_visual'] = implode(',', $w);
                $updateArray['SSI_board'] = implode(',', $ssi);
            }
            updateTPSettings($updateArray);
            return $from;
        } elseif ($from == 'categories') {
            checkSession('post');
            isAllowedTo('tp_articles');
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 3) == 'tp_') {
                    // for frontpage, do some extra
                    if ($from == 'categories') {
                        if (substr($what, 0, 19) == 'tp_category_value2_') {
                            $where = tp_sanitize(substr($what, 19));
                            //make sure parent are not its own parent
                            $request = $smcFunc['db_query']('', '
								SELECT value2 FROM {db_prefix}tp_variables 
								WHERE id = {string:varid} LIMIT 1', array('varid' => $value));
                            $row = $smcFunc['db_fetch_assoc']($request);
                            $smcFunc['db_free_result']($request);
                            if ($row['value2'] == $where) {
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_variables 
									SET value2 = {string:val2}
									WHERE id = {string:varid} LIMIT 1', array('val2' => '0', 'varid' => $value));
                            }
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}tp_variables 
								SET value2 = {string:val2}
								WHERE id = {string:varid} LIMIT 1', array('val2' => $value, 'varid' => $where));
                        }
                    }
                }
            }
            return $from;
        } elseif ($from == 'articles') {
            checkSession('post');
            isAllowedTo('tp_articles');
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 14) == 'tp_article_pos') {
                    $where = tp_sanitize(substr($what, 14));
                    $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET parse = {int:parse} 
							WHERE id = {int:artid} LIMIT 1', array('parse' => $value, 'artid' => $where));
                }
            }
            if (isset($_POST['tpadmin_form_category']) && is_numeric($_POST['tpadmin_form_category'])) {
                return $from . ';cu=' . $_POST['tpadmin_form_category'];
            } else {
                return $from;
            }
        } elseif ($from == 'modules') {
            checkSession('post');
            isAllowedTo('tp_settings');
            foreach ($_POST as $what => $value) {
                if ($what == 'tp_show_download') {
                    $updateArray['show_download'] = $value;
                } elseif (substr($what, 0, 14) == 'tpmodule_state') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_modules 
						SET active = {int:active} 
						WHERE id = {int:modid}', array('active' => $value, 'modid' => substr($what, 14)));
                }
            }
            updateTPSettings($updateArray);
            return $from;
        } elseif ($from == 'menuitems') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $all = explode(',', $context['TPortal']['sitemap_items']);
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 8) == 'menu_pos') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET subtype = {string:subtype} 
						WHERE id = {int:varid}', array('subtype' => tp_sanitize($value), 'varid' => substr($what, 8)));
                } elseif (substr($what, 0, 8) == 'menu_sub') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value4 = {string:val4} 
						WHERE id = {int:varid}', array('val4' => tp_sanitize($value), 'varid' => substr($what, 8)));
                } elseif (substr($what, 0, 15) == 'tp_menu_sitemap') {
                    $new = substr($what, 15);
                    if ($value == 0 && in_array($new, $all)) {
                        foreach ($all as $key => $value) {
                            if ($all[$key] == $new) {
                                unset($all[$key]);
                            }
                        }
                    } elseif ($value == 1 && !in_array($new, $all)) {
                        $all[] = $new;
                    }
                    $updateArray['sitemap_items'] = implode(',', $all);
                }
            }
            updateTPSettings($updateArray);
            redirectexit('action=tpadmin;sa=menubox;mid=' . $_POST['tp_menuid']);
        } elseif ($from == 'menus') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 12) == 'tp_menu_name') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value1 = {string:val1} 
						WHERE id = {int:varid}', array('val1' => tp_sanitize($value), 'varid' => substr($what, 12)));
                }
            }
            redirectexit('action=tpadmin;sa=menubox');
        } elseif ($from == 'singlemenuedit') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $where = isset($_POST['tpadmin_form_id']) ? $_POST['tpadmin_form_id'] : 0;
            foreach ($_POST as $what => $value) {
                if ($what == 'tp_menu_name') {
                    // make sure special charachters can't be done
                    $value = preg_replace('~&#\\d+$~', '', $value);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value1 = {string:val1} 
						WHERE id = {int:varid}', array('val1' => $value, 'varid' => $where));
                } elseif ($what == 'tp_menu_newlink') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value2 = {string:var2} 
						WHERE id = {int:varid}', array('var2' => $value, 'varid' => $where));
                } elseif ($what == 'tp_menu_menuid') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET subtype2 = {int:subtype2} 
						WHERE id = {int:varid}', array('subtype2' => $value, 'varid' => $where));
                } elseif ($what == 'tp_menu_type') {
                    if ($value == 'cats') {
                        $idtype = 'cats' . $_POST['tp_menu_category'];
                    } elseif ($value == 'arti') {
                        $idtype = 'arti' . $_POST['tp_menu_article'];
                    } elseif ($value == 'link') {
                        $idtype = $_POST['tp_menu_link'];
                    } elseif ($value == 'head') {
                        $idtype = 'head';
                    } elseif ($value == 'spac') {
                        $idtype = 'spac';
                    }
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value3 = {string:val3} 
						WHERE id = {int:varid}', array('val3' => $idtype, 'varid' => $where));
                } elseif ($what == 'tp_menu_sub') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables
						SET value4 = {string:val4}
						WHERE id = {int:varid}', array('val4' => $value, 'varid' => $where));
                } elseif (substr($what, 0, 15) == 'tp_menu_newlink') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value2 =  
						WHERE id = {int:varid}', array('val2' => $value, 'varid' => $where));
                }
            }
            redirectexit('action=tpadmin;linkedit=' . $where . ';' . $context['session_var'] . '=' . $context['session_id']);
        } elseif ($from == 'addcategory') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $name = !empty($_POST['tp_cat_name']) ? $_POST['tp_cat_name'] : $txt['tp-noname'];
            $parent = !empty($_POST['tp_cat_parent']) ? $_POST['tp_cat_parent'] : '0';
            $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype' => 'string', 'value7' => 'string', 'value8' => 'string', 'subtype2' => 'int'), array(strip_tags($name), $parent, '', 'category', '', 0, '', 'catlayout=1|layout=1', 0, 0), array('id'));
            $go = $smcFunc['db_insert_id']('{db_prefix}tp_variables', 'id');
            redirectexit('action=tpadmin;sa=categories;cu=' . $go);
        } elseif ($from == 'clist') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $cats = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 8) == 'tp_clist') {
                    $cats[] = $value;
                }
            }
            if (sizeof($cats) > 0) {
                $catnames = implode(',', $cats);
            } else {
                $catnames = '';
            }
            $updateArray['cat_list'] = $catnames;
            updateTPSettings($updateArray);
            return $from;
        } elseif ($from == 'editcategory') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $options = array();
            $groups = array();
            $where = $_POST['tpadmin_form_id'];
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 3) == 'tp_') {
                    $clean = tp_sanitize($value);
                    $param = substr($what, 12);
                    if (in_array($param, array('value5', 'value6', 'value8'))) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET ' . $param . ' = {string:val} 
							WHERE id = {int:varid} LIMIT 1', array('val' => $value, 'varid' => $where));
                    } elseif ($param == 'value2') {
                        //make sure parent are not its own parent
                        $request = $smcFunc['db_query']('', '
							SELECT value2 FROM {db_prefix}tp_variables 
							WHERE id = {int:varid} LIMIT 1', array('varid' => $value));
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $smcFunc['db_free_result']($request);
                        if ($row['value2'] == $where) {
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}tp_variables 
								SET value2 = {string:val2} 
								WHERE id = {int:varid} LIMIT 1', array('val2' => '0', 'varid' => $value));
                        }
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET value2 = {string:val2} 
							WHERE id = {int:varid} LIMIT 1', array('val2' => $value, 'varid' => $where));
                    } elseif ($param == 'value1') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET value1 = {string:val1} 
							WHERE id = {int:varid} LIMIT 1', array('val1' => strip_tags($value), 'varid' => $where));
                    } elseif ($param == 'value4') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET value4 = {string:val4} 
							WHERE id = {int:varid} LIMIT 1', array('val4' => $value, 'varid' => $where));
                    } elseif ($param == 'value9') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET value9 = {string:val9} 
							WHERE id = {int:varid} LIMIT 1', array('val9' => $value, 'varid' => $where));
                    } elseif (substr($param, 0, 6) == 'group_') {
                        $groups[] = substr($param, 6);
                    } else {
                        $options[] = $param . '=' . $value;
                    }
                }
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_variables 
				SET value3 = {string:val3}, value7 = {string:val7} 
				WHERE id = {int:varid} LIMIT 1', array('val3' => implode(',', $groups), 'val7' => implode('|', $options), 'varid' => $where));
            $from = 'categories;cu=' . $where;
            return $from;
        } elseif ($from == 'strays') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $ccats = array();
            // check if we have some values
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 16) == 'tp_article_stray') {
                    $ccats[] = substr($what, 16);
                } elseif ($what == 'tp_article_cat') {
                    $straycat = $value;
                } elseif ($what == 'tp_article_new') {
                    $straynewcat = $value;
                }
            }
            // update
            if (isset($straycat) && sizeof($ccats) > 0) {
                $category = $straycat;
                if ($category == 0 && !empty($straynewcat)) {
                    $request = $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'type' => 'string'), array(strip_tags($straynewcat), '0', 'category'), array('id'));
                    $newcategory = $smcFunc['db_insert_id']('{db_prefix}tp_variables', 'id');
                    $smcFunc['db_free_result']($request);
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_articles 
					SET category = {int:cat} 
					WHERE id IN ({array_int:artid})', array('cat' => !empty($newcategory) ? $newcategory : $category, 'artid' => $ccats));
            }
            return $from;
        } elseif ($from == 'articons') {
            checkSession('post');
            isAllowedTo('tp_articles');
            // any icons sent?
            if (file_exists($_FILES['tp_article_newicon']['tmp_name'])) {
                TPuploadpicture('tp_article_newicon', '', '300', 'jpg,gif,png', 'tp-files/tp-articles/icons');
            }
            if (file_exists($_FILES['tp_article_newillustration']['tmp_name'])) {
                $name = TPuploadpicture('tp_article_newillustration', '', '500', 'jpg,gif,png', 'tp-files/tp-articles/illustrations');
                tp_createthumb('tp-files/tp-articles/illustrations/' . $name, 128, 128, 'tp-files/tp-articles/illustrations/s_' . $name);
                unlink('tp-files/tp-articles/illustrations/' . $name);
            }
            // how about deleted?
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 7) == 'articon') {
                    unlink($boarddir . '/tp-files/tp-articles/icons/' . $value);
                } elseif (substr($what, 0, 15) == 'artillustration') {
                    unlink($boarddir . '/tp-files/tp-articles/illustrations/' . $value);
                }
            }
            return $from;
        } elseif ($from == 'menuadd') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            if (!empty($_POST['tp_menu_title'])) {
                $mtitle = strip_tags($_POST['tp_menu_title']);
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'type' => 'string'), array($mtitle, 'menus'), array('id'));
                redirectexit('action=tpadmin;sa=menubox');
            }
        } elseif ($from == 'menuaddsingle') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $mid = $_POST['tp_menu_menuid'];
            $mtitle = strip_tags($_POST['tp_menu_title']);
            if ($mtitle == '') {
                $mtitle = $txt['tp-no_title'];
            }
            $mtype = $_POST['tp_menu_type'];
            $mcat = isset($_POST['tp_menu_category']) ? $_POST['tp_menu_category'] : '';
            $mart = isset($_POST['tp_menu_article']) ? $_POST['tp_menu_article'] : '';
            $mlink = isset($_POST['tp_menu_link']) ? $_POST['tp_menu_link'] : '';
            $mhead = isset($_POST['tp_menu_head']) ? $_POST['tp_menu_head'] : '';
            $mnewlink = isset($_POST['tp_menu_newlink']) ? $_POST['tp_menu_newlink'] : '0';
            if ($mtype == 'cats') {
                $mtype = 'cats' . $mcat;
            } elseif ($mtype == 'arti') {
                $mtype = 'arti' . $mart;
            } elseif ($mtype == 'head') {
                $mtype = 'head' . $mhead;
            } elseif ($mtype == 'spac') {
                $mtype = 'spac';
            } else {
                $mtype = $mlink;
            }
            $msub = $_POST['tp_menu_sub'];
            $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype2' => 'int'), array($mtitle, $mnewlink, $mtype, 'menubox', $msub, -1, $mid), array('id'));
            redirectexit('action=tpadmin;sa=menubox;mid=' . $mid);
        } elseif ($from == 'submission') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $ccats = array();
            // check if we have some values
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 21) == 'tp_article_submission') {
                    $ccats[] = substr($what, 21);
                } elseif ($what == 'tp_article_cat') {
                    $straycat = $value;
                } elseif ($what == 'tp_article_new') {
                    $straynewcat = $value;
                }
            }
            // update
            if (isset($straycat) && sizeof($ccats) > 0) {
                $category = $straycat;
                if ($category == 0 && !empty($straynewcat)) {
                    $request = $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'type' => 'string'), array($straynewcat, '0', 'category'), array('id'));
                    $newcategory = $smcFunc['db_insert_id']('{db_prefix}tp_variables', 'id');
                    $smcFunc['db_free_result']($request);
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_articles 
					SET approved = {int:approved}, category = {int:cat} 
					WHERE id IN ({array_int:artid})', array('approved' => 1, 'cat' => !empty($newcategory) ? $newcategory : $category, 'artid' => $ccats));
                $smcFunc['db_query']('', '
					DELETE FROM {db_prefix}tp_variables 
					WHERE type = {string:type} 
					AND value5 IN ({array_int:val5})', array('type' => 'art_not_approved', 'val5' => $ccats));
            }
            return $from;
        } elseif ($from == 'blocks') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 3) == 'pos') {
                    $where = substr($what, 3);
                    if (is_numeric($where)) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET pos = {int:pos} 
							WHERE id = {int:blockid}', array('pos' => $value, 'blockid' => $where));
                    }
                } elseif (substr($what, 0, 6) == 'addpos') {
                    $where = substr($what, 6);
                    if (is_numeric($where)) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET pos = (pos + 11) 
							WHERE id = {int:blockid}', array('blockid' => $where));
                    }
                } elseif (substr($what, 0, 6) == 'subpos') {
                    $where = substr($what, 6);
                    if (is_numeric($where)) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks SET pos = (pos - 11) 
							WHERE id = {int:blockid}', array('blockid' => $where));
                    }
                } elseif (substr($what, 0, 4) == 'type') {
                    $where = substr($what, 4);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET type = {int:type} 
						WHERE id = {int:blockid}', array('type' => $value, 'blockid' => $where));
                } elseif (substr($what, 0, 5) == 'title') {
                    $where = strip_tags(substr($what, 5));
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET title = {string:title} 
						WHERE id = {int:blockid}', array('title' => $value, 'blockid' => $where));
                } elseif (substr($what, 0, 9) == 'blockbody') {
                    $where = tp_sanitize(substr($what, 9));
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET body = {string:body} 
						WHERE id = {int:blockid}', array('body' => $value, 'blockid' => $where));
                }
            }
            redirectexit('action=tpadmin;sa=blocks');
        } elseif ($from == 'addblock') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $title = empty($_POST['tp_addblocktitle']) ? '-no title-' : $_POST['tp_addblocktitle'];
            $panel = $_POST['tp_addblockpanel'];
            $type = $_POST['tp_addblock'];
            if (!is_numeric($type)) {
                if (substr($type, 0, 3) == 'mb_') {
                    $request = $smcFunc['db_query']('', '
						SELECT * FROM {db_prefix}tp_blocks 
						WHERE id = {int:blockid}', array('blockid' => substr($type, 3)));
                    if ($smcFunc['db_num_rows']($request) > 0) {
                        $cp = $smcFunc['db_fetch_assoc']($request);
                        $smcFunc['db_free_result']($request);
                    }
                } else {
                    $od = TPparseModfile(file_get_contents($boarddir . '/tp-files/tp-blockcodes/' . $type . '.blockcode'), array('code'));
                }
            }
            if (isset($od['code'])) {
                $body = tp_convertphp($od['code']);
                $type = 10;
            } else {
                $body = '';
            }
            if (isset($cp)) {
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_blocks', array('type' => 'int', 'frame' => 'string', 'title' => 'string', 'body' => 'string', 'access' => 'string', 'bar' => 'int', 'pos' => 'int', 'off' => 'int', 'visible' => 'string', 'var1' => 'int', 'var2' => 'int', 'lang' => 'string', 'access2' => 'string', 'editgroups' => 'string'), array($cp['type'], $cp['frame'], $title, $cp['body'], $cp['access'], $panel, 0, 1, 1, $cp['var1'], $cp['var2'], $cp['lang'], $cp['access2'], $cp['editgroups']), array('id'));
            } else {
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_blocks', array('type' => 'int', 'frame' => 'string', 'title' => 'string', 'body' => 'string', 'access' => 'string', 'bar' => 'int', 'pos' => 'int', 'off' => 'int', 'visible' => 'string', 'var1' => 'int', 'var2' => 'int', 'lang' => 'string', 'access2' => 'string', 'editgroups' => 'string'), array($type, 'theme', $title, $body, '-1,0,1', $panel, 0, 1, 1, 0, 0, '', 'actio=allpages', ''), array('id'));
            }
            $where = $smcFunc['db_insert_id']('{db_prefix}tp_blocks', 'id');
            if (!empty($where)) {
                redirectexit('action=tpadmin;blockedit=' . $where . ';sesc=' . $context['session_id']);
            } else {
                redirectexit('action=tpadmin;sa=blocks');
            }
        } elseif ($from == 'blockedit') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $where = is_numeric($_POST['tpadmin_form_id']) ? $_POST['tpadmin_form_id'] : 0;
            $tpgroups = array();
            $editgroups = array();
            $access = array();
            $lang = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 9) == 'tp_block_') {
                    $setting = substr($what, 9);
                    if ($setting == 'body') {
                        // If we came from WYSIWYG then turn it back into BBC regardless.
                        if (!empty($_REQUEST['tp_block_body_mode']) && isset($_REQUEST['tp_block_body'])) {
                            require_once $sourcedir . '/Subs-Editor.php';
                            $_REQUEST['tp_block_body'] = html_to_bbc($_REQUEST['tp_block_body']);
                            // We need to unhtml it now as it gets done shortly.
                            $_REQUEST['tp_block_body'] = un_htmlspecialchars($_REQUEST['tp_block_body']);
                            // We need this for everything else.
                            $value = $_POST['tp_block_body'] = $_REQUEST['tp_block_body'];
                        }
                        // PHP block?
                        if ($_POST['tp_block_type'] == 10) {
                            $value = tp_convertphp($value);
                        }
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET ' . $setting . ' = {string:value} 
							WHERE id = {int:blockid}', array('value' => $value, 'blockid' => $where));
                    } elseif ($setting == 'title') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET title = {string:title} 
							WHERE id = {int:blockid}', array('title' => $value, 'blockid' => $where));
                    } elseif ($setting == 'body_mode' || $setting == 'body_choice' || $setting == 'body_pure') {
                        $go = '';
                    } elseif ($setting == 'frame') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET frame = {string:val}
							WHERE id = {int:blockid}', array('val' => $value, 'blockid' => $where));
                    } else {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET ' . $setting . ' = {raw:val}
							WHERE id = {int:blockid}', array('val' => $value, 'blockid' => $where));
                    }
                } elseif (substr($what, 0, 8) == 'tp_group') {
                    $tpgroups[] = substr($what, 8);
                } elseif (substr($what, 0, 12) == 'tp_editgroup') {
                    $editgroups[] = substr($what, 12);
                } elseif (substr($what, 0, 10) == 'actiontype') {
                    $access[] = 'actio=' . $value;
                } elseif (substr($what, 0, 9) == 'boardtype') {
                    $access[] = 'board=' . $value;
                } elseif (substr($what, 0, 11) == 'articletype') {
                    $access[] = 'tpage=' . $value;
                } elseif (substr($what, 0, 12) == 'categorytype') {
                    $access[] = 'tpcat=' . $value;
                } elseif (substr($what, 0, 8) == 'langtype') {
                    $access[] = 'tlang=' . $value;
                } elseif (substr($what, 0, 9) == 'dlcattype') {
                    $access[] = 'dlcat=' . $value;
                } elseif (substr($what, 0, 9) == 'tpmodtype') {
                    $access[] = 'tpmod=' . $value;
                } elseif (substr($what, 0, 9) == 'custotype' && !empty($value)) {
                    $items = explode(',', $value);
                    foreach ($items as $iti => $it) {
                        $access[] = 'actio=' . $it;
                    }
                } elseif (substr($what, 0, 8) == 'tp_lang_') {
                    if (substr($what, 8) != '') {
                        $lang[] = substr($what, 8) . '|' . $value;
                    }
                } elseif (substr($what, 0, 18) == 'tp_userbox_options') {
                    if (!isset($userbox)) {
                        $userbox = array();
                    }
                    $userbox[] = $value;
                } elseif (substr($what, 0, 8) == 'tp_theme') {
                    $theme = substr($what, 8);
                    if (!isset($themebox)) {
                        $themebox = array();
                    }
                    // get the path too
                    if (isset($_POST['tp_path' . $theme])) {
                        $tpath = $_POST['tp_path' . $theme];
                    } else {
                        $tpath = '';
                    }
                    $themebox[] = $theme . '|' . $value . '|' . $tpath;
                }
            }
            // construct the access++
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_blocks 
				SET	access2 = {string:acc2},
					access = {string:acc},
					lang = {string:lang},
					editgroups = {string:editgrp}
				WHERE id = {int:blockid}', array('acc2' => implode(',', $access), 'acc' => implode(',', $tpgroups), 'lang' => implode('|', $lang), 'editgrp' => implode(',', $editgroups), 'blockid' => $where));
            if (isset($userbox)) {
                $updateArray['userbox_options'] = implode(',', $userbox);
            }
            if (isset($themebox)) {
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_blocks 
					SET body = {string:body}
					WHERE id = {int:blockid}', array('body' => implode(',', $themebox), 'blockid' => $where));
            }
            // anything from PHP block?
            if (isset($_POST['blockcode_overwrite'])) {
                // get the blockcode
                $newval = TPparseModfile(file_get_contents($boarddir . '/tp-files/tp-blockcodes/' . $_POST['tp_blockcode'] . '.blockcode'), array('code'));
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_blocks 
					SET body = {string:body}
					WHERE id = {int:blockid}', array('body' => $newval['code'], 'blockid' => $where));
            }
            // check if uploadad picture
            if (isset($_FILES['qup_blockbody']) && file_exists($_FILES['qup_blockbody']['tmp_name'])) {
                $name = TPuploadpicture('qup_blockbody', $context['user']['id'] . 'uid');
                tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
            }
            updateTPSettings($updateArray);
            redirectexit('action=tpadmin;blockedit=' . $where . ';' . $context['session_var'] . '=' . $context['session_id']);
        } elseif (substr($from, 0, 11) == 'editarticle') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $new = false;
            $where = substr($from, 11);
            if (empty($where)) {
                // we need to create one first
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_articles', array('date' => 'int'), array(time()), array('id'));
                $where = $smcFunc['db_insert_id']('{db_prefix}tp_articles', 'id');
                $new = true;
                $from = 'editarticle' . $where;
            }
            // check if uploads are there
            if (file_exists($_FILES['tp_article_illupload']['tmp_name'])) {
                $name = TPuploadpicture('tp_article_illupload', '', '180', 'jpg,gif,png', 'tp-files/tp-articles/illustrations');
                tp_createthumb('tp-files/tp-articles/illustrations/' . $name, 128, 128, 'tp-files/tp-articles/illustrations/s_' . $name);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_articles 
					SET illustration = {string:ill} 
					WHERE id = {int:artid} LIMIT 1', array('ill' => 's_' . $name, 'artid' => $where));
            }
            // check if uploadad picture
            if (isset($_FILES['qup_tp_article_body']) && file_exists($_FILES['qup_tp_article_body']['tmp_name'])) {
                $name = TPuploadpicture('qup_tp_article_body', $context['user']['id'] . 'uid');
                tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
            }
            $options = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 11) == 'tp_article_' && !empty($where)) {
                    $setting = substr($what, 11);
                    if ($setting == 'authorid') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET author_id = {int:auth} 
							WHERE id = {int:artid} LIMIT 1', array('auth' => $value, 'artid' => $where));
                    } elseif ($setting == 'idtheme') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET id_theme = {int:id_theme} 
							WHERE id = {int:artid} LIMIT 1', array('id_theme' => $value, 'artid' => $where));
                    } elseif ($setting == 'subject') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET subject = {string:subject} 
							WHERE id = {int:artid} LIMIT 1', array('subject' => $value, 'artid' => $where));
                    } elseif ($setting == 'shortname') {
                        $value = htmlspecialchars(str_replace(' ', '-', $value), ENT_QUOTES);
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET shortname = {string:shortname} 
							WHERE id = {int:artid} LIMIT 1', array('shortname' => $value, 'artid' => $where));
                    } elseif ($setting == 'category') {
                        // for the event, get the allowed
                        $request = $smcFunc['db_query']('', '
							SELECT value3 FROM {db_prefix}tp_variables 
							WHERE id = {int:varid} LIMIT 1', array('varid' => $value));
                        if ($smcFunc['db_num_rows']($request) > 0) {
                            $row = $smcFunc['db_fetch_assoc']($request);
                            $allowed = $row['value3'];
                            $smcFunc['db_free_result']($request);
                        }
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET category = {int:cat} 
							WHERE id = {int:artid} LIMIT 1', array('cat' => $value, 'artid' => $where));
                    } elseif (in_array($setting, array('body', 'intro'))) {
                        // If we came from WYSIWYG then turn it back into BBC regardless.
                        if (!empty($_REQUEST['tp_article_body_mode']) && isset($_REQUEST['tp_article_body'])) {
                            require_once $sourcedir . '/Subs-Editor.php';
                            $_REQUEST['tp_article_body'] = html_to_bbc($_REQUEST['tp_article_body']);
                            // We need to unhtml it now as it gets done shortly.
                            $_REQUEST['tp_article_body'] = un_htmlspecialchars($_REQUEST['tp_article_body']);
                            // We need this for everything else.
                            if ($setting == 'body') {
                                $value = $_POST['tp_article_body'] = $_REQUEST['tp_article_body'];
                            } elseif ($settings == 'intro') {
                                $value = $_POST['tp_article_intro'] = $_REQUEST['tp_article_intro'];
                            }
                        }
                        // in case of HTML article we need to check it
                        if (isset($_POST['tp_article_body_pure']) && isset($_POST['tp_article_body_choice'])) {
                            if ($_POST['tp_article_body_choice'] == 0) {
                                if ($setting == 'body') {
                                    $value = $_POST['tp_article_body_pure'];
                                } elseif ($setting == 'intro') {
                                    $value = $_POST['tp_article_intro'];
                                }
                            }
                            // save the choice too
                            $request = $smcFunc['db_query']('', '
								SELECT id FROM {db_prefix}tp_variables 
								WHERE subtype2 = {int:sub2}  
								AND type = {string:type} LIMIT 1', array('sub2' => $where, 'type' => 'editorchoice'));
                            if ($smcFunc['db_num_rows']($request) > 0) {
                                $row = $smcFunc['db_fetch_assoc']($request);
                                $smcFunc['db_free_result']($request);
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_variables 
									SET value1 = {string:val1}
									WHERE subtype2 = {int:sub2} 
									AND type = {string:type}', array('val1' => $_POST['tp_article_body_choice'], 'sub2' => $where, 'type' => 'editorchoice'));
                            } else {
                                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'type' => 'string', 'subtype2' => 'int'), array($_POST['tp_article_body_choice'], 'editorchoice', $where), array('id'));
                            }
                        }
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET ' . $setting . ' = {string:val} 
							WHERE id = {int:artid} LIMIT 1', array('val' => $value, 'artid' => $where));
                    } elseif (in_array($setting, array('day', 'month', 'year', 'minute', 'hour', 'timestamp'))) {
                        $timestamp = mktime($_POST['tp_article_hour'], $_POST['tp_article_minute'], 0, $_POST['tp_article_month'], $_POST['tp_article_day'], $_POST['tp_article_year']);
                        if (!isset($savedtime)) {
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}tp_articles 
								SET date = {int:date} 
								WHERE id = {int:artid} LIMIT 1', array('date' => $timestamp, 'artid' => $where));
                        }
                        $savedtime = 1;
                    } elseif (in_array($setting, array('pubstartday', 'pubstartmonth', 'pubstartyear', 'pubstartminute', 'pubstarthour', 'pub_start'))) {
                        // are all zero? then skip
                        if (empty($_POST['tp_article_pubstarthour']) && empty($_POST['tp_article_pubstartminute']) && empty($_POST['tp_article_pubstartmonth']) && empty($_POST['tp_article_pubstartday']) && empty($_POST['tp_article_pubstartyear'])) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_articles 
									SET pub_start = {int:start}
									WHERE id = {int:artid} LIMIT 1', array('start' => 0, 'artid' => $where));
                        } else {
                            $timestamp = mktime($_POST['tp_article_pubstarthour'], $_POST['tp_article_pubstartminute'], 0, $_POST['tp_article_pubstartmonth'], $_POST['tp_article_pubstartday'], $_POST['tp_article_pubstartyear']);
                        }
                        if (!isset($pubstart)) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_articles 
									SET pub_start = {int:start} 
									WHERE id = {int:artid} LIMIT 1', array('start' => $timestamp, 'artid' => $where));
                        }
                        $pubstart = 1;
                    } elseif (in_array($setting, array('pubendday', 'pubendmonth', 'pubendyear', 'pubendminute', 'pubendhour', 'pub_start'))) {
                        // are all zero? then skip
                        if (empty($_POST['tp_article_pubendhour']) && empty($_POST['tp_article_pubendminute']) && empty($_POST['tp_article_pubendmonth']) && empty($_POST['tp_article_pubendday']) && empty($_POST['tp_article_pubendyear'])) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_articles 
									SET pub_end = {int:end}
									WHERE id = {int:artid} LIMIT 1', array('end' => 0, 'artid' => $where));
                        } else {
                            $timestamp = mktime($_POST['tp_article_pubendhour'], $_POST['tp_article_pubendminute'], 0, $_POST['tp_article_pubendmonth'], $_POST['tp_article_pubendday'], $_POST['tp_article_pubendyear']);
                        }
                        if (!isset($pubend)) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_articles 
									SET pub_end = {int:end}
									WHERE id = {int:artid} LIMIT 1', array('end' => $timestamp, 'artid' => $where));
                        }
                        $pubend = 1;
                    } elseif (substr($setting, 0, 8) == 'options_') {
                        if (substr($setting, 0, 19) == 'options_lblockwidth' || substr($setting, 0, 19) == 'options_rblockwidth') {
                            $options[] = substr($setting, 8) . $value;
                        } else {
                            $options[] = substr($setting, 8);
                        }
                    } elseif (in_array($setting, array('body_mode', 'intro_mode', 'illupload', 'body_pure', 'body_choice'))) {
                        // ignore it
                        continue;
                    } elseif ($setting == 'approved') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET approved = {int:approved} 
							WHERE id = {int:artid} LIMIT 1', array('approved' => $value, 'artid' => $where));
                        if ($value == 1) {
                            $smcFunc['db_query']('', '
								DELETE FROM {db_prefix}tp_variables 
								WHERE type = {string:type} 
								AND value5 = {int:val5}', array('type' => 'art_not_approved', 'val5' => $where));
                        } elseif ($new) {
                            $smcFunc['db_insert']('replace', '{db_prefix}tp_variables', array('type' => 'string', 'value5' => 'int'), array('art_not_approved', $where), array('id'));
                        }
                    } else {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET ' . $setting . ' = {string:val}
							WHERE id = {int:artid} LIMIT 1', array('val' => $value, 'artid' => $where));
                    }
                }
            }
            // if this was a new article
            if ($_POST['tp_article_approved'] == 1 && $_POST['tp_article_off'] == 0) {
                tp_recordevent($timestamp, $_POST['tp_article_authorid'], 'tp-createdarticle', 'page=' . $where, 'Creation of new article.', isset($allowed) ? $allowed : 0, $where);
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_articles 
				SET options = {string:opt} 
				WHERE id = {int:artid} LIMIT 1', array('opt' => implode(',', $options), 'artid' => $where));
        }
    } else {
        return;
    }
}
function shd_admin_canned_savereply()
{
    global $context, $smcFunc, $sourcedir, $txt;
    checkSession('request');
    require_once $sourcedir . '/Subs-Editor.php';
    require_once $sourcedir . '/Subs-Post.php';
    // If we're deleting this reply, do it first and get it out the way.
    if (!empty($_REQUEST['delete'])) {
        $_REQUEST['reply'] = isset($_REQUEST['reply']) ? (int) $_REQUEST['reply'] : 0;
        if ($_REQUEST['reply'] > 0) {
            // 1. Get the current position.
            $query = $smcFunc['db_query']('', '
				SELECT reply_order
				FROM {db_prefix}helpdesk_cannedreplies
				WHERE id_reply = {int:reply}', array('reply' => $_REQUEST['reply']));
            if ($smcFunc['db_num_rows']($query) == 0) {
                redirectexit('action=admin;area=helpdesk_cannedreplies');
            }
            list($old_pos) = $smcFunc['db_fetch_row']($query);
            $smcFunc['db_free_result']($query);
            // 2. Delete the reply itself.
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}helpdesk_cannedreplies
				WHERE id_reply = {int:reply}', array('reply' => $_REQUEST['reply']));
            // 3. Shunt the rest up one.
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}helpdesk_cannedreplies
				SET reply_order = reply_order - 1
				WHERE reply_order > {int:old_pos}', array('old_pos' => $old_pos));
            // 4. Delete any attached departments.
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}helpdesk_cannedreplies_depts
				WHERE id_reply = {int:reply}', array('reply' => $_REQUEST['reply']));
        }
        redirectexit('action=admin;area=helpdesk_cannedreplies');
    }
    if (empty($_REQUEST['reply'])) {
        fatal_lang_error('shd_admin_cannedreplies_thereplyisalie', false);
    }
    $_POST['title'] = isset($_POST['title']) ? strtr($smcFunc['htmlspecialchars']($_POST['title']), array("\r" => '', "\n" => '', "\t" => '')) : '';
    if (empty($_POST['title'])) {
        fatal_lang_error('shd_admin_cannedreplies_notitle', false);
    }
    $_REQUEST['shd_canned_reply'] = isset($_POST['shd_canned_reply']) ? $_POST['shd_canned_reply'] : '';
    // If we came from WYSIWYG, we need to convert from HTML to bbc, then unhtml it.
    if (!empty($_REQUEST['shd_canned_reply_mode'])) {
        $_REQUEST['shd_canned_reply'] = un_htmlspecialchars(html_to_bbc($_REQUEST['shd_canned_reply']));
        $_POST['shd_canned_reply'] = $_REQUEST['shd_canned_reply'];
    }
    if ($smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['shd_canned_reply']), ENT_QUOTES) === '') {
        fatal_lang_error('shd_admin_cannedreplies_nobody', false);
    }
    $_POST['shd_canned_reply'] = $smcFunc['htmlspecialchars']($_POST['shd_canned_reply'], ENT_QUOTES);
    preparsecode($_POST['shd_canned_reply']);
    // Now clean up the rest of the stuff.
    $_POST['vis_user'] = !empty($_POST['vis_user']) ? 1 : 0;
    $_POST['vis_staff'] = !empty($_POST['vis_staff']) ? 1 : 0;
    $_POST['active'] = !empty($_POST['active']) ? 1 : 0;
    // Verify the destination category exists.
    if (!isset($_POST['cat'])) {
        fatal_lang_error('shd_admin_cannedreplies_thecatisalie', false);
    }
    $query = $smcFunc['db_query']('', '
		SELECT cat_name
		FROM {db_prefix}helpdesk_cannedreplies_cats
		WHERE id_cat = {int:cat}', array('cat' => (int) $_REQUEST['cat']));
    if ($smcFunc['db_num_rows']($query) == 0) {
        $smcFunc['db_free_result']($query);
        fatal_lang_error('shd_admin_cannedreplies_thecatisalie', false);
    }
    $smcFunc['db_free_result']($query);
    // Lastly, figure out what departments we're doing.
    $depts_insert = array();
    $query = $smcFunc['db_query']('', '
		SELECT id_dept
		FROM {db_prefix}helpdesk_depts
		ORDER BY dept_order');
    while ($row = $smcFunc['db_fetch_assoc']($query)) {
        if (!empty($_POST['dept_' . $row['id_dept']])) {
            $depts_insert[] = $row['id_dept'];
        }
    }
    $smcFunc['db_free_result']($query);
    checkSubmitOnce('check');
    if ($_REQUEST['reply'] == 'new') {
        // 1. Get the next reply order
        $query = $smcFunc['db_query']('', '
			SELECT MAX(reply_order)
			FROM {db_prefix}helpdesk_cannedreplies');
        list($current_max) = $smcFunc['db_fetch_row']($query);
        $smcFunc['db_free_result']($query);
        // 2. Insert the row.
        $smcFunc['db_insert']('insert', '{db_prefix}helpdesk_cannedreplies', array('id_cat' => 'int', 'title' => 'string', 'body' => 'string', 'vis_user' => 'int', 'vis_staff' => 'int', 'reply_order' => 'int', 'active' => 'int'), array($_POST['cat'], $_POST['title'], $_POST['shd_canned_reply'], $_POST['vis_user'], $_POST['vis_staff'], (int) $current_max + 1, $_POST['active']), array('id_cat'));
        // 3. Insert the departments.
        $reply_id = $smcFunc['db_insert_id']('{db_prefix}helpdesk_cannedreplies', 'id_reply');
        if (empty($reply_id)) {
            fatal_lang_error('shd_admin_cannedreplies_notcreated', false);
        }
        $insert = array();
        foreach ($depts_insert as $dept) {
            $insert[] = array($dept, $reply_id);
        }
        $smcFunc['db_insert']('insert', '{db_prefix}helpdesk_cannedreplies_depts', array('id_dept' => 'int', 'id_reply' => 'int'), $insert, array('id_dept', 'id_reply'));
    } else {
        // Verify it exists.
        $query = $smcFunc['db_query']('', '
			SELECT id_reply
			FROM {db_prefix}helpdesk_cannedreplies
			WHERE id_reply = {int:reply}', array('reply' => $_REQUEST['reply']));
        if ($smcFunc['db_num_rows']($query) == 0) {
            fatal_lang_error('shd_admin_cannedreplies_thereplyisalie', false);
        }
        $smcFunc['db_free_result']($query);
        // We're updating, apparently.
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}helpdesk_cannedreplies
			SET title = {string:title},
				body = {string:body},
				vis_user = {int:vis_user},
				vis_staff = {int:vis_staff},
				active = {int:active}
			WHERE id_reply = {int:reply}', array('reply' => $_REQUEST['reply'], 'title' => $_POST['title'], 'body' => $_POST['shd_canned_reply'], 'vis_user' => $_POST['vis_user'], 'vis_staff' => $_POST['vis_staff'], 'active' => $_POST['active']));
        // Sort out departments. Nuke the existing ones first.
        $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}helpdesk_cannedreplies_depts
			WHERE id_reply = {int:reply}', array('reply' => $_REQUEST['reply']));
        $insert = array();
        foreach ($depts_insert as $dept) {
            $insert[] = array($dept, $_REQUEST['reply']);
        }
        $smcFunc['db_insert']('insert', '{db_prefix}helpdesk_cannedreplies_depts', array('id_dept' => 'int', 'id_reply' => 'int'), $insert, array('id_dept', 'id_reply'));
    }
    redirectexit('action=admin;area=helpdesk_cannedreplies');
}
/**
* 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']);
        }
    }
}
Beispiel #18
0
function shd_save_post()
{
    global $txt, $modSettings, $sourcedir, $context, $scripturl;
    global $user_info, $options, $smcFunc;
    // Oh no, robots!
    $context['robot_no_index'] = true;
    $context['shd_errors'] = array();
    // We'll probably be needing these.
    require_once $sourcedir . '/Subs-Editor.php';
    require_once $sourcedir . '/Subs-Post.php';
    require_once $sourcedir . '/sd_source/Subs-SimpleDeskPost.php';
    loadTemplate('sd_template/SimpleDesk-Post');
    loadLanguage('Errors');
    // for some of the errors we already have
    loadLanguage('Post');
    // for some of the common post errors
    $context['template_layers'][] = 'shd_post_nojs';
    if (!empty($_REQUEST['shd_message_mode']) && isset($_REQUEST['shd_message'])) {
        // If we came from WYSIWYG, we need to convert from HTML to bbc, then unhtml it; then push to $_POST for everything else
        $_REQUEST['shd_message'] = un_htmlspecialchars(html_to_bbc($_REQUEST['shd_message']));
        $_POST['shd_message'] = $_REQUEST['shd_message'];
    }
    // Check session and double-posting
    checkSubmitOnce('check');
    if (checkSession('post', '', false) != '') {
        $context['shd_errors'][] = 'session_timeout';
    }
    // Clean up the details
    if (!isset($_POST['shd_message']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['shd_message']), ENT_QUOTES) === '') {
        $context['shd_errors'][] = 'no_message';
        $_POST['shd_message'] = '';
    } else {
        // Pfft.
        if (isset($_POST['shd_message']) && strtolower($_POST['shd_message']) == 'this is simpledesk!') {
            fatal_error('You are not King Leonidas...', false);
        }
        $_POST['shd_message'] = $smcFunc['htmlspecialchars']($_POST['shd_message'], ENT_QUOTES);
        preparsecode($_POST['shd_message']);
        // Make sure there's something underneath all the tags
        if ($smcFunc['htmltrim'](strip_tags(shd_format_text($_POST['shd_message'], false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($_POST['shd_message'], '[html]') === false)) {
            $context['shd_errors'][] = 'no_message';
        } elseif (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_POST['shd_message']) > $modSettings['max_messageLength']) {
            $context['shd_errors'][] = 'long_message';
            $txt['error_long_message'] = sprintf($txt['error_long_message'], $modSettings['max_messageLength']);
        }
    }
    // Now send them off to the specific areas, whether that's saving a ticket or a reply
    $actions = array('saveticket' => 'shd_save_ticket', 'savereply' => 'shd_save_reply');
    if (isset($actions[$_REQUEST['sa']])) {
        $actions[$_REQUEST['sa']]();
    }
}
Beispiel #19
0
function MessagePost2()
{
    global $txt, $context, $sourcedir;
    global $user_info, $modSettings, $scripturl, $smcFunc;
    isAllowedTo('pm_send');
    require_once $sourcedir . '/Subs-Auth.php';
    loadLanguage('PersonalMessage', '', false);
    // Extract out the spam settings - it saves database space!
    list($modSettings['max_pm_recipients'], $modSettings['pm_posts_verification'], $modSettings['pm_posts_per_hour']) = explode(',', $modSettings['pm_spam_settings']);
    // Check whether we've gone over the limit of messages we can send per hour - fatal error if fails!
    if (!empty($modSettings['pm_posts_per_hour']) && !allowedTo(array('admin_forum', 'moderate_forum', 'send_mail')) && $user_info['mod_cache']['bq'] == '0=1' && $user_info['mod_cache']['gq'] == '0=1') {
        // How many have they sent this last hour?
        $request = $smcFunc['db_query']('', '
			SELECT COUNT(pr.id_pm) AS post_count
			FROM {db_prefix}personal_messages AS pm
				INNER JOIN {db_prefix}pm_recipients AS pr ON (pr.id_pm = pm.id_pm)
			WHERE pm.id_member_from = {int:current_member}
				AND pm.msgtime > {int:msgtime}', array('current_member' => $user_info['id'], 'msgtime' => time() - 3600));
        list($postCount) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
        if (!empty($postCount) && $postCount >= $modSettings['pm_posts_per_hour']) {
            fatal_lang_error('pm_too_many_per_hour', true, array($modSettings['pm_posts_per_hour']));
        }
    }
    // If we came from WYSIWYG then turn it back into BBC regardless.
    if (!empty($_POST['message_mode']) && isset($_POST['message'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_POST['message'] = html_to_bbc($_POST['message']);
        // We need to unhtml it now as it gets done shortly.
        $_POST['message'] = un_htmlspecialchars($_POST['message']);
        // We need this in case of errors etc.
        $_REQUEST['message'] = $_POST['message'];
    }
    // Initialize the errors we're about to make.
    $post_errors = array();
    // If your session timed out, show an error, but do allow to re-submit.
    if (checkSession('post', '', false) != '') {
        $post_errors[] = 'session_timeout';
    }
    $_REQUEST['subject'] = isset($_REQUEST['subject']) ? trim($_REQUEST['subject']) : '';
    $_REQUEST['to'] = empty($_POST['to']) ? empty($_GET['to']) ? '' : $_GET['to'] : $_POST['to'];
    $_REQUEST['bcc'] = empty($_POST['bcc']) ? empty($_GET['bcc']) ? '' : $_GET['bcc'] : $_POST['bcc'];
    // Route the input from the 'u' parameter to the 'to'-list.
    if (!empty($_POST['u'])) {
        $_POST['recipient_to'] = explode(',', $_POST['u']);
    }
    // Construct the list of recipients.
    $recipientList = array();
    $namedRecipientList = array();
    $namesNotFound = array();
    foreach (array('to', 'bcc') as $recipientType) {
        // First, let's see if there's user ID's given.
        $recipientList[$recipientType] = array();
        if (!empty($_POST['recipient_' . $recipientType]) && is_array($_POST['recipient_' . $recipientType])) {
            foreach ($_POST['recipient_' . $recipientType] as $recipient) {
                $recipientList[$recipientType][] = (int) $recipient;
            }
        }
        // Are there also literal names set?
        if (!empty($_REQUEST[$recipientType])) {
            // We're going to take out the "s anyway ;).
            $recipientString = strtr($_REQUEST[$recipientType], array('\\"' => '"'));
            preg_match_all('~"([^"]+)"~', $recipientString, $matches);
            $namedRecipientList[$recipientType] = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $recipientString))));
            foreach ($namedRecipientList[$recipientType] as $index => $recipient) {
                if (strlen(trim($recipient)) > 0) {
                    $namedRecipientList[$recipientType][$index] = $smcFunc['htmlspecialchars']($smcFunc['strtolower'](trim($recipient)));
                } else {
                    unset($namedRecipientList[$recipientType][$index]);
                }
            }
            if (!empty($namedRecipientList[$recipientType])) {
                $foundMembers = findMembers($namedRecipientList[$recipientType]);
                // Assume all are not found, until proven otherwise.
                $namesNotFound[$recipientType] = $namedRecipientList[$recipientType];
                foreach ($foundMembers as $member) {
                    $testNames = array($smcFunc['strtolower']($member['username']), $smcFunc['strtolower']($member['name']), $smcFunc['strtolower']($member['email']));
                    if (count(array_intersect($testNames, $namedRecipientList[$recipientType])) !== 0) {
                        $recipientList[$recipientType][] = $member['id'];
                        // Get rid of this username, since we found it.
                        $namesNotFound[$recipientType] = array_diff($namesNotFound[$recipientType], $testNames);
                    }
                }
            }
        }
        // Selected a recipient to be deleted? Remove them now.
        if (!empty($_POST['delete_recipient'])) {
            $recipientList[$recipientType] = array_diff($recipientList[$recipientType], array((int) $_POST['delete_recipient']));
        }
        // Make sure we don't include the same name twice
        $recipientList[$recipientType] = array_unique($recipientList[$recipientType]);
    }
    // Are we changing the recipients some how?
    $is_recipient_change = !empty($_POST['delete_recipient']) || !empty($_POST['to_submit']) || !empty($_POST['bcc_submit']);
    // Check if there's at least one recipient.
    if (empty($recipientList['to']) && empty($recipientList['bcc'])) {
        $post_errors[] = 'no_to';
    }
    // Make sure that we remove the members who did get it from the screen.
    if (!$is_recipient_change) {
        foreach ($recipientList as $recipientType => $dummy) {
            if (!empty($namesNotFound[$recipientType])) {
                $post_errors[] = 'bad_' . $recipientType;
                // Since we already have a post error, remove the previous one.
                $post_errors = array_diff($post_errors, array('no_to'));
                foreach ($namesNotFound[$recipientType] as $name) {
                    $context['send_log']['failed'][] = sprintf($txt['pm_error_user_not_found'], $name);
                }
            }
        }
    }
    // Did they make any mistakes?
    if ($_REQUEST['subject'] == '') {
        $post_errors[] = 'no_subject';
    }
    if (!isset($_REQUEST['message']) || $_REQUEST['message'] == '') {
        $post_errors[] = 'no_message';
    } elseif (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_REQUEST['message']) > $modSettings['max_messageLength']) {
        $post_errors[] = 'long_message';
    } else {
        // Preparse the message.
        $message = $_REQUEST['message'];
        preparsecode($message);
        // Make sure there's still some content left without the tags.
        if ($smcFunc['htmltrim'](strip_tags(parse_bbc($smcFunc['htmlspecialchars']($message, ENT_QUOTES), false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($message, '[html]') === false)) {
            $post_errors[] = 'no_message';
        }
    }
    // Wrong verification code?
    if (!$user_info['is_admin'] && !empty($modSettings['pm_posts_verification']) && $user_info['posts'] < $modSettings['pm_posts_verification']) {
        require_once $sourcedir . '/Subs-Editor.php';
        $verificationOptions = array('id' => 'pm');
        $context['require_verification'] = create_control_verification($verificationOptions, true);
        if (is_array($context['require_verification'])) {
            $post_errors = array_merge($post_errors, $context['require_verification']);
        }
    }
    // If they did, give a chance to make ammends.
    if (!empty($post_errors) && !$is_recipient_change && !isset($_REQUEST['preview'])) {
        return messagePostError($post_errors, $namedRecipientList, $recipientList);
    }
    // Want to take a second glance before you send?
    if (isset($_REQUEST['preview'])) {
        // Set everything up to be displayed.
        $context['preview_subject'] = $smcFunc['htmlspecialchars']($_REQUEST['subject']);
        $context['preview_message'] = $smcFunc['htmlspecialchars']($_REQUEST['message'], ENT_QUOTES);
        preparsecode($context['preview_message'], true);
        // Parse out the BBC if it is enabled.
        $context['preview_message'] = parse_bbc($context['preview_message']);
        // Censor, as always.
        censorText($context['preview_subject']);
        censorText($context['preview_message']);
        // Set a descriptive title.
        $context['page_title'] = $txt['preview'] . ' - ' . $context['preview_subject'];
        // Pretend they messed up but don't ignore if they really did :P.
        return messagePostError($post_errors, $namedRecipientList, $recipientList);
    } elseif ($is_recipient_change) {
        // Maybe we couldn't find one?
        foreach ($namesNotFound as $recipientType => $names) {
            $post_errors[] = 'bad_' . $recipientType;
            foreach ($names as $name) {
                $context['send_log']['failed'][] = sprintf($txt['pm_error_user_not_found'], $name);
            }
        }
        return messagePostError(array(), $namedRecipientList, $recipientList);
    } elseif (!empty($modSettings['max_pm_recipients']) && count($recipientList['to']) + count($recipientList['bcc']) > $modSettings['max_pm_recipients'] && !allowedTo(array('moderate_forum', 'send_mail', 'admin_forum'))) {
        $context['send_log'] = array('sent' => array(), 'failed' => array(sprintf($txt['pm_too_many_recipients'], $modSettings['max_pm_recipients'])));
        return messagePostError($post_errors, $namedRecipientList, $recipientList);
    }
    // Protect from message spamming.
    spamProtection('pm');
    // Prevent double submission of this form.
    checkSubmitOnce('check');
    // Do the actual sending of the PM.
    if (!empty($recipientList['to']) || !empty($recipientList['bcc'])) {
        $context['send_log'] = sendpm($recipientList, $_REQUEST['subject'], $_REQUEST['message'], !empty($_REQUEST['outbox']), null, !empty($_REQUEST['pm_head']) ? (int) $_REQUEST['pm_head'] : 0);
    } else {
        $context['send_log'] = array('sent' => array(), 'failed' => array());
    }
    // Mark the message as "replied to".
    if (!empty($context['send_log']['sent']) && !empty($_REQUEST['replied_to']) && isset($_REQUEST['f']) && $_REQUEST['f'] == 'inbox') {
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}pm_recipients
			SET is_read = is_read | 2
			WHERE id_pm = {int:replied_to}
				AND id_member = {int:current_member}', array('current_member' => $user_info['id'], 'replied_to' => (int) $_REQUEST['replied_to']));
    }
    // If one or more of the recipient were invalid, go back to the post screen with the failed usernames.
    if (!empty($context['send_log']['failed'])) {
        return messagePostError($post_errors, $namesNotFound, array('to' => array_intersect($recipientList['to'], $context['send_log']['failed']), 'bcc' => array_intersect($recipientList['bcc'], $context['send_log']['failed'])));
    }
    // Message sent successfully?
    if (!empty($context['send_log']) && empty($context['send_log']['failed'])) {
        $context['current_label_redirect'] = $context['current_label_redirect'] . ';done=sent';
    }
    // Go back to the where they sent from, if possible...
    redirectexit($context['current_label_redirect']);
}
Beispiel #20
0
function UpdateJSONFeedBots()
{
    global $smcFunc, $txt, $context, $sourcedir, $tag_attrs, $feedcount, $smcFunc, $maxitemcount, $insideitem, $tag, $modSettings;
    // Load the language files
    if (loadlanguage('FeedPoster') == false) {
        loadLanguage('FeedPoster', 'english');
    }
    // First get all the enabled bots
    $context['feeds'] = array();
    $request = $smcFunc['db_query']('', "\n\t\t\tSELECT\n\t\t\t\tID_FEED, ID_BOARD, feedurl, title, postername, updatetime, enabled, html,\n\t\t\t\tID_MEMBER, locked, articlelink, topicprefix, numbertoimport, importevery,\n\t\t\t\tmsgicon, footer, id_topic  \n\t\t\tFROM {db_prefix}feedbot\n\t\t\tWHERE enabled = 1 AND json = 1");
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        $request2 = $smcFunc['db_query']('', "\n\t\t\tSELECT\n\t\t\t\tcount_posts\n\t\t\tFROM {db_prefix}boards \n\t\t\tWHERE ID_BOARD = " . $row['ID_BOARD']);
        $row2 = $smcFunc['db_fetch_assoc']($request2);
        $row['count_posts'] = $row2['count_posts'];
        $context['feeds'][] = $row;
    }
    $smcFunc['db_free_result']($request);
    // For the createPost function
    require_once $sourcedir . '/Subs-Post.php';
    require_once $sourcedir . '/Subs-Editor.php';
    // Check if a field expired
    foreach ($context['feeds'] as $key => $feed) {
        $current_time = time();
        // If the feedbot time to next import has expired
        if ($current_time > $feed['updatetime']) {
            $feeddata = disguise_curl($feed['feedurl']);
            $json_feed_object = json_decode($feeddata);
            $feedcount = 0;
            $context['feeditems'] = array();
            if (!empty($json_feed_object->entries)) {
                foreach ($json_feed_object->entries as $entry) {
                    // echo "<h2>{$entry->title}</h2>";
                    // $published = date("g:i A F j, Y", strtotime($entry->published));
                    // echo "<small>{$published}</small>";
                    //echo "<p>{$entry->content}</p>";
                    $context['feeditems'][$feedcount]['title'] = (string) $entry->title;
                    $context['feeditems'][$feedcount]['description'] = (string) $entry->content;
                    $context['feeditems'][$feedcount]['description'] = html_to_bbc($context['feeditems'][$feedcount]['description']);
                    $context['feeditems'][$feedcount]['link'] = (string) $entry->alternate;
                    $feedcount++;
                }
            }
            if (!empty($feeddata)) {
                // Process the XML
                $maxitemcount = $feed['numbertoimport'];
                $context['feeditems'] = array_reverse($context['feeditems']);
                // Loop though all the items
                $myfeedcount = 0;
                for ($i = 0; $i < $feedcount; $i++) {
                    if ($myfeedcount >= $maxitemcount) {
                        continue;
                    }
                    // Check feed Log
                    // Generate the hash for the log
                    if (!isset($context['feeditems'][$i]['title']) || !isset($context['feeditems'][$i]['description'])) {
                        continue;
                    }
                    if (empty($context['feeditems'][$i]['title']) && empty($context['feeditems'][$i]['description'])) {
                        continue;
                    }
                    $itemhash = md5($context['feeditems'][$i]['title'] . $context['feeditems'][$i]['description']);
                    $request = $smcFunc['db_query']('', "\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tfeedtime\n\t\t\t\t\t\t\tFROM {db_prefix}feedbot_log\n\t\t\t\t\t\t\tWHERE feedhash = '{$itemhash}'");
                    $smcFunc['db_free_result']($request);
                    // If no has has found that means no duplicate entry
                    if ($smcFunc['db_affected_rows']() == 0) {
                        // Create the Post
                        $msg_title = $smcFunc['htmlspecialchars']($feed['html'] ? $context['feeditems'][$i]['title'] : strip_tags($context['feeditems'][$i]['title']), ENT_QUOTES);
                        $msg_title = trim($msg_title);
                        $msg_body = '';
                        if ($feed['html']) {
                            $msg_body = $smcFunc['htmlspecialchars']($context['feeditems'][$i]['description'], ENT_QUOTES);
                            $msg_body = trim($msg_body);
                            preparsecode($msg_body);
                            $msg_body = '[html]' . $msg_body . '[/html]';
                            $msg_body .= $smcFunc['htmlspecialchars']("\n\n" . $txt['feedposter_source'] . "[url=" . $context['feeditems'][$i]['link'] . "]" . $msg_title . "[/url]", ENT_QUOTES);
                            if (!empty($feed['footer'])) {
                                $msg_body .= $smcFunc['htmlspecialchars']("\n\n" . $feed['footer'], ENT_QUOTES);
                            }
                        } else {
                            $msg_body = $smcFunc['htmlspecialchars'](strip_tags($context['feeditems'][$i]['description']), ENT_QUOTES);
                            $msg_body = trim($msg_body);
                            $msg_body .= $smcFunc['htmlspecialchars']("\n\n" . $txt['feedposter_source'] . "[url=" . $context['feeditems'][$i]['link'] . "]" . $msg_title . "[/url]", ENT_QUOTES);
                            if (!empty($feed['footer'])) {
                                $msg_body .= $smcFunc['htmlspecialchars']("\n\n" . $feed['footer'], ENT_QUOTES);
                            }
                        }
                        $msg_title = htmlspecialchars_decode($msg_title);
                        $msg_body = htmlspecialchars_decode($msg_body);
                        $updatePostCount = $feed['ID_MEMBER'] == 0 ? 0 : 1;
                        if ($feed['count_posts'] == 0) {
                            $updatePostCount = 0;
                        }
                        $msgOptions = array('id' => 0, 'subject' => $feed['topicprefix'] . $msg_title, 'body' => '[b]' . $msg_title . "[/b]\n\n" . $msg_body, 'icon' => $feed['msgicon'], 'smileys_enabled' => 1, 'attachments' => array());
                        $topicOptions = array('id' => $row['id_topic'], 'board' => $feed['ID_BOARD'], 'poll' => null, 'lock_mode' => $feed['locked'], 'sticky_mode' => null, 'mark_as_read' => false);
                        $posterOptions = array('id' => $feed['ID_MEMBER'], 'name' => $feed['postername'], 'email' => '', 'ip' => '127.0.0.1', 'update_post_count' => $updatePostCount);
                        createPost($msgOptions, $topicOptions, $posterOptions);
                        $topicID = 0;
                        if (isset($topicOptions['id'])) {
                            $topicID = $topicOptions['id'];
                        }
                        $msgID = 0;
                        if (isset($msgOptions['id'])) {
                            $msgID = $msgOptions['id'];
                        }
                        // Add Feed Log
                        $fid = $feed['ID_FEED'];
                        $ftime = time();
                        $smcFunc['db_query']('', "\n\t\t\t\t\t\t\t\tINSERT INTO {db_prefix}feedbot_log\n\t\t\t\t\t\t\t\t\t(ID_FEED, feedhash, feedtime, ID_TOPIC,ID_MSG)\n\t\t\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t\t\t({$fid},'{$itemhash}',{$ftime},{$topicID},{$msgID})");
                        $smcFunc['db_query']('', "\n\t\t\t\t\t\t\t\tUPDATE {db_prefix}feedbot\n\t\t\t\t\t\t\t\tSET total_posts = total_posts + 1 \n\t\t\t\t\t\t\t\tWHERE ID_FEED = {$fid}\n\t\t\t\t\t\t\t\t");
                        $myfeedcount++;
                    }
                }
            }
            // End get feed data
            // Set the RSS Feed Update time
            $updatetime = time() + 60 * $feed['importevery'];
            $smcFunc['db_query']('', "\n\t\t\tUPDATE {db_prefix}feedbot \n\t\t\tSET \n\t\t\t\tupdatetime = '{$updatetime}'\n\t\t\n\t\t\tWHERE ID_FEED = " . $feed['ID_FEED']);
        }
        // End expire check
    }
    // End for each feed
}
function sportal_admin_page_edit()
{
    global $txt, $context, $modSettings, $smcFunc, $sourcedir, $options;
    require_once $sourcedir . '/Subs-Editor.php';
    require_once $sourcedir . '/Subs-Post.php';
    $context['SPortal']['is_new'] = empty($_REQUEST['page_id']);
    if (!empty($_REQUEST['content_mode']) && $_POST['type'] == 'bbc') {
        $_REQUEST['content'] = html_to_bbc($_REQUEST['content']);
        $_REQUEST['content'] = un_htmlspecialchars($_REQUEST['content']);
        $_POST['content'] = $_REQUEST['content'];
    }
    $context['sides'] = array(5 => $txt['sp-positionHeader'], 1 => $txt['sp-positionLeft'], 2 => $txt['sp-positionTop'], 3 => $txt['sp-positionBottom'], 4 => $txt['sp-positionRight'], 6 => $txt['sp-positionFooter']);
    $blocks = getBlockInfo();
    $context['page_blocks'] = array();
    foreach ($blocks as $block) {
        $shown = false;
        $tests = array('all', 'allpages', 'sforum');
        if (!$context['SPortal']['is_new']) {
            $tests[] = 'p' . (int) $_REQUEST['page_id'];
        }
        foreach (array('display', 'display_custom') as $field) {
            if (substr($block[$field], 0, 4) === '$php') {
                continue 2;
            }
            $block[$field] = explode(',', $block[$field]);
            if (!$context['SPortal']['is_new'] && in_array('-p' . (int) $_REQUEST['page_id'], $block[$field])) {
                continue;
            }
            foreach ($tests as $test) {
                if (in_array($test, $block[$field])) {
                    $shown = true;
                    break;
                }
            }
        }
        $context['page_blocks'][$block['column']][] = array('id' => $block['id'], 'label' => $block['label'], 'shown' => $shown);
    }
    if (!empty($_POST['submit'])) {
        checkSession();
        if (!isset($_POST['title']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['title'], ENT_QUOTES)) === '') {
            fatal_lang_error('sp_error_page_name_empty', false);
        }
        if (!isset($_POST['namespace']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['namespace'], ENT_QUOTES)) === '') {
            fatal_lang_error('sp_error_page_namespace_empty', false);
        }
        $result = $smcFunc['db_query']('', '
			SELECT id_page
			FROM {db_prefix}sp_pages
			WHERE namespace = {string:namespace}
				AND id_page != {int:current}
			LIMIT 1', array('limit' => 1, 'namespace' => $smcFunc['htmlspecialchars']($_POST['namespace'], ENT_QUOTES), 'current' => (int) $_POST['page_id']));
        list($has_duplicate) = $smcFunc['db_fetch_row']($result);
        $smcFunc['db_free_result']($result);
        if (!empty($has_duplicate)) {
            fatal_lang_error('sp_error_page_namespace_duplicate', false);
        }
        if (preg_match('~[^A-Za-z0-9_]+~', $_POST['namespace']) != 0) {
            fatal_lang_error('sp_error_page_namespace_invalid_chars', false);
        }
        if (preg_replace('~[0-9]+~', '', $_POST['namespace']) === '') {
            fatal_lang_error('sp_error_page_namespace_numeric', false);
        }
        if ($_POST['type'] == 'php' && !empty($_POST['content']) && empty($modSettings['sp_disable_php_validation'])) {
            $error = sp_validate_php($_POST['content']);
            if ($error) {
                fatal_lang_error('error_sp_php_' . $error, false);
            }
        }
        $permission_set = 0;
        $groups_allowed = $groups_denied = '';
        if (!empty($_POST['permission_set'])) {
            $permission_set = (int) $_POST['permission_set'];
        } elseif (!empty($_POST['membergroups']) && is_array($_POST['membergroups'])) {
            $groups_allowed = $groups_denied = array();
            foreach ($_POST['membergroups'] as $id => $value) {
                if ($value == 1) {
                    $groups_allowed[] = (int) $id;
                } elseif ($value == -1) {
                    $groups_denied[] = (int) $id;
                }
            }
            $groups_allowed = implode(',', $groups_allowed);
            $groups_denied = implode(',', $groups_denied);
        }
        if (!empty($_POST['blocks']) && is_array($_POST['blocks'])) {
            foreach ($_POST['blocks'] as $id => $block) {
                $_POST['blocks'][$id] = (int) $block;
            }
        } else {
            $_POST['blocks'] = array();
        }
        $fields = array('namespace' => 'string', 'title' => 'string', 'body' => 'string', 'type' => 'string', 'permission_set' => 'int', 'groups_allowed' => 'string', 'groups_denied' => 'string', 'style' => 'string', 'status' => 'int');
        $page_info = array('id' => (int) $_POST['page_id'], 'namespace' => $smcFunc['htmlspecialchars']($_POST['namespace'], ENT_QUOTES), 'title' => $smcFunc['htmlspecialchars']($_POST['title'], ENT_QUOTES), 'body' => $smcFunc['htmlspecialchars']($_POST['content'], ENT_QUOTES), 'type' => $_POST['type'], 'permission_set' => $permission_set, 'groups_allowed' => $groups_allowed, 'groups_denied' => $groups_denied, 'style' => sportal_parse_style('implode'), 'status' => !empty($_POST['status']) ? 1 : 0);
        if ($page_info['type'] == 'bbc') {
            preparsecode($page_info['body']);
        }
        if ($context['SPortal']['is_new']) {
            unset($page_info['id']);
            $smcFunc['db_insert']('', '{db_prefix}sp_pages', $fields, $page_info, array('id_page'));
            $page_info['id'] = $smcFunc['db_insert_id']('{db_prefix}sp_pages', 'id_page');
        } else {
            $update_fields = array();
            foreach ($fields as $name => $type) {
                $update_fields[] = $name . ' = {' . $type . ':' . $name . '}';
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}sp_pages
				SET ' . implode(', ', $update_fields) . '
				WHERE id_page = {int:id}', $page_info);
        }
        $to_show = array();
        $not_to_show = array();
        $changes = array();
        foreach ($context['page_blocks'] as $page_blocks) {
            foreach ($page_blocks as $block) {
                if ($block['shown'] && !in_array($block['id'], $_POST['blocks'])) {
                    $not_to_show[] = $block['id'];
                } elseif (!$block['shown'] && in_array($block['id'], $_POST['blocks'])) {
                    $to_show[] = $block['id'];
                }
            }
        }
        foreach ($to_show as $id) {
            if (empty($blocks[$id]['display']) && empty($blocks[$id]['display_custom']) || $blocks[$id]['display'] == 'sportal') {
                $changes[$id] = array('display' => 'portal,p' . $page_info['id'], 'display_custom' => '');
            } elseif (in_array($blocks[$id]['display'], array('allaction', 'allboard'))) {
                $changes[$id] = array('display' => '', 'display_custom' => $blocks[$id]['display'] . ',p' . $page_info['id']);
            } elseif (in_array('-p' . $page_info['id'], explode(',', $blocks[$id]['display_custom']))) {
                $changes[$id] = array('display' => $blocks[$id]['display'], 'display_custom' => implode(',', array_diff(explode(',', $blocks[$id]['display_custom']), array('-p' . $page_info['id']))));
            } elseif (empty($blocks[$id]['display_custom'])) {
                $changes[$id] = array('display' => implode(',', array_merge(explode(',', $blocks[$id]['display']), array('p' . $page_info['id']))), 'display_custom' => '');
            } else {
                $changes[$id] = array('display' => $blocks[$id]['display'], 'display_custom' => implode(',', array_merge(explode(',', $blocks[$id]['display_custom']), array('p' . $page_info['id']))));
            }
        }
        foreach ($not_to_show as $id) {
            if (count(array_intersect(array($blocks[$id]['display'], $blocks[$id]['display_custom']), array('sforum', 'allpages', 'all'))) > 0) {
                $changes[$id] = array('display' => '', 'display_custom' => $blocks[$id]['display'] . $blocks[$id]['display_custom'] . ',-p' . $page_info['id']);
            } elseif (empty($blocks[$id]['display_custom'])) {
                $changes[$id] = array('display' => implode(',', array_diff(explode(',', $blocks[$id]['display']), array('p' . $page_info['id']))), 'display_custom' => '');
            } else {
                $changes[$id] = array('display' => implode(',', array_diff(explode(',', $blocks[$id]['display']), array('p' . $page_info['id']))), 'display_custom' => implode(',', array_diff(explode(',', $blocks[$id]['display_custom']), array('p' . $page_info['id']))));
            }
        }
        foreach ($changes as $id => $data) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}sp_blocks
				SET
					display = {string:display},
					display_custom = {string:display_custom}
				WHERE id_block = {int:id}', array('id' => $id, 'display' => $data['display'], 'display_custom' => $data['display_custom']));
        }
        redirectexit('action=admin;area=portalpages');
    }
    if (!empty($_POST['preview'])) {
        $permission_set = 0;
        $groups_allowed = $groups_denied = array();
        if (!empty($_POST['permission_set'])) {
            $permission_set = (int) $_POST['permission_set'];
        } elseif (!empty($_POST['membergroups']) && is_array($_POST['membergroups'])) {
            foreach ($_POST['membergroups'] as $id => $value) {
                if ($value == 1) {
                    $groups_allowed[] = (int) $id;
                } elseif ($value == -1) {
                    $groups_denied[] = (int) $id;
                }
            }
        }
        $context['SPortal']['page'] = array('id' => $_POST['page_id'], 'page_id' => $_POST['namespace'], 'title' => $smcFunc['htmlspecialchars']($_POST['title'], ENT_QUOTES), 'body' => $smcFunc['htmlspecialchars']($_POST['content'], ENT_QUOTES), 'type' => $_POST['type'], 'permission_set' => $permission_set, 'groups_allowed' => $groups_allowed, 'groups_denied' => $groups_denied, 'style' => sportal_parse_style('implode'), 'status' => !empty($_POST['status']));
        if ($context['SPortal']['page']['type'] == 'bbc') {
            preparsecode($context['SPortal']['page']['body']);
        }
        loadTemplate('PortalPages');
        $context['SPortal']['preview'] = true;
    } elseif ($context['SPortal']['is_new']) {
        $context['SPortal']['page'] = array('id' => 0, 'page_id' => 'page' . mt_rand(1, 5000), 'title' => $txt['sp_pages_default_title'], 'body' => '', 'type' => 'bbc', 'permission_set' => 3, 'groups_allowed' => array(), 'groups_denied' => array(), 'style' => '', 'status' => 1);
    } else {
        $_REQUEST['page_id'] = (int) $_REQUEST['page_id'];
        $context['SPortal']['page'] = sportal_get_pages($_REQUEST['page_id']);
    }
    if ($context['SPortal']['page']['type'] == 'bbc') {
        $context['SPortal']['page']['body'] = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), un_preparsecode($context['SPortal']['page']['body']));
    }
    if ($context['SPortal']['page']['type'] != 'bbc') {
        $temp_editor = !empty($options['wysiwyg_default']);
        $options['wysiwyg_default'] = false;
    }
    $editorOptions = array('id' => 'content', 'value' => $context['SPortal']['page']['body'], 'width' => '95%', 'height' => '200px', 'preview_type' => 0);
    create_control_richedit($editorOptions);
    $context['post_box_name'] = $editorOptions['id'];
    if (isset($temp_editor)) {
        $options['wysiwyg_default'] = $temp_editor;
    }
    $context['SPortal']['page']['groups'] = sp_load_membergroups();
    $context['SPortal']['page']['style'] = sportal_parse_style('explode', $context['SPortal']['page']['style'], !empty($context['SPortal']['preview']));
    $context['page_title'] = $context['SPortal']['is_new'] ? $txt['sp_admin_pages_add'] : $txt['sp_admin_pages_edit'];
    $context['sub_template'] = 'pages_edit';
}
Beispiel #22
0
function ProfileComments_Edit2()
{
    global $smcFunc, $user_info, $txt, $sourcedir;
    // Guests can't do this stuff
    is_not_guest();
    // If we came from WYSIWYG then turn it back into BBC regardless.
    if (!empty($_REQUEST['comment_mode']) && isset($_REQUEST['comment'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_REQUEST['comment'] = html_to_bbc($_REQUEST['comment']);
        // We need to unhtml it now as it gets done shortly.
        $_REQUEST['comment'] = un_htmlspecialchars($_REQUEST['comment']);
    }
    @($subject = htmlspecialchars($_POST['subject'], ENT_QUOTES));
    @($comment = htmlspecialchars($_REQUEST['comment'], ENT_QUOTES));
    @($id = (int) $_POST['commentid']);
    // Uncomment if you want the subject required
    //if ($subject == '')
    //	fatal_error($txt['pcomments_err_subject'],false);
    if ($comment == '') {
        fatal_error($txt['pcomments_err_comment'], false);
    }
    if (empty($id)) {
        fatal_error($txt['pcomments_err_nocom']);
    }
    // Check if you are allowed to edit the comment
    $dbresult = $smcFunc['db_query']('', "\n\tSELECT \n\t\tp.ID_COMMENT, p.ID_MEMBER, p.COMMENT_MEMBER_ID \n\tFROM {db_prefix}profile_comments as p \n\tWHERE p.ID_COMMENT = {$id}");
    $row = $smcFunc['db_fetch_assoc']($dbresult);
    $smcFunc['db_free_result']($dbresult);
    if (allowedTo('pcomments_edit_any') || allowedTo('pcomments_edit_own') && $row['ID_MEMBER'] == $user_info['id']) {
        // Check if you have automatic approval
        $approved = allowedTo('pcomments_autocomment') ? 1 : 0;
        // Update the Comment
        $smcFunc['db_query']('', "UPDATE {db_prefix}profile_comments\n\t\t\tSET subject = '{$subject}', comment = '{$comment}', approved = {$approved} \n\t\t WHERE ID_COMMENT = {$id} LIMIT 1");
        // Redirect back to profile
        redirectexit('action=profile;u=' . $row['COMMENT_MEMBER_ID']);
    } else {
        fatal_error($txt['pcomments_noedit'], false);
    }
}