<?php

/*    mod_poll: allows users to create polls within phorum messages 
    author: Arthur Louie (arthur.louie@gmail.com)
    version: 0.2
    license: You are free to use, modify, or redistribute this code so long 
       as I am given credit for the original development somewhere.
               This code comes with absolutly no warranty.
    (license copied from Thomas Seifert's forumstats module)
*/

if(!defined("PHORUM")) return;

define("MOD_POLL_NUM_POSSIBLE_ANSWERS_DEFAULT", 10);
define("MOD_POLL_MAX_BAR_WIDTH_DEFAULT", 350);
define("MOD_POLL_BAR_COLOR_DEFAULT", "red");
define("MOD_POLL_RESULT_BG_COLOR_DEFAULT", "#F9FFFF");
define("MOD_POLL_RESULT_HEADER_COLOR_DEFAULT", "#CCFFCC");

// We get here when creating a new poll or previewing a new poll.
// hook: common
function mod_poll_setup_form() {
  GLOBAL $PHORUM;
  if($PHORUM['DATA']['LOGGEDIN']) {
    $allowed = !$PHORUM["mod_poll"]["moderator_only"] || phorum_user_access_allowed(PHORUM_USER_ALLOW_MODERATE_MESSAGES);
    if ($allowed) {
      $PHORUM['DATA']['NEWPOLLURL'] = phorum_get_url(PHORUM_POST_URL, "newpoll=1");
    }
    if(phorum_page == "post") {
      if (isset($PHORUM["args"]["newpoll"]) || $_POST['addpoll']) {
         if ($PHORUM["mod_poll"]["moderator_only"] && !phorum_user_access_allowed(PHORUM_USER_ALLOW_MODERATE_MESSAGES)) {
           return;
         }
         if ($POST['pollq']) {
           $_POST['pollq'] = htmlspecialchars($_POST['pollq']);
           $_POST['pollq'] = str_replace ('"', '&quot;', $_POST['pollq']);
         }
         $PHORUM['DATA']['POLLFORM'] =<<<EOT
Poll question:<br />
<input type="text" name="pollq" size="50" value="$_POST[pollq]" />
<input type="hidden" name="addpoll" value="1" /><br />
<br />
Possible poll responses:<br />
<ol>
EOT;
        if (!isset($PHORUM["mod_poll"]["num_possible_ans"])) {
          $PHORUM["mod_poll"]["num_possible_ans"] = MOD_POLL_NUM_POSSIBLE_ANSWERS_DEFAULT;
        }
        for ($i=1; $i <= $PHORUM["mod_poll"]["num_possible_ans"]; ++$i) {
          if ($_POST["pollans"][$i]) {
            $_POST["pollans"][$i] = htmlspecialchars($_POST["pollans"][$i]);
            $_POST["pollans"][$i] = str_replace ('"', '&quot;', $_POST["pollans"][$i]);
          }
          $val = $_POST["pollans"][$i];
          $PHORUM['DATA']['POLLFORM'] .=<<<EOT
  <li><input type="text" name="pollans[$i]" size="50" value="$val" /></li>
EOT;
        }
        $PHORUM['DATA']['POLLFORM'] .= '</ol>';
      }

      // set up the question and answers
      if ($_POST['addpoll']){
        $PHORUM['DATA']['POLL']['QUESTION'] = $_POST['pollq'];
        foreach ($_POST['pollans'] AS $ans) {
          $ans = trim($ans);
          if ($ans) {
            $PHORUM['DATA']['POLL']['ANSWERS'][] = $ans; 
          }
        }
        if (empty($PHORUM['DATA']['POLL']['QUESTION']) || empty($PHORUM['DATA']['POLL']['ANSWERS'])) {
          $PHORUM['DATA']['POLL']['ERROR'] = true;
        }
        else {
          $PHORUM['DATA']['POLL']['ERROR'] = false;
        }
      }
    }
  }
}
// After the message is formatted, we add the poll info to the beginning of the message body.
// hook: format
function mod_poll_display($messages) {
  GLOBAL $PHORUM;
  if (isset($PHORUM['DATA']['POLL'])) {
    // we get here when we preview a poll -- need to simulate metadata
    $messages[0]["meta"]["mod_poll"]["question"]=$PHORUM['DATA']['POLL']['QUESTION'];
    $messages[0]["meta"]["mod_poll"]["answers"]=$PHORUM['DATA']['POLL']['ANSWERS'];
    if (is_array($PHORUM['DATA']['POLL']['ANSWERS'])) {
      foreach ($PHORUM['DATA']['POLL']['ANSWERS'] AS $key => $val) {
        $messages[0]["meta"]["mod_poll"]["votes"][$key]=0;
      }
    }
  }
  foreach ($messages AS $key => $val) {
    // add the poll to the start of the message
    if (isset($messages[$key]["meta"]["mod_poll"]["question"])) {
       $num_responses = 0;
       if (is_array($messages[$key]["meta"]["mod_poll"]["votes"])) {
         foreach ($messages[$key]["meta"]["mod_poll"]["votes"] AS $n) {
           $num_responses += $n;
         }
       }
       $s_plural = ($num_responses==1 ? '' : 's');
       $user_has_voted = isset($PHORUM["user"]["mod_poll"]["voted"][$key]);
       $poll_question = $messages[$key]["meta"]["mod_poll"]["question"];
       $pre_body = "<h2 align=\"center\">$poll_question</h2>\n";
       $post_url = phorum_get_url(PHORUM_POST_URL);

       if (!$user_has_voted) {
         $poll_answers = '';

         $poll_answers .= "<table border=\"0\" align=\"center\">\n<tbody>\n";
         if (is_array($messages[$key]["meta"]["mod_poll"]["answers"])) {
           foreach ($messages[$key]["meta"]["mod_poll"]["answers"] AS $anskey => $ans) {
             $poll_answers .=<<<EOT
    <tr>
      <td valign="top"><input TYPE="radio" NAME="pollvote" VALUE="$anskey" /></td>
      <td valign="top">$ans</td>
    </tr>
EOT;
           }
         }
         $poll_answers .= "  </tbody>\n</table>\n";

         if ($PHORUM['DATA']['LOGGEDIN']) {
          $submit = '<p align="center"><input type="submit" value="Vote" /></p>';
         }
         else {
          $submit = "<p align=\"center\"><i>You must be logged in to vote.</i></p>";
         }

         $show_results_url = phorum_get_url(PHORUM_READ_URL, $key, 'showresults=1');
         $show_results_html = isset($PHORUM["args"]["showresults"]) ? '' : "<p align=\"center\"><a href=\"$show_results_url\">Show results</a></p>";
         $pre_body .=<<<EOT
<form action="$post_url" method="post" style="display: inline;">
$poll_answers
<input type="hidden" name="message_id" value="$key" />
$submit
<p></p>
$show_results_html
</form>
EOT;
      }

      if ($user_has_voted || isset($PHORUM["args"]["showresults"])) {
         $bar_width = isset($PHORUM["mod_poll"]["max_bar_width"]) ? $PHORUM["mod_poll"]["max_bar_width"]  : MOD_POLL_MAX_BAR_WIDTH_DEFAULT;
         $bar_color = isset($PHORUM["mod_poll"]["bar_color"]) ? $PHORUM["mod_poll"]["bar_color"]  : MOD_POLL_BAR_COLOR_DEFAULT;
         $result_bg_color = isset($PHORUM["mod_poll"]["result_bg_color"]) ? $PHORUM["mod_poll"]["result_bg_color"]  : MOD_POLL_RESULT_BG_COLOR_DEFAULT;
         $result_header_color = isset($PHORUM["mod_poll"]["result_header_color"]) ? $PHORUM["mod_poll"]["result_header_color"]  : MOD_POLL_RESULT_HEADER_COLOR_DEFAULT;
               $pre_body .= "<h3 align=\"center\">Poll results</h3>";
               $pre_body .= "<table cellpadding=\"0\" cellspacing=\"1\" border=\"0\" align=\"center\">\n";
               $pre_body .= "  <tbody>\n";

         foreach ($messages[$key]["meta"]["mod_poll"]["answers"] AS $anskey => $ans) {
           $ansvotes = $messages[$key]["meta"]["mod_poll"]["votes"][$anskey];
           if ($num_responses > 0) {
             $fraction = $ansvotes / $num_responses;
           }
           else {
             $fraction = 0;
           }
           $width=$fraction * $bar_width;
           $color = $bar_color;
           $percentage = sprintf("%01.2f", $fraction * 100);
           if ($PHORUM["user"]["mod_poll"]["voted"][$key] == $anskey) {
             $ans = "<strong>$ans</strong>";
           }
           $pre_body .= "    <tr>\n      <td valign=\"top\">";
           $pre_body .= "\n<table border=\"0\" bgcolor=\"$result_bg_color\" cellspacing=\"0\" cellpadding=\"3\" width=\"100%\" style=\"border: 1px solid $result_header_color\">\n";
           $pre_body .= "<tbody>\n";
           $pre_body .=<<<EOT
  <tr>
    <td valign="top">$ans</td>
    <td valign="top" align="right" width="50" nowrap="nowrap">votes: $ansvotes</td>
  </tr>
EOT;
           if ($width > 0) {
             $pre_body .=<<<EOT
  <tr>
    <td valign="top" align="left" colspan="2">
    <table border="0" cellpadding="0" cellspacing="0" style="border: 0px">
      <tbody>
        <tr>
          <td valign="top" align="left" bgcolor="$color" width="$width"><font size="-3">&nbsp;</font></td>
          <td valign="top" align="left" nowrap="nowrap">&nbsp;$percentage%</td>
        </tr>
      </tbody>
    </table>
    </td>
EOT;
           }
           $pre_body .=<<<EOT
    </tr>
  </tbody>
</table>
      </td>
    </tr>
EOT;
         } 
         if ($PHORUM['DATA']['LOGGEDIN']) {
           $vote_status = $user_has_voted ? 'Your vote is in <strong>bold</strong>' : '<i>You have not voted yet</i>';
         }
         $pre_body .= "  </tbody>\n</table>\n<div align=\"center\"><p>$num_responses vote$s_plural</p>\n<p>$vote_status</p>";
         if ($user_has_voted) {
           $pre_body .=<<<EOT
<form action="$post_url" method="post" style="display: inline;">
<input type="hidden" name="pollcancel" value="1" />
<input type="hidden" name="message_id" value="$key" />
<input type="submit" value="Cancel my vote" />
</form>
EOT;
         }
         $pre_body .= "</div>";
      }
      $pre_body = '<div class="body">' . $pre_body . '</div>';
      $messages[$key]['body'] = $pre_body . $messages[$key]['body'];
    }
  }
  return $messages;
}


