<?php
// $Id: poll.module,v 1.222.2.5 2008/10/05 00:51:40 drumm Exp $

/**
 * @file
 * Enables your site to capture votes on different topics in the form of multiple
 * choice questions.
 */

/**
 * Implementation of hook_help().
 */
function poll_help($section) {
  switch ($section) {
    case 'admin/help#poll':
      $output = '<p>'. t('The poll module can be used to create simple polls for site users. A poll is a simple multiple choice questionnaire which displays the cumulative results of the answers to the poll. Having polls on the site is a good way to get instant feedback from community members.') .'</p>';
      $output .= '<p>'. t('Users can create a poll. The title of the poll should be the question, then enter the answers and the "base" vote counts. You can also choose the time period over which the vote will run.The <a href="@poll">poll</a> item in the navigation menu will take you to a page where you can see all the current polls, vote on them (if you haven\'t already) and view the results.', array('@poll' => url('poll'))) .'</p>';
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@poll">Poll page</a>.', array('@poll' => 'http://drupal.org/handbook/modules/poll/')) .'</p>';
      return $output;
  }
}

/**
 * Implementation of hook_access().
 */
function poll_access($op, $node) {
  if ($op == 'create') {
    return user_access('create polls');
  }
}

/**
 * Implementation of hook_block().
 *
 * Generates a block containing the latest poll.
 */
function poll_block($op = 'list', $delta = 0) {
  if (user_access('access content')) {
    if ($op == 'list') {
      $blocks[0]['info'] = t('Most recent poll');
      return $blocks;
    }
    else if ($op == 'view') {
      // Retrieve the latest poll.
      $sql = db_rewrite_sql("SELECT MAX(n.created) FROM {node} n INNER JOIN {poll} p ON p.nid = n.nid WHERE n.status = 1 AND p.active = 1");
      $timestamp = db_result(db_query($sql));
      if ($timestamp) {
        $poll = node_load(array('type' => 'poll', 'created' => $timestamp, 'status' => 1));

        if ($poll->nid) {
          $poll = poll_view($poll, TRUE, FALSE, TRUE);
        }
      }
      $block['subject'] = t('Poll');
      $block['content'] = drupal_render($poll->content);
      return $block;
    }
  }
}

/**
 * Implementation of hook_cron().
 *
 * Closes polls that have exceeded their allowed runtime.
 */
function poll_cron() {
  $result = db_query('SELECT p.nid FROM {poll} p INNER JOIN {node} n ON p.nid = n.nid WHERE (n.created + p.runtime) < '. time() .' AND p.active = 1 AND p.runtime != 0');
  while ($poll = db_fetch_object($result)) {
    db_query("UPDATE {poll} SET active = 0 WHERE nid = %d", $poll->nid);
  }
}

/**
 * Implementation of hook_delete().
 */
function poll_delete($node) {
  db_query("DELETE FROM {poll} WHERE nid = %d", $node->nid);
  db_query("DELETE FROM {poll_choices} WHERE nid = %d", $node->nid);
  db_query("DELETE FROM {poll_votes} WHERE nid = %d", $node->nid);
}

/**
 * Implementation of hook_submit().
 */
function poll_submit(&$node) {
  // Renumber fields
  $node->choice = array_values($node->choice);
  $node->teaser = poll_teaser($node);
}

/**
 * Implementation of hook_validate().
 */
function poll_validate($node) {
  if (isset($node->title)) {
    // Check for at least two options and validate amount of votes:
    $realchoices = 0;
    // Renumber fields
    $node->choice = array_values($node->choice);
    foreach ($node->choice as $i => $choice) {
      if ($choice['chtext'] != '') {
        $realchoices++;
      }
      if ($choice['chvotes'] < 0) {
        form_set_error("choice][$i][chvotes", t('Negative values are not allowed.'));
      }
    }

    if ($realchoices < 2) {
      form_set_error("choice][$realchoices][chtext", t('You must fill in at least two choices.'));
    }
  }
}

