<?php

/*
 *	W-AGORA 4.0
 *	-----------
 *	$Id: create_forum.php,v 1.26 2003/12/03 15:06:29 mdruilhe Exp $
 *	Usage:	Create a new forum
 *	Author:	Marc Druilhe <mdruilhe@w-agora.net>
 *
 */

require ("init_admin.inc");

# Check is safe_mode On
# ---------------------
	$sf = get_cfg_var("safe_mode");

# Load site administration configuration
# --------------------------------------
require ("$site_cfg_file");	
require ("$bn_dir/$bn_fields");
if (empty($bn_msgs) ) {
	include ("$bn_dir_default/site_msgs.$ext");
} else {
	include "$bn_dir/$bn_msgs";
}

display_header (TITLE_CREATE_FORUM);

# --------------------------------------------------
# check if this user is authorized to create a forum
# --------------------------------------------------
if ($auth->level < ADMIN) {
	MsgForm (ERROR_NO_ADMIN, "admin_site.$ext?site=$site&force_login=1", "", "_top");
	echo "</body></html>";
	exit;
}

#  Creation form have been submitted => do installation
# -----------------------------------------------------
if (isset($do_install)) {
	unset($do_install);

#  Check required fields
# ----------------------
	while (list($field, $required) = each($bn_bind_var)) {
		if ($required && !$$field) {
			$mess = sprintf (ERROR_MISSING_FIELD, $field);
			MsgForm ($mess, "$WA_SELF", 'back');
			exit;
		}
	}

#  assume that forum name is a valid name for a DBMS table
# --------------------------------------------------------
	$bn_name = ereg_replace ("[^[:alnum:]]+", "", strip_magic_quotes(strtolower($bn_name)));
	$bn = $site . "_". $bn_name;
	// Check max size

	if (strlen ($bn) > ( (int)$bn_var_size["bn_name"])) {
		MsgForm (ERROR_FORUM_NAME_TO_LONG, "$WA_SELF", 'back');
		exit;
	}

#  Check if configuration file already exists
# -------------------------------------------
	$cfg_file = "${cfg_dir}/${bn}.${ext}";

	if (file_exists ("$cfg_file")) {
		MsgForm (sprintf(ERROR_CONFIG_FILE_EXISTS, $cfg_file), "$WA_SELF?site=$site", 'back');
		echo "</BODY>\n</HTML>";
		exit;
	}

#  initialize configuration values
# --------------------------------
	$bn_dir_forums = empty ($bn_dir_forums) ? "forums" : $bn_dir_forums;
	$bn_dir_default = empty ($bn_dir_default) ? "${bn_dir_forums}/${site}/default" : $bn_dir_default;
	$bn_dir="${bn_dir_forums}/${site}/$bn_name";
	$bn_dir_notes="$bn_dir/notes";
	$bn_db=$bn;
	$dbpassword = addslashes($dbpassword);	// preserve slashes 
	$dbname = addslashes($dbname);	// preserve slashes 
	
	if ($HTTP_POST_VARS['theme'] == 'DEFAULT') {
		$src_dir="$bn_dir_default";
	} else {
		$src_dir="$tmpl_dir/". $HTTP_POST_VARS['theme'];
	}

	$base_cfg_file = "$src_dir/conf.$ext";

	if (!is_file ("$base_cfg_file")) {
		MsgForm (ERROR_NO_CONFIG_FILE . " ($base_cfg_file)", "$WA_SELF?site=$site", 'back');
		echo "</BODY>\n</HTML>";
		exit;
	}

	include ("$base_cfg_file");

#  Create Configuration File
# --------------------------
	$conf = new Config;
	$ret = $conf->open("$cfg_file");
	if (!$ret) {
		MsgForm ( sprintf (ERROR_CREATE_FILE, $cfg_file) . ", " .  ERROR_NO_PERMISSIONS, "$WA_SELF?site=$site", 'back'); /* access problem */
		exit;
	}
	$conf->writeConfig();
	$conf->close ();

#  Create directories (forum and notes)
# ------------------------------------------
	if (! @is_dir ("$bn_dir")) {
		$ret = mkdir ("$bn_dir", _DIRMODE);
		if (!$ret) {
			$msgerr = str_replace("{DIRECTORY}",  $bn_dir, ERROR_CREATE_DIR) . " ";
			if ($sf) {
				$msgerr .= str_replace("{DIRECTORY}",  $bn_dir, ERROR_SAFE_MODE);
			} else {
				$msgerr .= ERROR_NO_PERMISSIONS;
			}
			unlink("$cfg_file");
			msgForm ($msgerr, "$WA_SELF", 'back');
			exit;
		}
		$bn_dir_created = TRUE;
	}

	if (! @is_dir ("$bn_dir_notes")) {
		$ret = mkdir ("$bn_dir_notes", _DIRMODE);
		if (!$ret) {
			$msgerr = str_replace("{DIRECTORY}",  $bn_dir_notes, ERROR_CREATE_DIR) . " ";
			if ($sf) {
				$msgerr .= str_replace("{DIRECTORY}",  $bn_dir_notes, ERROR_SAFE_MODE);
				if ($bn_dir_created) {
					$ret = @rmdir("$bn_dir");
				}
			} else {
				$msgerr .= ERROR_NO_PERMISSIONS;
			}
			unlink("$cfg_file");
			msgForm ($msgerr, "$WA_SELF", 'back');
			exit;
		}
	}

#  Copy all template files to the new forum directory
#  --------------------------------------------------
	$dest_dir=$bn_dir;

	$files = array ( $bn_header, $bn_footer, $bn_msgs, $bn_form, $bn_search_form, $bn_login_form, $bn_register_form, $bn_change_form, $bn_forgot_form, $bn_fields, $bn_list_vars, $bn_template, $bn_before_access, $bn_style, $bn_mail_template, $bn_style);

	reset ($files);
	while (list(,$file) = each ($files) ) {
		if (!empty ($file) ) {
			$ret = Copy ("$src_dir/$file", "$dest_dir/$file");
			if (!$ret) {
				/* Unable to copy files */
				unlink("$cfg_file");
				MsgForm (sprintf(ERROR_NO_FILE_COPY,$file), "$WA_SELF?site=$site", 'back');
				exit;
			}
		}
	}

#  Create DBMS table or DBM files
# --------------------------------

	/* create forum table */
	if (!empty($bn_fields) && file_exists ("$bn_dir/$bn_fields") ) {
		$descr_file = "$bn_dir/$bn_fields";
	} else {
		$descr_file = "$bn_dir_default/fields.$ext";
	}

	$ret = $db->createForum ($bn_db, $descr_file);
	if ($ret == -1) {
		if ($bn_access == "dbm")
			MsgForm (sprintf(ERROR_FORUM_DB_DBM_EXISTS,$bn_db,$dbname,$bn_db), "$WA_SELF?site=$site", 'back');
		else
			MsgForm (sprintf(ERROR_FORUM_DB_EXISTS, $bn_db,$dbname), "$WA_SELF?site=$site", 'back');
		unlink("$cfg_file");
		exit;
	}
	elseif ($ret == -3) {
		if ($bn_access == "dbm")
			MsgForm (sprintf(ERROR_FORUM_DB_DBM_ACCESS, "dbm/$dbname/$bn_db"), "$WA_SELF?site=$site", 'back');
		else
			MsgForm (sprintf(ERROR_FORUM_DB_ACCESS, $bn_db, $dbname), "$WA_SELF?site=$site", 'back');
		unlink("$cfg_file");
		exit;
	} elseif ($ret < 0) {
		MsgForm (ERROR_NO_CREATE_FORUM . $bn_db, "$WA_SELF?site=$site", 'back');
		unlink("$cfg_file");
		exit;
	}

		
#  initialize search configuration file
#  -----------------------------------------------
	if (!empty($bn_search_engine) && ($bn_search_engine != "none")) {
		include "$inc_dir/$bn_search_engine.$ext";
		$search->initSearchConf();
	}

	
# Now Insert entry for this forum in the main table
#  -----------------------------------------------
	
	/* restore administration config */
	include ("$site_cfg_file");
	require ("$bn_dir/$bn_fields");

	$state = "1";	// active
	$moderated = (isset($moderated)) ? 1 : 0;
	$totalnotes = 0;
	$lastnote = $now;
	
	/* variables handled by w-agora */
	for (reset ($bn_var); $field=current($bn_var); next($bn_var)) {
		$$field=strip_magic_quotes($$field);
		$fields[$field]=$$field;
	}
	$fields["bn_name"]=$bn;
	$fields["bn_db"]=$bn;
	$fields["parent"]=$parent;

	$ret = $db->insertForum ($site, $fields);

	if ($ret < 0) {
		MsgForm (sprintf(ERROR_NO_FORUM_INSERT, $bn,$site), "$WA_SELF?site=$site&key=$key", 'back');
		$db->deleteForum ($site, $bn_db);
		unlink("$cfg_file");
		exit;
	}

# If moderator has been choosen, then set moderator privileges
# for this forum in the userforum table (if user is a moderator)
# --------------------------------------------------------------
	include "$tmpl_dir/admin/userforum_fields.$ext";

	if (!empty ($owner)) {
		$u = $db->getUser($site, $owner);
		if (is_array($u) && ($u["userpriv"] == "moder") ) {
			$uf_fields["unixdate"]   = $now;
			$uf_fields["userid"]     = $owner;
			$uf_fields["bn_name"]    = $bn;
			// moderator can read, write, list
			$uf_fields["listpriv"]   = 1;
			$uf_fields["readpriv"]   = 1;
			$uf_fields["writepriv"]  = 1;
			$uf_fields["modpriv"]    = 1;
			$uf_fields["state"]      = 1;
			$uf_fields["lastpost"]   = 0;
			$ret = $db->insertPrivs ($site, $bn, $owner, $uf_fields);
			if ($ret < 0) {
				MsgForm (sprintf(ERROR_NO_ADD_PRIVILEGES, $owner,$forum_name), "$WA_SELF?site=$site&key=$key", 'back');
				exit;
			}
		}
	}

# Display success message then exit
# ---------------------------------
	$success_msg = "<BR><BR><BLOCKQUOTE><font face='Arial, Geneva, Verdana, sans-serif' size='+1'><b>" . sprintf(LABEL_FORUM_CREATED, $bn_name,  $site) . "</b> <ul>";
	$success_msg .= "<li> " . anchor ("create_forum.$ext?site=$site", "", LABEL_CREATE_ANOTHER_FORUM, LABEL_CREATE_ANOTHER_FORUM);
	$success_msg .= "<li> " . anchor ("$main_page?bn=$bn", "_top", LABEL_ACCESS_THIS_FORUM, ALT_ACCESS_FORUM);
	$success_msg .= "<li> " . anchor ("admin_forum.$ext?site=$site&bn=$bn", "_top", LABEL_ADMINISTRATE_FORUM, ALT_ADMINISTRATE_FORUM);
	$success_msg .= "<li> " . anchor ("edit_forum.$ext?site=$site&bn=$bn", "", LABEL_EDIT_THIS_FORUM, ALT_EDIT_THIS_FORUM);
	$success_msg .= "<li> " . anchor ("admin.$ext?site=$site", "_top", LABEL_SITE_ADMINISTRATION, LABEL_SITE_ADMINISTRATION);
	$success_msg .= "</ul></font></BLOCKQUOTE><BR><BR>";

	table_header(sprintf(LABEL_FORUM_CREATED_SUCCESSFULLY, $bn_name));
	print ("$success_msg");
	table_footer();
	echo "</BODY>\n</HTML>";
	exit;
} // End $do_install

