<?php

/*
 *	W-AGORA 4.0
 *	-----------
 *	$Id: form.php,v 1.71 2006/01/19 21:29:17 mdruilhe Exp $
 *	Usage:		display the FORM to the user
 *	Author:	Marc Druilhe <mdruilhe@w-agora.com>
 *
 */

if (!defined("_GLOBALS")) die("hacking attempt");

if ($use_html_editor && !empty($html_editor) && file_exists("include/$html_editor.$ext") ) {
	require_once "$inc_dir/$html_editor.$ext";
} elseif ($use_htmlarea && file_exists("include/htmlarea.$ext")) {
	// backward compatibility 
	$use_html_editor = true;
	$html_editor = "htmlarea";
	require_once "$inc_dir/htmlarea.$ext";
}


# Disable file upload if file upload not available in PHP configuration
# ---------------------------------------------------------------------
$file_uploads = (function_exists('ini_get')) ? ini_get('file_uploads') : get_cfg_var('file_uploads');
if (!$file_uploads) {
	$bn_file_upload = 0;
}

function preserveHtmlBox () {
	global $html_tags, $use_html_editor, $bn_allow_html, $bn_html_var;

	$checkbox = getCheckBox ("html_tags", 1, $html_tags, LABEL_PRESERVE_HTML_TAGS );
	$hiddenfield = getHiddenField ("html_tags", 1);

	if (empty($bn_allow_html) ) {
		return "";
	} elseif ($use_html_editor) {
		// htmlarea is used => lets the browser play according to its configuration
		$html = '<SCRIPT type="text/javascript" language="JavaScript">'. "\n". '  <!-- // Hide for old browsers' . "\n";
		$html .= "if (_use_html_editor) {document.write ('$hiddenfield')} else {document.write ('$checkbox')}";
		$html .= '  // End of script -->' . "\n" . '</script>';
		$html .= "<noscript>$checkbox</noscript>";
		return $html;
	} elseif (@is_array($bn_html_var)) {
		return $checkbox;
	} else {
		return "";
	}
}

# output JavaScript functions
# ----------------------------
?>
<SCRIPT type="text/javascript" language="JavaScript">
 <!-- // Hide for old browsers
var has_submitted = 0;

if (document.images){
	imgcopy=new Image;
	imgcopy.src="images/filecopy.gif";
}

function checkForm() {
	
//	alert("checkform");
  var f = document.form0;

  if (typeof(editorSubmit) == 'function') {
    editorSubmit(f);
  }

<?php
	if (is_array($bn_bind_var) ) {
		reset ($bn_bind_var);
		while (list($field, $required) = each($bn_bind_var)) {
			if ($required) {
				printf ("  if ((f.%s) && (f.%s.value.length == 0)) {\n", $field, $field);
				$alert = sprintf (ERROR_MISSING_FIELD, $field);
				print ("    alert (\"$alert\");\n");
				print ("    try { f.$field.focus() } catch(e){ try {editorFocus('$field')} catch(e){} };\n");
				print ("    return false;\n  }\n");
			}
		}
	}
?>

  if ( f.img_upload) {
    if (f.pcfile.value=='') {
      f.img_upload.src = 'images/none.gif';
    } else {
      f.img_upload.src = 'images/filecopy.gif';
    }
  }

  if(has_submitted == 0) {
    sel=false;
    for (i = 0; i < f.elements.length; i++) {
      if ( (f.elements[i].name == 'del_att[]')&&(f.elements[i].checked) ){
        sel = true;
        break;
      }
    }
	if (sel) {
      if (window.confirm("<?php echo CONFIRM_DEL_FILE?>") ) {
        has_submitted = 1;
        setTimeout('has_submitted=0', 5000);
        return true;
	  } else {
        return false;	      
	  }
	} else {
      has_submitted = 1;
      setTimeout('has_submitted=0', 5000);
      return true;
	}
  } else {
    alert("<?php echo ERROR_ALREADY_SUBMITED?>");
    return false;
  }
}