/**
 * Implementation of hook_form().
 */
function poll_form($node, $form_values = NULL) {
  $admin = user_access('administer nodes');
  $type = node_get_types('type', $node);
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#required' => TRUE,
    '#default_value' => $node->title,
    '#weight' => -1
  );

  if (isset($form_values)) {
    $choices = $form_values['choices'];
    if ($form_values['morechoices']) {
      $choices *= 2;
    }
  }
  else {
    $choices = max(2, count($node->choice) ? count($node->choice) : 5);
  }

  $form['choices'] = array(
    '#type' => 'hidden',
    '#value' => $choices,
  );

  // Poll choices
  $form['choice'] = array(
    '#type' => 'fieldset',
    '#title' => t('Choices'),
    '#prefix' => '<div class="poll-form">',
    '#suffix' => '</div>',
    '#tree' => TRUE
  );

  // We'll manually set the #parents property of this checkbox so that
  // it appears in the fieldset visually, but its value won't pollute
  // the $form_values['choice'] array.
  $form['choice']['morechoices'] = array(
    '#type' => 'checkbox',
    '#parents' => array('morechoices'),
    '#title' => t('Need more choices'),
    '#value' => 0,
    '#description' => t("If the amount of boxes above isn't enough, check this box and click the Preview button below to add some more."),
    '#weight' => 1,
  );

  for ($a = 0; $a < $choices; $a++) {
    $form['choice'][$a]['chtext'] = array(
      '#type' => 'textfield',
      '#title' => t('Choice @n', array('@n' => ($a + 1))),
      '#default_value' => $node->choice[$a]['chtext'],
    );

    if ($admin) {
      $form['choice'][$a]['chvotes'] = array(
        '#type' => 'textfield',
        '#title' => t('Votes for choice @n', array('@n' => ($a + 1))),
        '#default_value' => (int)$node->choice[$a]['chvotes'],
        '#size' => 5, '#maxlength' => 7
      );
    }
  }

  // Poll attributes
  $_duration = array(0 => t('Unlimited')) + drupal_map_assoc(array(86400, 172800, 345600, 604800, 1209600, 2419200, 4838400, 9676800, 31536000), "format_interval");
  $_active = array(0 => t('Closed'), 1 => t('Active'));

  if ($admin) {
    $form['settings'] = array('#type' => 'fieldset', '#title' => t('Settings'));

    $form['settings']['active'] = array(
      '#type' => 'radios',
      '#title' => t('Poll status'),
      '#default_value' => isset($node->active) ? $node->active : 1,
      '#options' => $_active,
      '#description' => t('When a poll is closed, visitors can no longer vote for it.')
    );
  }
  $form['settings']['runtime'] = array(
    '#type' => 'select',
    '#title' => t('Poll duration'),
    '#default_value' => $node->runtime,
    '#options' => $_duration,
    '#description' => t('After this period, the poll will be closed automatically.'),
  );

  $form['#multistep'] = TRUE;
  return $form;
}

function poll_insert($node) {
  if (!user_access('administer nodes')) {
    // Make sure all votes are 0 initially
    foreach ($node->choice as $i => $choice) {
      $node->choice[$i]['chvotes'] = 0;
    }
    $node->active = 1;
  }

  db_query("INSERT INTO {poll} (nid, runtime, active) VALUES (%d, %d, %d)", $node->nid, $node->runtime, $node->active);

  $i = 0;
  foreach ($node->choice as $choice) {
    if ($choice['chtext'] != '') {
      db_query("INSERT INTO {poll_choices} (nid, chtext, chvotes, chorder) VALUES (%d, '%s', %d, %d)", $node->nid, $choice['chtext'], $choice['chvotes'], $i++);
    }
  }
}

/**
 * Implementation of hook_menu().
 */