# Initialize default values then display FORM
# -------------------------------------------
	$bn_name = (isset($bn_name)) ? $bn_name : "";
	$key = (isset($key)) ? $key : "";
	$descr = (isset($descr)) ? $descr : "";
	$theme = (isset($HTTP_POST_VARS['theme'])) ? $HTTP_POST_VARS['theme'] : "DEFAULT";
	$rank = (isset($rank)) ? $rank : 1;

	$parent = (isset($parent)) ? $parent : "";
	$categories = $db->getCategories($site);

?>

<SCRIPT type="text/javascript" LANGUAGE="JavaScript">
<!-- // Hide for old browsers
  function CheckForm(form) {
<?
	/* Check for required fields */
	while (is_array($bn_bind_var) && list($field, $required) = each($bn_bind_var)) {
		if ($required) {
?>
    if ((form.<?echo $field?>.value != null) && (form.<?echo $field?>.value.length == 0)) {
      alert ("<?php printf (ERROR_MISSING_FIELD, $field)?>");
      form.<?echo $field?>.focus();
      return false;
    }
<?
		}
	}
?>
    return true;
  }
// End of script -->
 </SCRIPT>
<FORM NAME="form_post" METHOD="post" ACTION="<?echo $WA_SELF?>" onSubmit="return CheckForm(this);" >

