<?

	#---------------------------------------------------------------------#
	# This source code is (c)2000 Dave Belfer-Shevett - shevett@pobox.com #
	# see http://www.stonekeep.com/license.html for licensing information #
	#---------------------------------------------------------------------#

	#----------------------------------------------------------------------
	# $Id: utils.php3,v 1.66 2000/12/19 15:27:40 shevett Exp $
	#----------------------------------------------------------------------
	
	# Contains the normal function library used all over the place.

	#----------------------------------------------------------------------
	# Message tools.
	#		dumps out text to the inside frame of the main screen.  Table
	#		formatting and all.

	Function Message($whattosay) {
		OpenMessage();
		echo "<h2>";
		echo "$whattosay";
		echo "</h2>";
		CloseMessage();
	}

	Function OpenMessage() {
		echo "<tr><td>&nbsp;</td></tr>";
		echo "<tr><td>&nbsp;</td><td align=center fgcolor=\"#FFFFFF\" bgcolor=\"#A0A0A0\">";
		echo "<font color=#ffffff>";
	}

	Function CloseMessage() {
		echo "</td><td>&nbsp</td></tr>";
	}

	Function Dialog() {
		OpenMessage();
		echo "Moo!<br><font size=2> Are you sure?</font>";
		CloseMessage();
	}

	#----------------------------------------------------------------------
	# Framing tools
	
	Function FrameTop() {
		Global $curruser, $sys_version, $sys_graphics, $sys_server,$state,$sys_col;
		$zslip=0;
		if (is_array($state)) {
			$zslip = $state[slipzoom];
		} 
		echo "<table width=\"100%\" cellspacing=0 cellpadding=0 border=0>\n";
		echo "<tr bgcolor=\"$sys_col[bordbg]\">\n";
		echo "<td colspan=2>";
		echo "<table width=\"100%\" cellspacing=0 cellpadding=0 border=0>\n";
		echo "<td width=\"50%\">\n";
		echo "<font size=2 color=\"$sys_col[bordfg]\">\n";
		echo "Keystone $sys_version &copy;2000 WhitePajamas, Inc.";
		echo "</td>\n";
		if (! ("$curruser" == "visitor")) {
			echo "<form action=\"nbrowse.php3\">\n";
			echo "<td width=\"50%\" align=right nowrap>\n";
			echo "<font size=2 color=\"$sys_col[bordfg]\">QuickSlip: \n";
			echo "<select name=\"f_slipzoom\" ONCHANGE=\"form.submit(this)\">\n";
			$qstring = "select "
				. "members.id,members.element,slips.sid,slips.problem "
				. "from slips,members " ;
			if ($sys_server == "postgresql") {
				$qstring .= "where int4(members.element) = slips.sid AND ";
			} else {
				$qstring .= "where members.element = slips.sid AND ";
			}
			$qstring .= "members.id = 'quickslips' order by slips.sid";
			$qsq = db_query("$qstring");
			if (db_numrows($qsq)) {
				echo "<option value=\"0\">None selected\n";
				while ($qsqdata = db_fetch_array($qsq)) {
					$sel = ($qsqdata[sid] == $state[slipzoom]) ? "selected" : "";
					# LogIt("DEBUG","FrameTop()","sel for $qsqdata[sid] (compared to $state[slipzoom]) is $sel");
					echo "<option value=\"$qsqdata[sid]\" $sel>";
					echo "$qsqdata[sid] - $qsqdata[problem]\n";
				}
			} else {
				echo "<option value=\"0\">No quickslips defined.\n";
			}
			echo "</select>\n";
			echo "<input type=image src=\"$sys_graphics/circle.gif\" border=0 alt=\"\">\n";
			echo "</td>\n";
			echo "</form>\n";
		} else {
			echo "<td align=right>&nbsp;</td>\n";
		}
		echo "</tr></table>";
		echo "</td></tr>";
#		echo "<table width=\"100%\" cellspacing=0 cellpadding=0 border=0>\n";
	}
	
	Function FrameFoot() {
		Global $lastresult, $curruser, $sys_col;
		echo "<tr bgcolor=\"$sys_col[bordbg]\">";
		echo "<td colspan=2>";
		echo "<table width=\"100%\">";
		echo "<tr bgcolor=\"$sys_col[bordbg]\">";
		echo "<td align=left>";
		echo "<font size=2 color=\"$sys_col[bordfg]\">Last Result: ";
		if (IsSet($lastresult)) {
			echo "<font size=2 color=\"$sys_col[bordmsg]\">$lastresult[1]";
		}
		echo "</td>";
		echo "<td align=right>";
		echo "<font size=2 color=\"$sys_col[bordfg]\">[Logged in as $curruser]";
		echo "</td>";
		echo "</tr>";
		echo "</table>";
		echo "</td>";
		echo "</tr>";
	}

	#----------------------------------------------------------------------
	# some misc db stuff.

	Function LoadStatus() {
		Global $stnames;
		
		$sth = db_query("select * from status order by flag");
		while ($strow = db_fetch_array($sth)) {
			$stnames[$strow[flag]] = "$strow[label]";
		}
	}
	
	Function RecalcSlip($whichslip) {
		if ($whichslip > 0) {
			# how many children do I have?
			$ch_dbh = db_query("select sid from slips where spid=$whichslip");
			$chcount = db_numrows($ch_dbh);
		
			# how many followups do I have?
			$fo_dbh = db_query("select f_sid from followups where f_sid=$whichslip");
			$focount = db_numrows($fo_dbh);
		
			$chupd = db_query("update slips set num_children=$chcount where sid=$whichslip");
			$foupd = db_query("update slips set num_follows=$focount where sid=$whichslip");
		}
	}
		
	#----------------------------------------------------------------------
	# funstuff

	Function ShowPolicies() {
		Global $currow;
		$ph = db_query("select * from policy");
		while ($prow = db_fetch_array($ph)) {
#			echo "<option value=\"$prow[pid]\"> $prow[pid] - $prow[fullname]\n";
			$sel = ($currow[spolicy] == $prow[pid]) ? "selected" : "" ;
			echo "<option value=\"$prow[pid]\" $sel > $prow[pid] - $prow[fullname]\n";
		}
	}

	Function Send_Mail($to,$subject,$message) {
		Global $sys_m_from, $sys_f_from, $sys_website;
		$footer	=		"---------------------------------------------------------------------------\n";
		$footer .=	"This message was generated automatically by Keystone at $sys_website\n";
		mail("$to", "$subject", "$message\n$footer","From: $sys_f_from\nPrecedence: bulk");
	}

	Function Member($user,$group) {
		$mq = db_query("select * from members where element='$user' and id='$group'");
		if (db_numrows($mq)) {
			return 1;
		} else {
			return 0;
		}
	}

	Function LogIt($type,$module,$message) {
		Global $sys_logfile,$sys_datefmt,$curruser,$sys_loginfo,$sys_logdebug,$sys_logerr,$REMOTE_HOST;

		# 'type' is INFO, ERR, DEBUG, 
		# 'module' is the function or file that generated the call
		# 'message' is, well, the message. duh.

		if ((("$type"=="INFO") AND ($sys_loginfo)) OR (("$type"=="ERR") AND ($sys_logerr)) OR (("$type"=="DEBUG") AND ($sys_logdebug))) {
			$now=time();
			$dstring = "[".date("$sys_datefmt",$now) . "]$curruser@$REMOTE_HOST";
			$ostring = sprintf("%-40s",$dstring);
			error_log("$ostring:$type:$module:$message\n",3,"$sys_logfile");
		}
	}

	Function PostBar($buttontext) {
		Global $sys_selfont;
		echo "<table width=100% bgcolor=#808080 cellpadding=2 cellspacing=1 border=0>\n";
		echo "<tr>\n";
		echo "<td width=33% align=center>\n";
		# FIXME: needs maxsize based on database query
		echo "<font size=$sys_selfont><input type=reset value=\"Reset\"></font>\n";
		echo "</td>\n";
		echo "<td width=33% align=center bgcolor=#202020>\n";
		echo "<font color=#cccccc>";
		echo "<font size=$sys_selfont><input type=submit value=\"$buttontext\"></font>\n";
		echo "</td>\n";
		echo "<td width=33% align=center>";
		echo "<font size=$sys_selfont><input type=submit name=f_cancel value=\"Cancel\"></font>";
		echo "</td>";
		echo "</tr>\n";
		echo "</table>\n";
		echo "</form>";
	}

	Function ShowStatusBar($whatsid) {
		Global $sys_col;
		echo "<table width=100% bgcolor=$sys_col[detailbg] cellspacing=2 border=0>\n";
		echo "<tr bgcolor=$sys_col[detailbg] valign=top>\n";
		$fq = db_query("select * from slips where sid=$whatsid");
		$finfo = db_fetch_array($fq);
		echo "<td bgcolor=$sys_col[detailbg]>";
		echo "<font fgcolor=$sys_col[detailfg]><i>Slip number</i><br><b>$finfo[sid]</b></td>";
		echo "<td bgcolor=$sys_col[detailbg]>";
		echo "<font fgcolor=$sys_col[detailfg]><i>Problem</i><br><b>".stripslashes(htmlspecialchars($finfo[problem]))."</b></td>";
		echo "<td bgcolor=$sys_col[detailbg]>";
		echo "<font fgcolor=$sys_col[detailfg]><i>Open Tech</i><br><b>$finfo[o_tech]</b></td>";
		echo "<td bgcolor=$sys_col[detailbg]>";
		echo "<font fgcolor=$sys_col[detailfg]><i>Contact</i><br><b>$finfo[ctag]</b></td>";
		echo "<td bgcolor=$sys_col[detailbg]>";
		echo "<font fgcolor=$sys_col[detailfg]><i>Current tech</i><br><b>$finfo[currtech]</b></td>";
		echo "</tr>";
		echo "</table>";
	}

	Function MailOptions() {
		Global $prefs,$sys_justrecent,$sys_selfont;
		echo "<i>Send email update to...</i><br>";
		$sel = ($prefs[opt_mopen]) ? "checked" : "";
		echo "<input type=checkbox name=m_open value=Y $sel>Opened by<br>\n";	
		$sel = ($prefs[opt_mcontact]) ? "checked" : "";
		echo "<input type=checkbox name=m_contact value=Y $sel>Contact Email<br>\n";
		$sel = ($prefs[opt_mtech]) ? "checked" : "";
		echo "<input type=checkbox name=m_currtech value=Y $sel>Current tech<p>\n";
		echo "<i>Or type in an address...</i><Br>";
		echo "<font size=$sys_selfont><input type=text name=m_other size=25 value=$prefs[opt_mother]></font><p>";
		$vstring = ($sys_justrecent) ? "value=\"Y\"" : "";
		echo "<input type=checkbox name=m_justlast $vstring>Send only most recent followup?";
	}

	Function CalcHighSeq($whatsid) {
		$ck = db_query("select f_seq from followups where f_sid=$whatsid") ;
		$highseq = 0;
		if (db_numrows($ck)) {
			while ($rows = db_fetch_array($ck)) {
				if ($rows[f_seq] > $highseq) {
					$highseq = $rows[f_seq];
				}
			}
		}
		return $highseq;
	}
	
	Function ShowExtras ($table,$edata) {
		$squery=db_query("select * from eschema where etable='$table' order by element asc, esequence asc");
		$pending = 0;
		while ($pending || ($s = db_fetch_array($squery))) {
			$pending = 0;
			if (strchr($s[eflags],"O")) {
				echo "<i>$s[elabel]</i><br>";
				$element = $s[element];
				$numselected = $edata[$element];
				echo "<select name=\"a_$s[element]\">\n";
				echo "<option value=0>None\n";
				$count=0;
				while (($s = db_fetch_array($squery)) && ($s[element] == $element)) {
					++$count;
					echo  "<option value=$s[esequence] ";
					if ($count == $numselected) {
						echo "selected";
					}
					echo ">$s[elabel]\n";
					$pending=1;
				}
				echo "</select><br>\n";
				if (!$s) {
					break;
				}
			} else {
				echo "<i>$s[elabel]</i><br>";
				# FIXME: needs maxsize based on database query
		 		echo "<input name=\"a_$s[element]\" ";
				$element = $s[element] ;
				echo "size=$s[elength]";
				if (IsSet($edata[$element])) {
					echo "value=\"$edata[$element]\"";
				}
				echo "> <br>";
			}
		}
	}

	# This is used only by slips and followups.  The value so $sid is
	# either the slip ID or the followup slip ID.
	Function InsertExtras ($table,$keyref) {
		$counter = 0;
		$eflist = db_query("select distinct element, etype from eschema where etable='$table'");
		while ($eres = db_fetch_array($eflist)) {
			$varname="a_${eres[element]}";
			global $$varname;
			eval("\$val=\"\$$varname\";");
#			if (Is_String($keyref)) {
			if (Is_String($keyref) && (strcmp(strval(intval($keyref)),$keyref) != 0)) { 

				LogIt("DEBUG","utils.php3","query=insert into ebulk (btable,belement,bvalue,bkeyref) values ('$table','$eres[element]','$val','$keyref')");
				$r=db_query("insert into ebulk (btable,belement,bvalue,bkeyref) values ('$table','$eres[element]','$val','$keyref')");

			} else {
				LogIt("DEBUG","utils.php3","query=insert into ebulk (btable,belement,bvalue,browref) values ('$table','$eres[element]','$val',$browref)");
#				$r=db_query("insert into ebulk (btable,belement,bvalue,browref) values ('$table','$eres[element]','$val',$browref)");
				$r=db_query("insert into ebulk (btable,belement,bvalue,browref) values ('$table','$eres[element]','$val','$keyref')");
			}
			$counter++;
		}
		return $counter;
	}

	#--------------------------------------------------------
	# These two functions are used for prompting for dates
	# within Keystone.;  The first shows the date in various
	#	pulldown menus... the second takes that entry after a post
	#	operation and turns it back into a Unix datestamp.

	Function PromptDate($vname,$default) {
		# Year Month Day Hour Minute
		LogIt("DEBUG","promptdate","Variable name is $vname, default value is $default");
		$defmonth = date("M",$default);
		LogIt("DEBUG","promptdate","Month name of default is $defmonth");
		echo "<select name=${vname}_month>\n";
		$sel = ($defmonth=='Jan') ? "selected" : "";
		echo "<option value=1 $sel>Jan\n";
		$sel = ($defmonth=='Feb') ? "selected" : "";
		echo "<option value=2 $sel>Feb\n";
		$sel = ($defmonth=='Mar') ? "selected" : "";
		echo "<option value=3 $sel>Mar\n";
		$sel = ($defmonth=='Apr') ? "selected" : "";
		echo "<option value=4 $sel>Apr\n";
		$sel = ($defmonth=='May') ? "selected" : "";
		echo "<option value=5 $sel>May\n";
		$sel = ($defmonth=='Jun') ? "selected" : "";
		echo "<option value=6 $sel>Jun\n";
		$sel = ($defmonth=='Jul') ? "selected" : "";
		echo "<option value=7 $sel>Jul\n";
		$sel = ($defmonth=='Aug') ? "selected" : "";
		echo "<option value=8 $sel>Aug\n";
		$sel = ($defmonth=='Sep') ? "selected" : "";
		echo "<option value=9 $sel>Sep\n";
		$sel = ($defmonth=='Oct') ? "selected" : "";
		echo "<option value=10 $sel>Oct\n";
		$sel = ($defmonth=='Nov') ? "selected" : "";
		echo "<option value=11 $sel>Nov\n";
		$sel = ($defmonth=='Dec') ? "selected" : "";
		echo "<option value=12 $sel>Dec\n";
		echo "</select>";
		echo "<select name=${vname}_day>\n";
		for ($i=1;$i<=31;$i++) {
			$sel = ($i==date("d",$default)) ? "selected" : "";
			echo "<option value=$i $sel>$i\n";
		}
		echo "</select>";
		echo "<select name=${vname}_year>\n";
		LogIt("DEBUG","promptdate","Year tag for default is " . date("Y",$default));
		for ($i=1969;$i<=2005;$i++) {
			$sel = ($i==date("Y",$default)) ? "selected" : "";
			echo "<option value=$i $sel>$i\n";
		}
		echo "</select>";
		echo "<select name=${vname}_hour>\n";
		for ($i=0;$i<=23;$i++) {
			$sel = ($i==date("H",$default)) ? "selected" : "";
			echo "<option value=$i $sel>$i\n";
		}
		echo "</select>";
		echo ": <select name=${vname}_minute\n";
		for ($i=-15;$i<50;$i+=15) {
			$sel = ($i==date("i",$default)) ? "selected" : "";
			echo "<option value=$i $sel>$i\n";
		}
		echo "</select>";
	}

	Function InterpretDate($mi,$hr,$da,$mo,$yr) {
		$retval = mktime($hr,$mi,0,$mo,$da,$yr);
		return $retval;
	}

	#----------------------------------------------------------------------

	Function GenOrder($currscreen) {
		Global $prefs;

		#
		# Figure out what the 'order' clause should be for the current
		# slip view.
		#

		if ($prefs[opt_prisort]) {
			$otxt = "order by $prefs[opt_prisort]";
			if ($prefs[opt_pridesc]) {
				$otxt = "$otxt desc";
			}
			if ($prefs[opt_secsort]) {
				$otxt = "$otxt,$prefs[opt_secsort]";
				if ($prefs[opt_secdesc]) {
					$otxt = "$otxt desc";
				}
			}
		} else {
			if ($currscreen == 'contacts') {
				$otxt = 'order by tag';
			} elseif ($currscreen == 'slips') {
				$otxt = '';
			}
		}
		return $otxt;
	}

	Function CheckEmpty($field, $replacement) {

		if (empty($field)) {
			return $replacement;
		} else {
			return $field;
		}
	}

	