function poll_menu($may_cache) {
  $items = array();

  if ($may_cache) {
    $items[] = array('path' => 'poll', 'title' => t('Polls'),
      'callback' => 'poll_page',
      'access' => user_access('access content'),
      'type' => MENU_SUGGESTED_ITEM);

    $items[] = array('path' => 'poll/vote',
      'title' => t('Vote'),
      'callback' => 'poll_vote',
      'access' => user_access('vote on polls'),
      'type' => MENU_CALLBACK);

    $items[] = array('path' => 'poll/cancel',
      'title' => t('Cancel'),
      'callback' => 'poll_cancel',
      'access' => user_access('cancel own vote'),
      'type' => MENU_CALLBACK);
  }
  else {
    // Add the CSS for this module
    // We put this in !$may_cache so it's only added once per request
    drupal_add_css(drupal_get_path('module', 'poll') .'/poll.css');

    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(arg(1));
      if ($node->type == 'poll') {
        $items[] = array('path' => 'node/'. arg(1) .'/votes',
          'title' => t('Votes'),
          'callback' => 'poll_votes',
          'access' => user_access('inspect all votes'),
          'weight' => 3,
          'type' => MENU_LOCAL_TASK);
      }
      if ($node->type == 'poll' && $node->allowvotes) {
        $items[] = array('path' => 'node/'. arg(1) .'/results',
          'title' => t('Results'),
          'callback' => 'poll_results',
          'access' => user_access('access content'),
          'weight' => 3,
          'type' => MENU_LOCAL_TASK);
      }
    }
  }

  return $items;
}

/**
 * Implementation of hook_load().
 */
function poll_load($node) {
  global $user;

  $poll = db_fetch_object(db_query("SELECT runtime, active FROM {poll} WHERE nid = %d", $node->nid));

  // Load the appropriate choices into the $poll object.
  $result = db_query("SELECT chtext, chvotes, chorder FROM {poll_choices} WHERE nid = %d ORDER BY chorder", $node->nid);
  while ($choice = db_fetch_array($result)) {
    $poll->choice[$choice['chorder']] = $choice;
  }

  // Determine whether or not this user is allowed to vote.
  $poll->allowvotes = FALSE;
  if (user_access('vote on polls') && $poll->active) {
    if ($user->uid) {
      $result = db_fetch_object(db_query('SELECT chorder FROM {poll_votes} WHERE nid = %d AND uid = %d', $node->nid, $user->uid));
    }
    else {
      $result = db_fetch_object(db_query("SELECT chorder FROM {poll_votes} WHERE nid = %d AND hostname = '%s'", $node->nid, $_SERVER['REMOTE_ADDR']));
    }
    if (isset($result->chorder)) {
      $poll->vote = $result->chorder;
    }
    else {
      $poll->vote = -1;
      $poll->allowvotes = TRUE;
    }
  }
  return $poll;
}

/**
 * Implementation of hook_node_info().
 */
function poll_node_info() {
  return array(
    'poll' => array(
      'name' => t('Poll'),
      'module' => 'poll',
      'description' => t("A poll is a multiple-choice question which visitors can vote on."),
      'title_label' => t('Question'),
      'has_body' => FALSE,
    )
  );
}

function poll_page() {
  // List all polls.
  $sql = db_rewrite_sql("SELECT n.nid, n.title, p.active, n.created, SUM(c.chvotes) AS votes FROM {node} n INNER JOIN {poll} p ON n.nid = p.nid INNER JOIN {poll_choices} c ON n.nid = c.nid WHERE n.status = 1 GROUP BY n.nid, n.title, p.active, n.created ORDER BY n.created DESC");
  // Count all polls for the pager.
  $count_sql = db_rewrite_sql('SELECT COUNT(*) FROM {node} n INNER JOIN {poll} p ON n.nid = p.nid WHERE n.status = 1');
  $result = pager_query($sql, 15, 0, $count_sql);
  $output = '<ul>';
  while ($node = db_fetch_object($result)) {
    $output .= '<li>'. l($node->title, "node/$node->nid") .' - '. format_plural($node->votes, '1 vote', '@count votes') .' - '. ($node->active ? t('open') : t('closed')) .'</li>';
  }
  $output .= '</ul>';
  $output .= theme("pager", NULL, 15);
  return $output;
}