// We get here when someone submits a vote 
// Input: $_POST["message_id"], $_POST["pollvote"]
// hook: common
function mod_poll_receive_vote() {
  GLOBAL $PHORUM;

  if($PHORUM['DATA']['LOGGEDIN']) {

    if(phorum_page == "post") {
      if (isset($_POST['pollvote']) || isset($_POST['pollcancel'])) {
        // get the poll info
        $vote = $_POST["pollvote"];
        $message_id = $_POST["message_id"];
        $message=phorum_db_get_message($message_id);
      }

      if (isset($_POST['pollvote'])) {
        // check that the user's response is a valid poll answer
        if (isset($message["meta"]["mod_poll"]["answers"][$vote])) {
          // check if the person has already voted 
          if (!isset($PHORUM["user"]["mod_poll"]["voted"][$message_id])) {
            // update poll
            $message["meta"]["mod_poll"]["votes"][$vote]++;
            phorum_db_update_message($message["message_id"], $message);

            // update user
            $userdata=array();
            $userdata['user_id']=$PHORUM["user"]["user_id"];
            $userdata["mod_poll"]=$PHORUM["user"]["mod_poll"];
            $userdata["mod_poll"]["voted"][$message_id]=$vote;
            phorum_user_save($userdata); 
          }
        }
        // redirect to thread
        $redirect = phorum_get_url(PHORUM_READ_URL, $message_id);
        phorum_redirect_by_url ($redirect);
      }

      if (isset($_POST['pollcancel'])) {
        // check if the person has already voted
        if (isset($PHORUM["user"]["mod_poll"]["voted"][$message_id])) {
          // update poll
          $the_vote = $PHORUM["user"]["mod_poll"]["voted"][$message_id];
          $message["meta"]["mod_poll"]["votes"][$the_vote]--;
          phorum_db_update_message($message["message_id"], $message);

          // update user
          $userdata=array();
          $userdata['user_id']=$PHORUM["user"]["user_id"];
          $userdata["mod_poll"]=$PHORUM["user"]["mod_poll"];
          unset($userdata["mod_poll"]["voted"][$message_id]);
          phorum_user_save($userdata);
        }
        // redirect to thread
        $redirect = phorum_get_url(PHORUM_READ_URL, $message_id, 'showresults=1');
        phorum_redirect_by_url ($redirect);
      }
    }
  }
}

// After a new poll is posted, we need to save it to the message's metadata
// hook: post_post
function mod_poll_save_metadata($message) {
  GLOBAL $PHORUM;
  if (isset($PHORUM['DATA']['POLL']) && !$PHORUM['DATA']['POLL']['ERROR']) {
    // save the poll as message metadata
    $temp_message = phorum_db_get_message ($message["message_id"]);
    $new_mess_struct["meta"]=$temp_message["meta"];
    $new_mess_struct["meta"]["mod_poll"]["question"]=$PHORUM['DATA']['POLL']['QUESTION'];
    $new_mess_struct["meta"]["mod_poll"]["answers"]=$PHORUM['DATA']['POLL']['ANSWERS'];
    foreach ($PHORUM['DATA']['POLL']['ANSWERS'] AS $key => $val) {
      $new_mess_struct["meta"]["mod_poll"]["votes"][$key]=0;
    }
    if (!stristr($temp_message["subject"], 'poll')) {
      $new_mess_struct["subject"] = 'Poll: ' . $temp_message["subject"];
    }
    phorum_db_update_message($message["message_id"], $new_mess_struct);
  }
  return $message;
} 
 
?>