function uniqueSubmit(f) {
  if(has_submitted == 0) {
    has_submitted = 1;
    setTimeout('has_submitted=0', 5000);
    if ( f.img_upload) {
      if (f.pcfile.value=='') {
        f.img_upload.src = 'images/none.gif';
      } else {
        f.img_upload.src = 'images/filecopy.gif';
      }
    }
 	if (typeof(editorSubmit) == 'function') {
      editorSubmit(f);
	}
    f.submit();
	return true;
  } else {
    alert("<?php echo ERROR_ALREADY_SUBMITED?>");
    return false;
  }
	
} // end func

function uploadFile(f) {
  if(f.pcfile.value.length>0) {
    f.actiontype.value='upload';
    uniqueSubmit(f);
  } else {
    f.actiontype.value='';
    alert ("<?php echo ERROR_SELECT_FILE?>");
	f.pcfile.focus();
  }
}

function deleteFile(f) {
  sel=false;
  for (i = 0; i < f.elements.length; i++) {
    if ( (f.elements[i].name == 'del_att[]')&&(f.elements[i].checked) ){
      sel = true;
      break;
    }
  }

  if (sel == false) {
    f.actiontype.value='';
    alert("<?php echo ERROR_SELECT_DEL_FILE?>");
    return false;
  } else {
    if (window.confirm("<?php echo CONFIRM_DEL_FILE?>") ) {
      f.actiontype.value='delete';
      uniqueSubmit(f);
      return true;
	} else {
      return false;
	}
  }
}

function copyFile(f) {
  if(f.server_file.value && f.server_file.value.length>0) {
    f.actiontype.value='copy';
    uniqueSubmit(f);
  } else {
    f.actiontype.value='';
    alert ("<?php echo ERROR_SELECT_FILE?>");
	f.server_file.focus();
  }
}

function confirmSendFile(f) {
  if (window.confirm("<?php echo CONFIRM_SEND_FILE?>") ) {
    uploadFile(f);
  }
}

function quoteText (elem, text) {
  var quotedText = text.value;
  if (typeof(editorQuoteText) == 'function') {
    editorQuoteText('body', quotedText);
  } else {
	quotedText = quotedText.replace(/<\w[^>]*>/g, '');
	if (elem.value.length > 0) {
      elem.value += "\n"; 
    }
    elem.value += quotedText;
    elem.value += "\n"; 
 }
 return true;
}

function nl2br (txt) {
  return txt.replace(/\r\n/g, '<br />').replace(/\n/g, '<br />').replace(/\r/g, '<br />');
}

function br2nl (txt) {
  return txt.replace(/<br[^>]*[\/]?>/gi, '\n');
}


function resetForm (f) {
  if (typeof(editorReset) == 'function') {
    editorReset(f);
  }
}

// End of script -->
</SCRIPT>

<?php

# set defaults for user options
# -----------------------------
	$html_tags = (isSet($html_tags)) ? $html_tags : $default_html_tags;
	$mail_reply = (isSet($mail_reply)) ? $mail_reply : $default_mail_reply;
	$mail_update=(isSet($mail_update))?$mail_update : $default_mail_update;
	

# Set user's name & address either from user database (if registered/private forum)
# or from cookies

	// first we unset $password which can only be set via cookie, in preview mode: don't reset it
	if (!isSet($_POST['password']) ) {
		$password = "";	
	}

	if ($setUserField) {

		// first: unset user infos (name, address) which can be set either via cookie or authentication
		$username = "";
		$useraddress = "";

		// set all "cookie stored" variables (!! password can be set here !!)
		if (isset($cookies) && is_array($cookies->p_cookies)) {
			reset ($cookies->p_cookies);
			while (list($var, $val) = each ($cookies->p_cookies) ) {
				$$var = $val;
			}
		}

		// then, override user infos (name, address) if the user is authenticated
		if ($is_authenticated) {
			$username = $auth->user["username"];
			$useraddress = $auth->user["useraddress"];
		}
	}

# set some default values
# -----------------------
	if (empty($icon) ) {
		$icon = "icon1.gif";
	}