/**
 * Implementation of hook_perm().
 */
function poll_perm() {
  return array('create polls', 'vote on polls', 'cancel own vote', 'inspect all votes');
}

/**
 * Creates a simple teaser that lists all the choices.
 */
function poll_teaser($node) {
  $teaser = NULL;
  if (is_array($node->choice)) {
    foreach ($node->choice as $k => $choice) {
      if ($choice['chtext'] != '') {
        $teaser .= '* '. check_plain($choice['chtext']) ."\n";
      }
    }
  }
  return $teaser;
}

/**
 * Generates the voting form for a poll.
 */
function poll_view_voting($node, $block) {
  if ($node->choice) {
    $list = array();
    foreach ($node->choice as $i => $choice) {
      $list[$i] = check_plain($choice['chtext']);
    }
    $form['choice'] = array(
      '#type' => 'radios',
      '#title' => $block ? check_plain($node->title) : '',
      '#default_value' => -1,
      '#options' => $list,
    );
  }
  $form['nid'] = array('#type' => 'hidden', '#value' => $node->nid);
  $form['vote'] = array('#type' => 'submit', '#value' => t('Vote'));
  $form['#action'] = url('node/'. $node->nid);
  return $form;
}

/**
 * Themes the voting form for a poll.
 */
function theme_poll_view_voting($form) {
  $output .= '<div class="poll">';
  $output .= '  <div class="vote-form">';
  $output .= '    <div class="choices">';
  $output .= drupal_render($form['choice']);
  $output .= '    </div>';
  $output .= drupal_render($form['nid']);
  $output .= drupal_render($form['vote']);
  $output .= '  </div>';
  $output .= drupal_render($form);
  $output .= '</div>';
  return $output;
}

/**
 * Generates a graphical representation of the results of a poll.
 */
function poll_view_results(&$node, $teaser, $page, $block) {
  // Count the votes and find the maximum
  foreach ($node->choice as $choice) {
    $total_votes += $choice['chvotes'];
    $max_votes = max($max_votes, $choice['chvotes']);
  }

  foreach ($node->choice as $i => $choice) {
    if ($choice['chtext'] != '') {
      $poll_results .= theme('poll_bar', check_plain($choice['chtext']), round($choice['chvotes'] * 100 / max($total_votes, 1)), format_plural($choice['chvotes'], '1 vote', '@count votes'), $block);
    }
  }

  $output .= theme('poll_results', check_plain($node->title), $poll_results, $total_votes, $node->links, $block, $node->nid, $node->vote);

  return $output;
}

function theme_poll_results($title, $results, $votes, $links, $block, $nid, $vote) {
  if ($block) {
    $output .= '<div class="poll">';
    $output .= '<div class="title">'. $title .'</div>';
    $output .= $results;
    $output .= '<div class="total">'. t('Total votes: %votes', array('%votes' => $votes)) .'</div>';
    $output .= '</div>';
    $output .= '<div class="links">'. theme('links', $links) .'</div>';
  }
  else {
    $output .= '<div class="poll">';
    $output .= $results;
    $output .= '<div class="total">'. t('Total votes: %votes', array('%votes' => $votes)) .'</div>';
    if (isset($vote) && $vote > -1 && user_access('cancel own vote')) {
      $output .= drupal_get_form('poll_cancel_form', $nid);
    }
    $output .= '</div>';
  }

  return $output;
}

function poll_cancel_form($nid) {
  $form['#action'] = url("poll/cancel/$nid");
  $form['submit'] = array('#type' => 'submit', '#value' => t('Cancel your vote'));
  return $form;
}

