Logo Search packages:      
Sourcecode: dacode version File versions  Download package

poll.php3

<?php
/**
 * This class will handle the poll system
 *
 * daCode http://www.dacode.org/
 * src/phplib/poll.php3
 * $Id: poll.php3,v 1.74.2.8 2002/06/04 20:58:50 ruffy Exp $
 *
 * Depends: Config Db Utils Html
 */

Class Poll {

      /**
       * Db abstraction layer
       *@var object Db
       */
      var $db;

      /**
       * Session instance
       *@var object Session
       */
      var $session;

      /**
       * Cache abstraction layer
       *@var object Cache
       */
      var $cache;

      /**
       * HTML rendering package (subclass of HTML)
       *@var object HTML
       */
      var $html;

      /**
       * Utils package
       *@var object Utils
       */
      var $utils;

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

      /**
       * Handles submission of a new poll
       * If table is an array, calls add_poll and returns; else prints the html form.
       *@param mixed $table array resulting of form submission
       *@param string width of comments textarea
       *@return string the HTML form or "Thanks sidebox.
       *@see Poll::add_poll()
       *@access public
       */
      Function submit_new($table,$widthcomment="60") {
            global $config;

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

            $out  = "<p>\n".
                  lecho("This form allow to submit a poll which, if accepted, will be proposed 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.")."</p><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("Mandatory")."</b></td>\n".
                  " </tr>\n".
                  " <tr>\n".
                  " <td>".lecho("Comment")."</td>\n".
                  " <td><textarea name=\"table[comment]\" cols=\"".$widthcomment."\" ".
                  "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("Mandatory")."</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("Erase")."\" /></td>\n".
                  "</tr>".
                  "</table></form>";
            return $out;
      }

      /**
       * Insert submitted values into the poll spool
       *@param array the table, resulting submit_new form submission
       *@return string thanks message
       *@access private
       */

      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 ").
                  lecho("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);
      }


      /**
       * Shows a poll with form to vote
       *@return string the sidebox with the form.
       *@access public
       */
      Function show_poll() {
            global $config;

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

            $content = "";

            $sqlc_q = "SELECT id,question,comment FROM ".
                  $config->tables['poll_questions'].
                  " WHERE accept='2' ORDER BY id DESC ".$this->db->compat_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 = lecho("No poll yet");

                  $out = $this->html->sidebox("<a href=\"".$config->basehref.
                        $config->pollindexfile.
                        "\" class=\"boxheader\">".lecho("Poll")."</a>", $content);
                  $this->cache->write_box("show_poll",$cachetmp,$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 .= "\n[".lecho("Comments")."]\n";

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

      /**
       * Take a vote into account.
       *@param integer the answer the user selected
       *@param integer ID of the poll
       *@return string HTML comments indicating status or error message
       *@access public
       */
      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();
            $known_ip = $this->db->num_rows();
            if($known_ip!=0 && $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 ($known_ip!=0 && $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";
      }

      /**
       * Displays the results of a poll
       * Calls exit if SQL fails
       *@param string the ID of poll, -1 for old polls?
       *@return string box with poll results
       *@access public
       */
      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 ".$this->db->compat_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();
                  if ($this->db->num_rows() == 0){
                        return lecho("No poll yet");
                  }
                  $id = $row['id'];
            }
            $sqlc_q = "SELECT ".$config->tables['poll_questions'].".question, ".
                  "sum(".$config->tables['poll_answers'].".number) AS my_sum 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".
                  ", ".$config->tables['poll_questions'].".question";
            $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["my_sum"];
            $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=300*$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;
      }

      /**
       * Lists polls to moderate
       *@return string the list
       *@access public
       */
      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;[".lecho("POLL")."]&nbsp;<a href=\"".
                        $config->basehref.$config->adminfile.
                        "?action=list_polls&amp;id=".$row['id']."\">".$row['question'].
                        "</a><br />\n";
            }
            return $content;
      }

      /**
       * Moderation form
       *@param integer the ID of the poll
       *@return string the form
       *@access public
       */
      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="selected"';
                  }
                  $content .= '>'.$status[$accept].'</option>';
            }
            $content .= '</select>';
            $content .= '<input type="submit" value="'.lecho("Confirm").
                  '" /></center>'."\n";
            $content .= '</form>';

            return $content;
      }

      /**
       * List all polls for admin
       *@return string the list
       *@access public
       */
      Function list_polls() {
            global $config,$HTTP_GET_VARS;

            if (isset ($HTTP_GET_VARS['id'])) {
                  return $this->edit_poll($HTTP_GET_VARS['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."\" class=\"boxheader\">".
                  lecho("Poll")."</a>", $content);
            return $out;
      }

      /**
       * Take into account moderator's choice
       * Calls exit if user is not moderator
       *@param integer the poll ID
       *@param integer the status to set
       *@return mixed void if success, string HTML comment describing error on failure
       *@access public
       */
      Function mod_poll($id,$status=0) {
            global $config;

            if (!$this->session->is_moderator) {
                  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;
                  }
            }
      }

}

?>

Generated by  Doxygen 1.6.0   Back to index