# Set icon list box
# -----------------
	$pics = array (
		"icon1.gif", 
		"icon2.gif", 
		"icon3.gif", 
		"icon4.gif", 
		"icon5.gif", 
		"icon6.gif", 
		"icon7.gif", 
		"icon8.gif", 
		"icon9.gif", 
		"icon10.gif", 
		"icon11.gif",
		"icon12.gif",
		"icon13.gif",
		"icon14.gif"
	);

	$icon_list = ''; $n = 0;
	reset($pics);
	while (list($i,$pic) = each($pics) ) {
		$icon_list .= getRadioButton ('icon', $pic, $icon, "&nbsp;&nbsp;<img src=\"$icon_dir/$pic\" height=\"15\" width=\"15\" border=\"0\" align=\"abscenter\" alt=\"$pic\">&nbsp;") ."&nbsp;&nbsp;&nbsp;";
		if ((($i+1)%7)==0) {
		    $icon_list .= '<br />';
		}
	}

# ------------------------------------------------------------
# Display form 
# ------------------------------------------------------------	
	print ("<a name=\"FORM\"></a>");
	printf ("<form method=\"post\" action=\"%s\" %s name=\"form0\" onSubmit=\"return checkForm();\">\n",
		$form_action,
		($bn_file_upload==1) ? " enctype=\"multipart/form-data\" " : "");
	hiddenField ("site", $site);
	hiddenField ("bn", $bn);
	hiddenField ("do_post", "1");
	hiddenField ("back_form", $back_form);
	hiddenField ("popup", $popup);
	hiddenField ("no_thanks_msg", $no_thanks_msg);
	hiddenField ("lynx", $lynx);
	hiddenField ("MAX_FILE_SIZE", $MAX_FILE_SIZE);
	hiddenField ("filename", $filename);
	hiddenField ("actiontype", "");

	if (isset($key)) {
		hiddenField ("key", $key);
	}

	if (isset($attkey)) {
		hiddenField ("attkey", $attkey);
	}
	if (isset($redirect_url)) {
	    hiddenField ("redirect_url", $redirect_url);
	}
	if (isset($thread) ) {
		hiddenField ("thread", $thread);
	} elseif (is_array($note)&& isset($note["thread"])) {
		hiddenField ("thread", $note["thread"]);
	}

	if (!$bn_file_upload) {
		hiddenField ("pcfile", "");
	}

	if (!$bn_browse_server) {
		hiddenField ("server_file", "");
	}

# Set input field variables ($input_username, $input_useraddress)
# ---------------------------------------------------------------
	$label_username = LABEL_ENTER_USERNAME;
	$label_useraddress = LABEL_ENTER_EMAIL;
	$label_short_description = LABEL_SHORT_DESCRIPTION;
	$label_comments = LABEL_COMMENTS;
	if ($is_authenticated && !$is_moderator) {
		$input_username = $username;
		$input_useraddress = $useraddress;
	} else {
		$input_username = "<INPUT NAME=\"username\" VALUE=\"$username\" SIZE=16 class=\"wa_textfield\" />";
		$input_useraddress = "<INPUT NAME=\"useraddress\" VALUE=\"$useraddress\" SIZE=16 class=\"wa_textfield\" />";
	}

	$label_subject = LABEL_ENTER_SUBJECT;
	$label_body = LABEL_ENTER_TEXT;
	$label_icon = LABEL_SELECT_ICON;

# Smiley help url
# ---------------
	$label_smileys_help = LABEL_SMILEYS_HELP;
	if (file_exists("help/$lang/smilies.htm") ) {
		$smileys_help_url = "help/$lang/smilies.htm";
	} else {
		$smileys_help_url = "help/en/smilies.htm";
	}

# Set title variable
# ------------------
	if (empty($form_title)) {
	    if ($bn_action == "reply") {
			$form_title = TITLE_REPLY_FORM;
		} elseif ($bn_action == "edit") {
			$form_title = TITLE_EDIT_FORM;
		} else {
			$form_title = TITLE_POST_FORM;
		}	
	}
	

# Initialize url field
# --------------------
	if (empty($url)) {
		$url='http://';
	}

# Set QUOTE TEXT button variable
# ------------------------------
	if (empty($quoted_text)) {
		$quote_button = "";
	} else {
		hiddenField ("quoted_text", $quoted_text);
		$quote_button = getButton ('', BUTTON_QUOTE, 'quoteText(this.form.body, this.form.quoted_text);');	
	}

# Create list of possible inline modes
# ----------------------------------
	$inline_list['1'] = LABEL_YES;
	$inline_list['0'] = LABEL_NO;

