<?php
/* daCode http://www.dacode.org/
 * src/phplib/poll.php3
 * $Id: poll.php3,v 1.60 2001/07/12 09:48:15 penso Exp $
 *
 * This class will handle the poll system
 *
 * Depends: Config Db Utils Html
*/

Class Poll {
	var $db,$session,$cache,$html,$utils;

	Function Poll() {
//echo '<br>Poll';
		$this->db = LoadClass('Db');
		$this->session = LoadClass('Session');
		$this->cache = LoadClass('Cache');
		$this->html  = LoadClass('Html');
		$this->utils = LoadClass('Utils');
	}

	Function submit_new($table) {
		global $config;

		if (is_array($table)) {
			return $this->add_poll($table);
		}

		$out  = "<p>\n".
			lecho("This form allow to submit a poll").
			lecho(" which, if accepted, will be proposed").
			lecho(" to this website visitors.")."</p>\n".
			"<hr><p>\n".
			lecho("<b>Question</b> must be provided.")."<br>".
			lecho("<b>Comments</b> is 255 caracters maximum.").".<br>".
			lecho("At least 2 <b>Answers</B> must be provided.")."</[><hr>";

		$out .= "<form method=\"post\" action=\"".
				$config->basehref.$config->pollsubmitfile."\">".
			"<table>\n".
			" <tr>\n".
			" <td>".lecho("Question")."</td>\n".
			" <td colspan=\"2\"><input type=\"text\" name=\"table[question]\" size=\"30\" maxlength=\"40\"></td>\n".
			" <td><b>".lecho("Necessary")."</b></td>\n".
			" </tr>\n".
			" <tr>\n".
			" <td>".lecho("Comment")."</td>\n".
			" <td><textarea name=\"table[comment]\" cols=\"60\" rows=\"5\"></textarea></td>\n".
			" </tr>\n";

		for($i=1; $i<=10; $i++) {
			$out .= "<tr>\n".
				"<td>".lecho("Answer")." $i</td>\n".
				"<td colspan=\"2\"><input type=\"text\" name=\"table[answer$i]\" size=\"30\" maxlength=\"40\"></td>";
			if($i <= 2) {
				$out .= "<td><b>".lecho("Necessary")."</b></td>\n";
			}
			$out .= "</tr>\n";
		}
		$out .= "<tr>\n".
			"<td colspan=\"3\" align=\"center\"><input type=\"submit\" name=\"submit\" value=\"".lecho("Add")."\"><input type=\"reset\" value=\"".lecho("Cancel")."\"></td>\n".
			"</tr>".
			"</table>";
		return $out;
	}

	/*
	 * Insert submitted values into the poll spool
	 */

	Function add_poll($table) {
		global $config;

		if (strlen($table['question'])>40 || strlen($table['comment'])>255) {
			return lecho("Question or comment too long.");
		}

		if (strlen($table['answer1'])==0 || strlen($table['answer2'])==0) {
			return lecho("Provide at least two different answers.");
		}
		if (strlen($table['question'])==0) {
			return lecho("A question would help :-)");
		}
		$date = date("U");
		$sqlc_q = "INSERT INTO ".$config->tables['poll_questions'].
			" (question,comment,date,accept) VALUES('".
			addslashes($table['question'])."','".
			addslashes($table['comment'])."','".
			addslashes($date)."','0')";
		$ret = $this->db->query($sqlc_q);
		$id = $this->db->last_insert_id();
		if (!$ret) {
			$out .= lecho("SQL Failed: "). $this->db->error();
			return $out;
		}

		$count=1;
		while (strlen($table["answer$count"])>0) {
			$answer = $table["answer$count"];
			$sqlc_q = "INSERT INTO ".$config->tables['poll_answers'].
				" (question_id,answer,number,question_number) VALUES('".
				addslashes($id)."','".
				addslashes($answer)."','0','".
				addslashes($count)."')";
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				$out .= lecho("SQL Failed: "). $this->db->error();
				return $out;
			}
			$count++;
		}

		$out =  lecho("Your poll has been correctly recorded and will be processed").
			lecho(" by one of the moderators")."<br>".
			lecho("If approved, it will be displayed on our website.");
		return $this->html->sidebox(lecho("Thanks"), $out);
	}

	Function show_poll() {
		global $config;

		$fcontents = $this->cache->check_box("3600","show_poll", $config->ext);
		if (!empty($fcontents)) {
			return $fcontents;
		}

		$content = "";

		$sqlc_q = "SELECT id,question,comment FROM ".
			$config->tables['poll_questions']." WHERE accept='2' ORDER BY id DESC LIMIT 1";
		$ret=$this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed: \n$sqlc_q\n -->\n";
		}

		if ($this->db->num_rows() == 0) {
			$this->db->free();
			$content .= "<br><center><a href=\"".
				$config->basehref.$config->pollsubmitfile.
				"\">".lecho("Submit a poll")."</a></center>";

			$out = $this->html->sidebox("<a href=\"".$config->basehref.
				$config->pollindexfile.
				"\">".lecho("Poll")."</a>", $content);
			$this->cache->write_box("show_poll",$config->ext,$out);
			return $out;
		}

		$row = $this->db->fetch_array();
		$row['question'] = stripslashes($row['question']);
		$row['comment'] = stripslashes($row['comment']);
		$row['id'] = stripslashes($row['id']);
		$content .= "\n<center>".$row['question'];
		$content .= "<br>".$row['comment']."</center>\n";

		$content .= "<form action=\"".$config->basehref.
			$config->pollindexfile."\" method=\"post\">\n";
		$content .= "<input type=\"hidden\" value=\"".$row['id']."\" name=\"id\">\n";

		$sqlc_q = "SELECT answer FROM ".$config->tables['poll_answers'].
			" WHERE question_id='".addslashes($row['id'])."' ORDER BY question_number";
		$ret=$this->db->query($sqlc_q);

		if(!$ret) {
			return "<!-- Poll: SQL Request Failed: \n$sqlc_q\n -->\n";
		}

		if ($this->db->num_rows() != 0) {
			while($row=$this->db->fetch_array()) {
				$row['answer'] = $this->utils->htmlspecial(stripslashes($row['answer']));
				$content .= "<input type=\"radio\" value=\"".$row['answer'].
						"\" name=\"answer\"> ".$row['answer']."<BR>\n";
			}
		} else {
			$content .= "<!-- Poll table looks wrong ... -->\n";
		}

		$content .= "<center><input type=\"submit\" value=\"".lecho("Confirm")."\"></center>\n";
		$content .= "</form>";

		$content .= "<br><center><a href=\"".
					$config->basehref.
					$config->pollsubmitfile.
					"\">".lecho("Submit a poll")."</a></center>";
		$out = $this->html->sidebox("<a href=\"".$config->basehref.
							$config->pollindexfile.
							"\">".
							lecho("Poll")."</a>", $content);
		$this->cache->write_box("show_poll",$config->ext,$out);
		return $out;
	}

	Function update_poll($answer,$id) {
		global $config;

		$date = date("U");
		$ip = $this->utils->ip();
		$sqlc_q = "SELECT ip,date from ".$config->tables['poll_ip'].
			" WHERE ip='".addslashes($ip)."'";
		$ret=$this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed -->";
		}
		$row = $this->db->fetch_array();
		if(isset($row['ip']) && $row['date'] > $date - $config->pollvote ) {
			$time =  $config->pollvote/3600;
			$return =  lecho("You must wait ").$time.lecho(" hours between two votes");
			return $return;
			exit;
		}
		$sqlc_q = "UPDATE ".$config->tables['poll_answers'].
			" SET number = number + 1 WHERE answer='".addslashes($answer).
			"' AND question_id='".addslashes($id)."'";
		$ret=$this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed -->";
		}
		if (isset($row['date']) && $row['date'] < $date - $config->pollvote) {
			$sqlc_q = "UPDATE ".$config->tables['poll_ip'].
				" SET date='".addslashes($date).
				"' WHERE ip='".addslashes($ip)."'";
		} else {
			$sqlc_q = "INSERT INTO ".$config->tables['poll_ip']." (ip,date) VALUES ('".
				addslashes($ip)."','".
				addslashes($date)."')";
		}
		$ret=$this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed -->";
		}
		return "<!-- Poll has been updated. -->\n";
	}

	Function show_results($id = "-1") {
		global $config;

		$content = '';
		if ($id == "-1") {
			$sqlc_q = "SELECT id,question,comment FROM ".
				$config->tables['poll_questions'].
				" WHERE accept='2' ORDER BY id DESC LIMIT 1";
			$ret=$this->db->query($sqlc_q);
			if(!$ret) {
				return "<!-- Poll: SQL Request Failed: \n$sqlc_q\n -->\n";
			}
			$row = $this->db->fetch_array();
			$id = $row['id'];
		}
		$sqlc_q = "SELECT ".$config->tables['poll_questions'].".question, ".
			"sum(".$config->tables['poll_answers'].".number) FROM ".
			$config->tables['poll_questions'].", ".
			$config->tables['poll_answers'].
			" WHERE ".$config->tables['poll_answers'].".question_id='".
			addslashes($id)."' AND ".$config->tables['poll_questions'].".id=".
			$config->tables['poll_answers'].".question_id".
			" GROUP BY ".$config->tables['poll_answers'].".question_id";
		$ret = $this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed: -->\n";
			exit;
		}
		$result = $this->db->fetch_array();
		$question = $result['question'];
		$tot = $result["sum(poll_answers.number)"];
		$sqlc_q = "SELECT answer,number FROM ".$config->tables['poll_answers'].
			" WHERE question_id='".addslashes($id)."'";
		$ret=$this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed: $sqlc_q -->\n";
			exit;
		}
		$content .= lecho("Poll Results").":<BR>\n";
		$content .= "<center><b>$question</b>\n";
		$content .= "<table>";
		while($row=$this->db->fetch_array()) {
			$row['answer'] = stripslashes($row['answer']);
			if ($tot != 0) {
				$width=500*$row['number']/$tot;
			} else {
				$width=0;
			}
			$width=round($width);
			if ($tot != 0) {
				$percent=100*$row['number']/$tot;
			} else {
				$percent=0;
			}
			$percent=round($percent);
			$content .= "<tr>\n<td class=\"newstext\">\n";
			if($row['number']){
				$content .= "<img src=\"".$this->session->imgurl('leftbar','png')."\" height=\"20\" alt=\"\">";
			}
			$content .= "<img src=\"".$this->session->imgurl('mainbar','png')."\"".
						" height=\"20\" width=\"$width\" ".
						"alt=\"$percent%\">";
			if($row['number']) {
				$content .= "<img src=\"".$this->session->imgurl('rightbar','png')."\" height=\"20\" alt=\"\">";
			}
			$content .= "</td><td class=\"newstext\">".$row['answer']." ".$row['number']."/".$percent."%</td></tr>\n";
		}
		$content .= "</table>\n";
		$content .= "<br>".lecho("Total").": ".$tot."\n";
		$content .= "</center>\n";
		$content = $this->html->simplebox($content);
		return $content;
	}

	Function poll_to_moderate() {
		global $config;

		$content = "";
		$sqlc_q = "SELECT id,question FROM ".
			$config->tables['poll_questions'].
			" WHERE accept='0' ORDER BY id";
		$ret=$this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed: \n$sqlc_q\n -->\n";
		}
		while ($row = $this->db->fetch_array()) {
			$row['question'] = stripslashes($row['question']);
			$row['id'] = stripslashes($row['id']);
			$content .= "&nbsp;-&nbsp;[POLL]&nbsp;<a href=\"".
						$config->basehref.
						$config->adminfile.
						"?action=list_polls&amp;id=".$row['id']."\">".$row['question']."</a><br>\n";
		}
		return $content;
	}

	Function edit_poll($id) {
		global $config;

		$content = "";

		$sqlc_q = "SELECT question,comment,accept FROM
			".$config->tables['poll_questions']." WHERE id='".addslashes($id)."'";
		$ret=$this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed: \n$sqlc_q\n -->\n";
		}

		$row = $this->db->fetch_array();
		$row['question'] = stripslashes($row['question']);
		$row['comment'] = stripslashes($row['comment']);
		$content .= "\n<center>".$row['question'];
		$content .= "<br>".$row['comment']."</center>\n";

		$sqlc_q = "SELECT answer FROM ".$config->tables['poll_answers']."
			WHERE question_id='".addslashes($id)."' ORDER BY question_number";
		$ret=$this->db->query($sqlc_q);

		if(!$ret) {
			return "<!-- Poll: SQL Request Failed: \n$sqlc_q\n -->\n";
		}

		while($answer=$this->db->fetch_array()) {
			$content .= stripslashes($answer['answer'])."<br>\n";
		}

		$content .= "<form action=\"".$config->basehref.$config->adminfile.
				$config->polladminfile."\" method=\"get\">\n";
		$content .= "<input type=\"hidden\" value=\"$id\" name=\"id\">\n";
		$content .= "<center><select name=\"status\">";
		$status = array(lecho("Wait"),lecho("Accept"),lecho("Current"),lecho("Previous"),lecho("Delete"));
		for($accept=0; $accept<=4; $accept++) {
			$content .= "<option value=\"$accept\"";
			if ($accept == $row['accept']) {
				$content .= " selected";
			}
			$content .= ">".$status[$accept];
		}
		$content .= "</select>";
		$content .= "<input type=\"submit\" value=\"".lecho("Confirm")."\"></center>\n";
		$content .= "</form>";

		return $content;
	}

	Function list_polls() {
		global $config,$HTTP_GET_VARS;

		$id = $HTTP_GET_VARS['id'];
		if ($id) {
			return $this->edit_poll($id);
		}
		$sqlc_q = "SELECT id,question,accept FROM ".
			$config->tables['poll_questions']." ORDER BY accept DESC";
		$ret=$this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed: \n$sqlc_q\n -->\n";
		}

		$content = '';
		$content .= "<table border=\"0\">";
		if ($this->db->num_rows() != 0) {
			$prev = -1;
			$poll_text = array(lecho("Polls to moderate"),
				lecho("Accepted polls"),lecho("Current poll"),
				lecho("Previous polls"));
			while ($row=$this->db->fetch_array()) {
				$content .= "<tr>";
				if ($row['accept'] != $prev) {
					$prev = $row['accept'];
					$content .= "<th>".$poll_text[$row['accept']]."</th>";
					$content .= "</tr>\n<tr>";
				}
				$content .= "<td><a href=\"".$config->basehref.
					$config->adminfile."?action=list_polls&amp;id=".$row['id']."\">".
					$row['question']."</a></td></tr>\n";
			}
		} else {
			$content .= "<!-- Poll table looks wrong ... -->\n";
		}
		$content .= "</table>";

		$out = $this->html->sidebox("<a href=\"".$config->basehref.
						$config->pollindexfile."\">".
						lecho("Poll")."</a>", $content);
		return $out;
	}

	Function mod_poll($id,$status=0) {
		global $config;

		if (!$this->session->is_admin) {
			echo lecho("you bad boy...");
			exit;
		}

		if($status == 2) {
			//   Mark current pool as obsolete
			$sqlc_q = "UPDATE ".$config->tables['poll_questions'].
				" SET accept='3' WHERE accept='2'";
			$ret=$this->db->query($sqlc_q);
			if(!$ret) {
				return "<!-- Poll: SQL Request Failed --><BR>".$sqlc_q;
			}

			// We delete all the IP which already voted
			$sqlc_q = "DELETE FROM ".$config->tables['poll_ip'];
			$ret=$this->db->query($sqlc_q);
			if(!$ret) {
				return "<!-- Poll: SQL Request Failed --><BR>".$sqlc_q;
			}

			if (!empty($config->htmldir)) {
				$this->cache->delete_htmlfiles('section',0,0,0);
				$this->cache->delete_htmlfiles('topic',0,0,0);
				$this->cache->delete_htmlfiles('.',1,0,0,'^index,');
			}
			if (!empty($config->cachedir)) {
				$this->cache->delete_boxfiles('show_poll',0,0,0,'^#');
			}
		}
		$sqlc_q= "UPDATE ".$config->tables['poll_questions']." SET accept='".
			addslashes($status)."' WHERE id='".addslashes($id)."'";
		$ret=$this->db->query($sqlc_q);
		if(!$ret) {
			return "<!-- Poll: SQL Request Failed --><BR>".$sqlc_q;
		}
		if($status == 4) {
			$sqlc_q = "DELETE from ".$config->tables['poll_questions'].
				" WHERE id='".addslashes($id)."'";
			$ret=$this->db->query($sqlc_q);
			if(!$ret) {
				return "<!-- Poll: SQL Request Failed --><BR>".$sqlc_q;
			}
			$sqlc_q = "DELETE from ".$config->tables['poll_answers'].
				" WHERE question_id='".addslashes($id)."'";
			$ret=$this->db->query($sqlc_q);
			if(!$ret) {
				return "<!-- Poll: SQL Request Failed --><BR>".$sqlc_q;
			}
		}
	}

}

?>
