<?php
/*======================================================================*\
|| #################################################################### ||
|| # vBHosting Version 2                                              # ||
|| # ---------------------------------------------------------------- # ||
|| # All PHP code in this file is ©2004 GameCrash.org.                # ||
|| # http://www.gamecrash.org (soon) | http://www.letzplay.de         # ||
|| # ---------------------------------------------------------------- # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # ||
|| # http://www.vbulletin.com | http://www.vbulletin.com/license.html # ||
|| #################################################################### ||
\*======================================================================*/

error_reporting(E_ALL & ~E_NOTICE);

require_once('./includes/adminfunctions_template.php');
require_once('./includes/adminfunctions_forums.php');
require_once('./includes/adminfunctions.php');
require_once('./includes/functions_newpost.php');

// ###################### Start build forum #######################
function vbhosting_create_forum($userid, $forumtitle, $forumdescription='', $websitelogo='', $websiteurl='', $websitetitle='')
{
	global $DB_site, $vboptions, $vbphrase, $bbuserinfo;

	// Just some security things - no real checks are done here!
	$userid = intval($userid);
	$forumtitle = htmlspecialchars_uni(trim($forumtitle));
	$forumdescription = htmlspecialchars_uni(trim($forumdescription));
	$websitelogo = htmlspecialchars_uni(trim($websitelogo));
	$websiteurl = htmlspecialchars_uni(trim($websiteurl));
	$websitetitle = htmlspecialchars_uni(trim($websitetitle));

    // First of all, we need a hosted id
    $DB_site->query("INSERT INTO " . TABLE_PREFIX . "vbhosting_hosted (hostedid) VALUES (NULL)");
    $hostedid = $DB_site->insert_id();

	// Build a new style
	$styleid = vbhosting_create_style($hostedid, $forumtitle);
	if (!empty($websitelogo))
	{
		$DB_site->query("INSERT INTO " . TABLE_PREFIX . "template (styleid, title, template, templatetype, dateline) VALUES ($styleid, 'titleimage', '" . addslashes($websitelogo) . "', 'stylevar', " . TIMENOW . ")");
	}
	if (!empty($websiteurl))
	{
		$DB_site->query("INSERT INTO " . TABLE_PREFIX . "template (styleid, title, template, templatetype, dateline) VALUES ($styleid, '{hostedsiteurl}', '" . addslashes($websiteurl) . "', 'replacement', " . TIMENOW . ")");
	}
	if (!empty($websitetitle))
	{
		$DB_site->query("INSERT INTO " . TABLE_PREFIX . "template (styleid, title, template, templatetype, dateline) VALUES ($styleid, '{hostedsitename}', '" . addslashes($websitetitle) . "', 'replacement', " . TIMENOW . ")");
	}
	vbhosting_quiet_build_style($styleid, $styletitle, array('docss' => 1, 'dostylevars' => 1, 'doreplacements' => 1, 'doposteditor' => 1));

	// Create the boards
	if ($vboptions['vbhosting_create_category'])
	{
		$categoryid = vbhosting_create_board($vboptions['vbhosting_create_parentboard'], $styleid, $forumtitle, $forumdescription, true);
		$boardid = vbhosting_create_board($categoryid, $styleid, $vboptions['vbhosting_create_firstboard']);
	}
	else
	{
		$categoryid = vbhosting_create_board($vboptions['vbhosting_create_parentboard'], $styleid, $forumtitle, $forumdescription);
		$boardid = $categoryid;
	}
	build_forum_permissions();

	// Update hosting information
	$DB_site->query("UPDATE " . TABLE_PREFIX . "vbhosting_hosted SET creatorid=$userid, creationtime=" . TIMENOW . ", forumid=$categoryid, styleid=$styleid WHERE hostedid=$hostedid");

    // Create the welcome message
    if ($vboptions['vbhosting_create_welcomemessage'])
    {
    	// The poster normally isn't the one posting the welcome message here...
    	$originalbbuserinfo = $bbuserinfo;
    	$welcomeuserinfo = $DB_site->query_first("SELECT userid FROM " . TABLE_PREFIX . "user WHERE username='" . htmlspecialchars_uni($vboptions['vbhosting_create_welcomeposter']) . "'");
    	$bbuserinfo = fetch_userinfo(intval($welcomeuserinfo['userid']));
    	// Get the foruminfo array
    	$foruminfo = fetch_foruminfo($boardid);
    	// Get the post information
    	$newpost = array (
			'message' => $vbphrase['vbhosting_create_welcomemessage'],
			'title' => $vbphrase['vbhosting_create_welcomemessage_subject'],
			'iconid' => 0,
			'parseurl' => 1,
			'signature' => 1,
			'emailupdate' => 9999,
			'poststarttime' => TIME_NOW,
			'posthash' => md5(TIME_NOW . $bbuserinfo['userid'] . $bbuserinfo['salt']),
			'stickunstick' => 1
	    );
	    // If we post as guest...
	    if ($bbuserinfo['userid'] <= 0)
	    {
			$newpost['username'] = htmlspecialchars_uni($vboptions['vbhosting_create_welcomeposter']);
			$bbuserinfo['userid'] = 0;
			// Failover in case the options are not correctly set
			if (empty($newpost['username']))
			{
				$newpost['username'] = 'Guest';
			}
	    }
	    // Build the post
		build_new_post('thread', $foruminfo, array(), 0, $newpost, $errors);
		// Revert the userinfo
		$bbuserinfo = $originalbbuserinfo;
    }

	// Create the initial moderator
	// NOTE TO MYSELF: The permissions should be generated dynamically
	$DB_site->query("INSERT INTO " . TABLE_PREFIX . "moderator (userid, forumid, permissions) VALUES ($userid, $categoryid, 1049599)");

	// Create the initial administrator
	$DB_site->query("INSERT INTO " . TABLE_PREFIX . "vbhosting_administrator (hostedid, userid, permissions) VALUES ($hostedid, $userid, 15)");

    // Send the welcome mail to the new administrator
    $creatorinfo = $DB_site->query_first("SELECT username, email FROM " . TABLE_PREFIX . "user WHERE userid=$userid");
	vbmail($creatorinfo['email'], $vbphrase['vbhosting_create_mail_creatornotify_subject'], construct_phrase($vbphrase['vbhosting_create_mail_creatornotify_body'], unhtmlspecialchars($creatorinfo['username']), unhtmlspecialchars($forumtitle), $vboptions['bburl'] . '/' . $vboptions['vbhosting_admin_directory'] . '/', $vboptions['bburl'] . '/forumdisplay.php?f=' . $categoryid), true);

	// Return the forumid so we can use it in notification mails
	return $categoryid;
}