<INPUT TYPE="hidden" NAME="site" VALUE="<?echo $site?>">
<INPUT TYPE="hidden" NAME="do_install" VALUE="1">
<INPUT TYPE="hidden" NAME="key" VALUE="<?echo $key?>">

<?table_header(LABEL_INSTALL_FORUM . "'$site'"); ?>
 <TABLE BORDER="0" WIDTH="100%">
  <CAPTION><B><?echo LABEL_FORUM_INFORMATION ?></B></CAPTION>
  <TR>
   <TD WIDTH="40%" ALIGN="RIGHT" VALIGN="MIDDLE" class=label><?echo COLUMN_GIVE_FORUM_NAME ?> </TD>
   <TD>
    <?textField ("bn_name", $bn_name, 30, (int)$bn_var_size["bn_name"] - strlen($site) - 1);?>
   </TD>
  </TR>
  <TR>
   <TD WIDTH="40%" ALIGN="RIGHT" VALIGN="MIDDLE" class=label><?echo COLUMN_FORUM_TITLE ?></TD>

   <TD><?textField ("bn_title", $bn_title, 30, 255);?></TD>
  </TR>
  <TR>
   <TD WIDTH="40%" ALIGN="RIGHT" VALIGN="TOP" class=label><?echo COLUMN_DESCRIPTION ?> </TD>
   <TD><?textArea ("descr", $descr, 3, 30);?></TD>
  </TR>
  <TR>
   <TD WIDTH="40%" ALIGN="RIGHT" VALIGN="MIDDLE" class=label><?echo COLUMN_FORUM_TEMPLATE ?> </TD>
   <TD>