function theme_poll_bar($title, $percentage, $votes, $block) {
  if ($block) {
    $output  = '<div class="text">'. $title .'</div>';
    $output .= '<div class="bar"><div style="width: '. $percentage .'%;" class="foreground"></div></div>';
    $output .= '<div class="percent">'. $percentage .'%</div>';
  }
  else {
    $output  = '<div class="text">'. $title .'</div>';
    $output .= '<div class="bar"><div style="width: '. $percentage .'%;" class="foreground"></div></div>';
    $output .= '<div class="percent">'. $percentage .'% ('. $votes .')</div>';
  }

  return $output;
}

/**
 * Callback for the 'results' tab for polls you can vote on
 */
function poll_results() {
  if ($node = node_load(arg(1))) {
    drupal_set_title(check_plain($node->title));
    return node_show($node, 0);
  }
  else {
    drupal_not_found();
  }
}

/**
 * Callback for the 'votes' tab for polls you can see other votes on
 */
function poll_votes() {
  if ($node = node_load(arg(1))) {
    drupal_set_title(check_plain($node->title));
    $output = t('This table lists all the recorded votes for this poll.  If anonymous users are allowed to vote, they will be identified by the IP address of the computer they used when they voted.');

    $header[] = array('data' => t('Visitor'), 'field' => 'u.name');
    $header[] = array('data' => t('Vote'), 'field' => 'pv.chorder');

    $result = pager_query("SELECT pv.chorder, pv.uid, pv.hostname, u.name FROM {poll_votes} pv LEFT JOIN {users} u ON pv.uid = u.uid WHERE pv.nid = %d" . tablesort_sql($header), 20, 0, NULL, $node->nid);
    $rows = array();
    while ($vote = db_fetch_object($result)) {
      $rows[] = array(
        $vote->name ? theme('username', $vote) : check_plain($vote->hostname),
        check_plain($node->choice[$vote->chorder]['chtext']));
    }
    $output .= theme('table', $header, $rows);
    $output .= theme('pager', NULL, 20, 0);
    print theme('page', $output);
  }
  else {
    drupal_not_found();
  }
}

/**
 * Callback for processing a vote
 */
function poll_vote(&$node) {
  global $user;
  $nid = arg(1);

  if ($node = node_load($nid)) {
    $edit = $_POST;
    $choice = $edit['choice'];
    $vote = $_POST['vote'];

    if (isset($choice) && isset($node->choice[$choice])) {
      if ($node->allowvotes) {
        // Record the vote by this user or host.
        if ($user->uid) {
          db_query('INSERT INTO {poll_votes} (nid, chorder, uid) VALUES (%d, %d, %d)', $node->nid, $choice, $user->uid);
        }
        else {
          db_query("INSERT INTO {poll_votes} (nid, chorder, hostname) VALUES (%d, %d, '%s')", $node->nid, $choice, $_SERVER['REMOTE_ADDR']);
        }

        // Add one to the votes.
        db_query("UPDATE {poll_choices} SET chvotes = chvotes + 1 WHERE nid = %d AND chorder = %d", $node->nid, $choice);

        $node->allowvotes = FALSE;
        $node->choice[$choice]['chvotes']++;
        cache_clear_all();
        drupal_set_message(t('Your vote was recorded.'));
      }
      else {
        drupal_set_message(t("You are not allowed to vote on this poll."), 'error');
      }
    }
    else {
      drupal_set_message(t("You did not specify a valid poll choice."), 'error');
    }
    drupal_goto('node/'. $nid);
  }
  else {
    drupal_not_found();
  }
}


/**
 * Callback for canceling a vote
 */