# Set Attachment table
# --------------------
	$display_att = false;
	// retrieving the temporary note's key 
	if (!empty($attkey)) {
		$nkey = $attkey;
	} elseif ($bn_action=="edit") {
		$nkey = $key;
	} else {
		$nkey = '';
	}

	if ($nkey != '') {
		$tsz = 0;
		$att = $db->getAttachments ($bn_db, $nkey);
		if (is_array($att)) {
			$att_count = count($att);
			$display_att = true;
			$att_table = '<table border=0 width="100%" class="att_table"><tr class="att_table_header"><td size=0>&nbsp;</td><td>'. COLUMN_ATTACHMENTS. '</td><td>'. COLUMN_TYPE. '</td><td>'. COLUMN_SIZE.'</td><td>'. COLUMN_INLINE. "</td></tr>\n";
			for ($i=0; $i<$att_count; $i++) {
				$id = $att[$i]['att_id'];
				$tsz += $att[$i]['att_size'];
				$sz = pretty_size($att[$i]['att_size']);
				if (getAttDisplayMode ($att[$i]['att_type'], 'A') == ATT_DSP_LINK) {
					// This mime-type can't be displayed inline
					hiddenField("inline_att[$id]", "0");
				    $inline_box = '--';
				} else {
				    $inline_box = getListBox ("inline_att[$id]", $inline_list, $att[$i]["inline"] );
				}
				$att_table .= '<tr class="att_table_row"><td>'.  getCheckBox ('del_att[]', $id, 0, ""). '</td><td>'. $att[$i]['att_name'] . '</td><td>'.  $att[$i]['att_type']. '</td><td>'. $sz. '</td><td>'.$inline_box."</td></tr>\n";
			}
			$total_sz = pretty_size($tsz);
			$att_table.= '<tr class="att_table_row"><td colspan="2" align="left">'.
				'<img src="images/arrow.gif" width="38" height="22" border="0" alt="" align="absmiddle">'.
			    '<a href="'."$form_action?bn=$bn&actiontype=delete".'" onclick="deleteFile(document.form0); return false;">'. LABEL_DELETE_FILES. '</a></td><td align="right"><b>Total: </b></td><td align="center"><b>' .$total_sz. '</b></td><td></td></tr></table>';
		}
	}

# Set "FILE UPLOAD" Button
# ------------------------
	if ($bn_file_upload) {
		$display_att = true;
		$file_upload_text = LABEL_ATTACH_LOCAL_FILE;
		$file_upload_field = '<INPUT TYPE="file" NAME="pcfile" width="260" SIZE="30" onChange="confirmSendFile(this.form);" />';
		$file_upload_button = getButton ('', BUTTON_UPLOAD, 'uploadFile(this.form);');
		$att_upload_table = '<table border="0" width="100%" cellpadding="0">'.
			"<tr class=\"att_table_row\"><td align=\"left\">$file_upload_text &nbsp;$file_upload_field &nbsp; $file_upload_button</td></tr></table>";
	} else {
		$file_upload_button = "";
		$file_upload_text = "";
		$file_upload_field = "";
		$att_upload_table = "";
	}

# Set "BROWSE SERVER" Button
# --------------------------
	if ($bn_browse_server) {
		$display_att = true;
		$browse_server_text = sprintf(LABEL_ATTACH_SERVER_FILE, $SERVER_NAME);
		$browse_server_field = getTextField ('server_file', '', 30);
		$browse_server_field .= getButton ('', BUTTON_BROWSE, "OpenWindow(\"browse.$ext?bn=$bn\",'winbrowse',500,400);return false;" );
		$browse_server_button = getButton ('', BUTTON_COPY, 'copyFile(this.form);');
		$att_browse_table = '<table border="0" width="100%" cellpadding="0">'.
			"<tr class=\"att_table_row\"><td align=\"left\">$browse_server_text $browse_server_field $browse_server_button</td></tr></table>";
	} else {
		$browse_server_button = "";
		$browse_server_text = "";
		$browse_server_field = "";
	}

# Options
# -------
	$label_options = LABEL_OPTIONS;