// ###################### Start build forum #######################
function vbhosting_create_board($parentid, $styleid, $title, $description = '', $iscategory = false)
{
	global $DB_site, $vboptions;

    	// Insert the new board
	$DB_site->query("INSERT INTO " . TABLE_PREFIX . "forum (forumid) VALUES (NULL)");
	$newforumid = $DB_site->insert_id();

	// Get the new options
	// NOTE TO MYSELF: The options should be generated dynamically
	$newoptions = 261831;
	if ($iscategory)
	{
		$newoptions = 261827;
	}

	// Insert the most important forum settings (using defaults)
	$parentlist = fetch_forum_parentlist($parentid);
    $DB_site->query("
		UPDATE " . TABLE_PREFIX . "forum SET
		title='" . addslashes($title) . "',
		description='" . addslashes($description) . "',
		styleid=$styleid,
		parentid=$parentid,
		parentlist='" . addslashes("$newforumid,$parentlist") . "',
		childlist='$forumid,-1',
		options=$newoptions,
		displayorder=1,
		daysprune=30
		WHERE forumid = $newforumid
	");

	return $newforumid;
}

// ###################### Start build forum #######################
function vbhosting_create_style($hostedid, $forumtitle)
{
	global $DB_site, $vboptions;

    // Not really for technical reasons, but for a better overview
    // in the style manager
    $styletitle = "Hosted forum #$hostedid ($forumtitle)";

	// Insert the new style
	$DB_site->query("INSERT INTO " . TABLE_PREFIX . "style (title, parentid, userselect, displayorder) VALUES ('" . addslashes($styletitle) . "', $vboptions[vbhosting_create_parentstyle], 0, 1)");
	$newstyleid = $DB_site->insert_id();

	build_style_datastore();
	build_template_parentlists();

    return $newstyleid;
}

// ###################### Start build forum #######################
function vbhosting_haspermission($permtype)
{
	global $_VBHOSTINGPERMISSIONS;
	
	if (!isset($_VBHOSTINGPERMISSIONS[$permtype]))
	{
		return false;
	}

	if (VBHOSTING_PERMISSIONS & $_VBHOSTINGPERMISSIONS[$permtype])
	{
		return true;
	}
	
	return false;
}

// ###################### Start print forum chooser #######################
// Print a nice forum chooser in case the user has more than one
function vbhosting_print_forumchooser()
{
	global $DB_site, $vboptions, $session, $bbuserinfo, $vbphrase, $_REQUEST;

	define('NO_PAGE_TITLE', true);
	
	$forumlist = $DB_site->query("SELECT f.title, h.hostedid FROM " . TABLE_PREFIX . "forum f, " . TABLE_PREFIX . "vbhosting_hosted h, " . TABLE_PREFIX . "vbhosting_administrator a WHERE a.userid=$bbuserinfo[userid] AND a.hostedid=h.hostedid AND f.forumid=h.forumid ORDER BY f.title");
	if (!$vboptions['vbhosting_admin_enabled'])
	{
		$title = $vbphrase['vbhosting_hostingcp_disabled'];
		$contenttable = '<table cellpadding="25" cellspacing="0" border="0" width="100%" class="logincontrols">
				<tr>
					<td><strong>' . $vboptions['vbhosting_admin_disabledreason'] . '</strong></td>
				</tr>
			</table>';
	}
	elseif ($DB_site->num_rows($forumlist) == 0)
	{
		$title = $vbphrase['vbhosting_you_dont_own_a_forum'];
		$contenttable = '<table cellpadding="25" cellspacing="0" border="0" width="100%" class="logincontrols">
				<tr>
					<td><strong>' . construct_phrase($vbphrase['vbhosting_you_dont_own_a_forum_details'], '../' . $vboptions[vbhosting_create_scriptname]) . '</strong></td>
				</tr>
			</table>';
	}
	else
	{
		$title = $vbphrase['vbhosting_please_coose_a_forum'];

		$forums = array();
		while($thisforum = $DB_site->fetch_array($forumlist))
		{
			$forums["$thisforum[hostedid]"] = $thisforum['title'];
		}
		
		$contenttable = '<table cellpadding="4" cellspacing="0" border="0" width="100%" class="logincontrols">
				<col width="50%" style="text-align:' . $stylevar['right'] . '; white-space:nowrap"></col>
				<col></col>
				<col width="50%"></col>
				<tr>
					<td>' . $vbphrase['forum'] . '</td>
					<td><select name="hostedid" class="login" style="padding-left:5px; font-weight:normal; width:250px" tabindex="1">' . construct_select_options($forums, '', 1) . '</select></td>
					<td>&nbsp;</td>
				</tr>
				<tr>
					<td colspan="3" align="center">
						<input type="submit" class="button" value="   ' . $vbphrase['log_in'] .   '   " accesskey="s" tabindex="2" />
					</td>
				</tr>
			</table>';
	}
	
	print_cp_header($title);
	
	echo '<p>&nbsp;</p><p>&nbsp;</p>
		<form action="' . 'index.php' . '" method="post">
			<input type="hidden" name="s" value="' . $session['dbsessionhash'] . '" />
			<input type="hidden" name="do" value="' . $_REQUEST['do'] . '" />
			<table class="tborder" cellpadding="0" cellspacing="0" border="0" width="450" align="center">
				<tr>
					<td>
						<div class="tcat" style="padding:4px; text-align:center"><b>' . $title . '</b></div>
						<table cellpadding="4" cellspacing="0" border="0" width="100%" class="navbody">
							<tr valign="bottom">
								<td><img src="../cpstyles/' . $vboptions['cpstylefolder'] . '/cp_logo.gif" alt="" title="' . $vbphrase['vbulletin_copyright'] . '" border="0" /></td>
								<td><b><a href="../' . $vboptions['forumhome'] . '.php">' . $vboptions['bbtitle'] . '</a></b><br />' . construct_phrase($vbphrase['vbhosting_vbhosting_x_control_panel'], $vboptions['vbhosting_version']) . '<br />&nbsp;</td>
							</tr>
						</table>
						' . $contenttable . '
					</td>
				</tr>
			</table>
		</form>';

	define('NO_CP_COPYRIGHT', true);
	unset($GLOBALS['DEVDEBUG']);
	print_cp_footer();
}

// ###################### Start log action #######################
function vbhosting_log($extrainfo='')
{
	global $DB_site, $bbuserinfo, $shutdownqueries;

	$userid = $bbuserinfo['userid'];
	$script = basename($_SERVER['PHP_SELF']);
	$scriptaction = $_REQUEST['do'];

	$DB_site->shutdown_query("INSERT INTO " . TABLE_PREFIX . "vbhosting_hostingcplog (userid, dateline, script, action, extrainfo, ipaddress) VALUES ($userid, " . TIMENOW.", '" . addslashes($script) . "', '" . addslashes($scriptaction) . "', '" . addslashes($extrainfo) ."', '$_SERVER[REMOTE_ADDR]')");
}

// ###################### Start do_update_style #######################
function vbhosting_quiet_build_style($styleid, $title = '', $actions, $parentlist = '', $indent = '')
{
	@ob_start();
	build_style($styleid, $title, $actions, $parentlist, $indent);
	@ob_end_clean();
}

// ###################### Start print_image_group #######################
function vbhosting_print_image_group($title, $filenames)
{
	global $vbphrase, $hostedid, $randomstring, $imagedir, $parentimagedir, $stylevar;
	
	print_form_header('image', 'updatebuttons', true);
	construct_hidden_code('hostedid', $hostedid);
	print_table_header($title, 4);
	
	print_column_style_code(array('width: 35%', 'width: 25%', 'width: 25%', 'width: 15%'));
	print_cells_row(array($vbphrase['filename'], $vbphrase['vbhosting_your_image'], $vbphrase['vbhosting_original_image'], $vbphrase['vbhosting_revert_image']), 1, 0, -3);
	
	if (!is_array($filenames))
	{
		$filenames = array($filenames);
	}
	
	for ($i = 0; $i < count($filenames); $i++)
	{
		$bgclass = fetch_row_bgclass();
		print_cells_row(array('<strong>' . $filenames[$i] . '</strong>', '<img src="../' . $imagedir . '/' . $filenames[$i] . '?random=' . $randomstring . '" alt="' . $filenames[$i] . '" border="0" />', '<img src="../' . $parentimagedir . '/' . $filenames[$i] . '?random=' . $randomstring . '" alt="' . $filenames[$i] . '" border="0" />', "<a href=\"image.php?{$session['sessionurl']}hostedid={$hostedid}&do=revert&image=" . $filenames[$i] . '">[' . $vbphrase['revert'] . ']</a>'), 0, 0, -3);
		echo '<tr valign="top" align="center">
			<td class="' . $bgclass . '" align="' . $stylevar['left'] . '">' . $vbphrase['vbhosting_upload_new_image'] . ':</td>
			<td class="' . $bgclass . '" align="' . $stylevar['left'] . '" colspan="3"><input type="file"' . iif(is_browser('opera'), '', ' class="bginput"') . ' name="' . str_replace('.', '_____', $filenames[$i]) . '" size="35" tabindex="1" /></td>
		</top>';
	}
	
	print_submit_row($vbphrase['upload'], '_default_', 5);
	print_table_footer();
}

?>