<?
#	Grab all directories in templates/
	$dir = dir("$tmpl_dir");
	$theme_dirs["DEFAULT"] = "DEFAULT (Site Default template)";
	while ($entry=$dir->read() ) {
		if ( is_dir("$tmpl_dir/$entry") && ($entry != ".") && ($entry != "..") && ($entry != "CVS") && ($entry != "default") && ($entry != "admin") ) {
			$desc="";
			if (file_exists ("$tmpl_dir/$entry/toc.$ext")) {
				include "$tmpl_dir/$entry/toc.$ext";
			}
			$theme_dirs[$entry] = (empty($desc)) ? $entry : $desc;
		}
	}
	$dir->close();
	listBox("theme", $theme_dirs, $theme);
?>
   </TD>
  </TR>
<? if (is_array($categories) ) { ?>
  <TR>
   <TD WIDTH="40%" ALIGN="RIGHT" VALIGN="TOP" class=label><?echo COLUMN_CATEGORY ?> :</TD>
   <TD><?listBox ("parent", $categories, $parent);?></TD>
  </TR>
<? } ?>
  <TR>
   <TD WIDTH="40%" ALIGN="RIGHT" VALIGN="TOP" class=label><?echo COLUMN_ORDER ?> :</TD>
   <TD class=label><?textField ("rank", $rank, 3);?></TD>
  </TR>
 </TABLE>
 <BR>
 <TABLE BORDER="0" CELLPADDING="2" WIDTH="100%">
  <CAPTION><B><?echo LABEL_PRIVACY_INFORMATION ?></B></CAPTION>
  <TR>
   <TD ALIGN="RIGHT" class=label><? echo LABEL_SET_ACCESS ?> :</TD>
   <TD><?listBox ("type", $forum_types, $type); ?></TD>
   <TD ALIGN="RIGHT"><?checkBox ("moderated", 1, $moderated); ?></TD>
   <TD class=label><?echo LABEL_MODERATED ?></TD>
  </TR>
<?
	$users = $db->getUsers ($site, "", "moder,admin,root");
	if (is_array($users)) {
		echo "<TR><TD ALIGN='RIGHT' colspan=2 class=label>" . LABEL_CHOOSE_FIRST_MODERATOR . "</TD>";
		echo "<TD colspan=2><SELECT NAME='owner'>\n";
##		echo "<option value=''> -- choose later -- </option>";
		reset($users);
		while (list(,$user) = each ($users) ) {
    		printf (" <option value='%s'>%s</option>\n", $user['userid'], $user['username']);
		}
		echo "</SELECT></TD></TR>";
	}

	if ($sf) {
?>
		<TR><TD COLSPAN=2><center><br><br>
		<font color=red><?echo LABEL_NOTICE ?> :</font> <strong><?echo NOTICE_SAFEMODE ?></strong></center>
		<?echo NOTICE_MANUAL_INSTALL ?>
		<ul>
		<li> <?echo "${bn_dir_forums}/${site}/forum"?> <? LABEL_NAME_OF_FORUM ?>
		<li> <?echo "${bn_dir_forums}/${site}/forum/notes"?> 
		</ul>
		</TD></TR>
<?
	}

	echo "</table>";
	echo "<br><center>";
	submitButton ("create", LABEL_CREATE_THIS_FORUM);
	resetButton ("reset", LABEL_RESET);
	echo "</center>";
	table_footer();
?>
</FORM>
</BODY>
</HTML>
