Esempio n. 1
0
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';
}
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;
    }
}
Esempio n. 3
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');
    }
}