# Set "RECEIVE MAIL " checkbox
# ----------------------------
	$mail_reply_box = ($bn_user_mail==1 && $bn_thread==1) ? getCheckBox ("mail_reply", 1, $mail_reply, LABEL_NOTIFY_ON_REPLY) : "";
	$mail_update_box = ($bn_user_mail==1 && $bn_action=="edit") ? getCheckBox ("mail_update", 1, $mail_update, LABEL_EMAIL_UPDATED_NOTE) : "";
# Set "Preserve HTML" checkbox
# ----------------------------
    $preserve_html_box = preserveHtmlBox();

# Set the "Password" field according to forum rules, user and context
# -------------------------------------------------------------------
	if (!isset($ask_password) ) {
		// should be set in edit/update
		$ask_password = (($forum["type"] == "pub") && !$is_authenticated && ($bn_modify || $bn_delete) ) ? true : false;
	}

	if ($ask_password) {
		$password_text = LABEL_USER_PASSWORD;
		$password_field = "<input type=\"password\" NAME=\"password\" VALUE=\"$password\" SIZE=16 class=\"wa_textfield\" />";
	} else {
		$password_text = "";
		$password_field = "";
	}


# Set "SUBMIT", "PREVIEW", "RESET" and "CANCEL" buttons
# -----------------------------------------------------
	$preview_button = getSubmitButton('preview', BUTTON_PREVIEW);
	$submit_button = getSubmitButton('insert', BUTTON_SUBMIT);
	// $reset_button = getButton ('reset', BUTTON_RESET, 'resetForm(document.form0);');
	$reset_button = '<input type="reset" name="reset" value="'.BUTTON_RESET.'" onClick="resetForm(this.form);" />';

	if ($bn_popup && $popup) {
		$cancel_button = getButton ('cancel', BUTTON_CANCEL, ($bn_popup==1) ? 'window.close();' : 'history.back();');
	} else {
		$cancel_button = "";
	}

# Create final attachment handling table
# --------------------------------------
	if ($display_att) {
 		$att_form = '<table width="100%" border=0><tr class="att_table_row"><td colspan=2 align=center><hr noshade></td></tr><tr class="att_table_row"><td class="att_form_title"><b>'.TITLE_ATTACHMENTS.'</b></td><td align=center><img src="images/none.gif" width="260" height="30" border=0 name="img_upload"></td></tr><tr class="att_table_row"><td colspan=2 align=center>'.
			$att_table.$att_upload_table.$att_browse_table;
		$att_form .= '</td></tr><tr class="att_table_row"><td colspan=2 align=center><hr noshade></td></tr></table>';
	}

# Set the button bar 
# ------------------
	$button_bar = '<table width="90%" border=0><tr><td>';
	if (!empty($quote_button)) {
		$button_bar .= "<br/>$quote_button";
	}

	if (!empty($att_form)) {
		$button_bar .= "<br/> $att_form";
	}

	if (!empty($mail_reply_box)) {
		$button_bar .= "<br/> $mail_reply_box";
	}
	
	if (!empty($mail_update_box)) {
		$button_bar .= "<br/> $mail_update_box";
	}
	if (!empty($preserve_html_box)) {
		$button_bar .= "<br/> $preserve_html_box";
	}

	if (!empty($password_field)) {
		$button_bar .= "<br/> $password_text $password_field";
	}
	$button_bar .= "</td></tr></table>\n";
	$button_bar .= "<p style=\"text-align:center\">$preview_button $submit_button $reset_button $cancel_button</p>";

# Include user (or default) form
# ------------------------------
	if (empty($bn_form)) {
		include ("$bn_dir_default/form.$ext");
	} else {
		include "$bn_dir/$bn_form";
	}

# Displays the "OPTIONS" button bar :
# -----------------------------------
	if (!$bn_no_form_button_bar) {
		print $button_bar;
	}
	echo "</form>";
?>

	<script type="text/javascript" language="JavaScript1.2" defer="1">
	 <!-- // Hide for old browsers
	 var editor = null;
<?php if ($use_htmlarea) { ?>
	 document.form0.body.value = nl2br(document.form0.body.value);
     editor = new HTMLArea(document.form0.body, myConfig);
     if (editor) {
	   editor.generate();
     } else {
      _use_html_editor = false;
      document.form0.body.value = br2nl(document.form0.body.value);
     }
<?php } ?>	 
	 // End of script -->
	</script>