function poll_cancel(&$node) {
  global $user;

  $nid = arg(2);
  if ($node = node_load($nid)) {
    if ($node->type == 'poll' && $node->allowvotes == FALSE) {
      if ($user->uid) {
        db_query('DELETE FROM {poll_votes} WHERE nid = %d and uid = %d', $node->nid, $user->uid);
      }
      else {
        db_query("DELETE FROM {poll_votes} WHERE nid = %d and hostname = '%s'", $node->nid, $_SERVER['REMOTE_ADDR']);
      }

      // Subtract from the votes.
      db_query("UPDATE {poll_choices} SET chvotes = chvotes - 1 WHERE nid = %d AND chorder = %d", $node->nid, $node->vote);
      $node->allowvotes = TRUE;
      $node->choice[$node->vote]['chvotes']--;
      drupal_set_message(t('Your vote was canceled.'));
    }
    else {
      drupal_set_message(t("You are not allowed to cancel an invalid poll choice."), 'error');
    }
    drupal_goto('node/'. $nid);
  }
  else {
    drupal_not_found();
  }
}

/**
 * Implementation of hook_view().
 *
 * @param $block
 *   An extra parameter that adapts the hook to display a block-ready
 *   rendering of the poll.
 */
function poll_view($node, $teaser = FALSE, $page = FALSE, $block = FALSE) {
  global $user;
  $output = '';

  // Special display for side-block
  if ($block) {
    // No 'read more' link
    $node->readmore = FALSE;

    $links = module_invoke_all('link', 'node', $node, 1);
    $links[] = array('title' => t('Older polls'), 'href' => 'poll', 'attributes' => array('title' => t('View the list of polls on this site.')));
    if ($node->allowvotes && $block) {
      $links[] = array('title' => t('Results'), 'href' => 'node/'. $node->nid .'/results', 'attributes' => array('title' => t('View the current poll results.')));
    }

    $node->links = $links;
  }

  if ($node->allowvotes && ($block || arg(2) != 'results')) {
    if ($_POST['op'] == t('Vote')) {
      poll_vote($node);
    }
    $node->content['body'] = array(
      '#value' => drupal_get_form('poll_view_voting', $node, $block),
    );
  }
  else {
    $node->content['body'] = array(
      '#value' => poll_view_results($node, $teaser, $page, $block),
    );
  }
  return $node;
}

/**
 * Implementation of hook_update().
 */
function poll_update($node) {
  // Update poll settings.
  db_query('UPDATE {poll} SET runtime = %d, active = %d WHERE nid = %d', $node->runtime, $node->active, $node->nid);

  // Clean poll choices.
  db_query('DELETE FROM {poll_choices} WHERE nid = %d', $node->nid);

  // Poll choices come in the same order with the same numbers as they are in
  // the database, but some might have an empty title, which signifies that
  // they should be removed. We remove all votes to the removed options, so
  // people who voted on them can vote again.
  $new_chorder = 0;
  foreach ($node->choice as $old_chorder => $choice) {
    $chvotes = isset($choice['chvotes']) ? (int)$choice['chvotes'] : 0;
    $chtext = $choice['chtext'];

    if (!empty($chtext)) {
      db_query("INSERT INTO {poll_choices} (nid, chtext, chvotes, chorder) VALUES (%d, '%s', %d, %d)", $node->nid, $chtext, $chvotes, $new_chorder);
      if ($new_chorder != $old_chorder) {
        // We can only remove items in the middle, not add, so
        // new_chorder is always <= old_chorder, making this safe.
        db_query("UPDATE {poll_votes} SET chorder = %d WHERE nid = %d AND chorder = %d", $new_chorder, $node->nid, $old_chorder);
      }
      $new_chorder++;
    }
    else {
      db_query("DELETE FROM {poll_votes} WHERE nid = %d AND chorder = %d", $node->nid, $old_chorder);
    }
  }
}

/**
 * Implementation of hook_user().
 */
function poll_user($op, &$edit, &$user) {
  if ($op == 'delete') {
    db_query('UPDATE {poll_votes} SET uid = 0 WHERE uid = %d', $user->uid);
  }
}
