home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / CMS / drupal-6.0.exe / drupal-6.0 / modules / poll / poll.module < prev    next >
Encoding:
Text File  |  2008-01-15  |  24.7 KB  |  794 lines

  1. <?php
  2. // $Id: poll.module,v 1.263 2008/01/15 07:57:46 dries Exp $
  3.  
  4. /**
  5.  * @file
  6.  * Enables your site to capture votes on different topics in the form of multiple
  7.  * choice questions.
  8.  */
  9.  
  10. /**
  11.  * Implementation of hook_help().
  12.  */
  13. function poll_help($path, $arg) {
  14.   switch ($path) {
  15.     case 'admin/help#poll':
  16.       $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 receive feedback from community members.') .'</p>';
  17.       $output .= '<p>'. t('When creating a poll, enter the question being posed, as well as the potential choices (and beginning vote counts for each choice). The status and duration (length of time the poll remains active for new votes) can also be specified. Use the <a href="@poll">poll</a> menu item to view all current polls. To vote in or view the results of a specific poll, click on the poll itself.', array('@poll' => url('poll'))) .'</p>';
  18.       $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@poll">Poll module</a>.', array('@poll' => 'http://drupal.org/handbook/modules/poll/')) .'</p>';
  19.       return $output;
  20.   }
  21. }
  22.  
  23. /**
  24.  * Implementation of hook_init().
  25.  */
  26. function poll_init() {
  27.   drupal_add_css(drupal_get_path('module', 'poll') .'/poll.css');
  28. }
  29.  
  30. /**
  31.  * Implementation of hook_theme()
  32.  */
  33. function poll_theme() {
  34.   return array(
  35.     'poll_vote' => array(
  36.       'template' => 'poll-vote',
  37.       'arguments' => array('form' => NULL),
  38.     ),
  39.     'poll_choices' => array(
  40.       'arguments' => array('form' => NULL),
  41.     ),
  42.     'poll_results' => array(
  43.       'template' => 'poll-results',
  44.       'arguments' => array('raw_title' => NULL, 'results' => NULL, 'votes' => NULL, 'raw_links' => NULL, 'block' => NULL, 'nid' => NULL, 'vote' => NULL),
  45.     ),
  46.     'poll_bar' => array(
  47.       'template' => 'poll-bar',
  48.       'arguments' => array('title' => NULL, 'votes' => NULL, 'total_votes' => NULL, 'vote' => NULL, 'block' => NULL),
  49.     ),
  50.   );
  51. }
  52.  
  53. /**
  54.  * Implementation of hook_perm().
  55.  */
  56. function poll_perm() {
  57.   return array('create poll content', 'delete own poll content', 'delete any poll content', 'edit any poll content', 'edit own poll content', 'vote on polls', 'cancel own vote', 'inspect all votes');
  58. }
  59.  
  60. /**
  61.  * Implementation of hook_access().
  62.  */
  63. function poll_access($op, $node, $account) {
  64.   switch ($op) {
  65.     case 'create':
  66.       return user_access('create poll content', $account);
  67.     case 'update':
  68.       return user_access('edit any poll content', $account) || (user_access('edit own poll content', $account) && ($node->uid == $account->uid));
  69.     case 'delete':
  70.       return user_access('delete any poll content', $account) || (user_access('delete own poll content', $account) && ($node->uid == $account->uid));
  71.   }
  72. }
  73.  
  74. /**
  75.  * Implementation of hook_menu().
  76.  */
  77. function poll_menu() {
  78.   $items['poll'] = array(
  79.     'title' => 'Polls',
  80.     'page callback' => 'poll_page',
  81.     'access arguments' => array('access content'),
  82.     'type' => MENU_SUGGESTED_ITEM,
  83.     'file' => 'poll.pages.inc',
  84.   );
  85.  
  86.   $items['node/%node/votes'] = array(
  87.     'title' => 'Votes',
  88.     'page callback' => 'poll_votes',
  89.     'page arguments' => array(1),
  90.     'access callback' => '_poll_menu_access',
  91.     'access arguments' => array(1, 'inspect all votes', FALSE),
  92.     'weight' => 3,
  93.     'type' => MENU_LOCAL_TASK,
  94.     'file' => 'poll.pages.inc',
  95.   );
  96.  
  97.   $items['node/%node/results'] = array(
  98.     'title' => 'Results',
  99.     'page callback' => 'poll_results',
  100.     'page arguments' => array(1),
  101.     'access callback' => '_poll_menu_access',
  102.     'access arguments' => array(1, 'access content', TRUE),
  103.     'weight' => 3,
  104.     'type' => MENU_LOCAL_TASK,
  105.     'file' => 'poll.pages.inc',
  106.   );
  107.  
  108.   $items['poll/js'] = array(
  109.     'title' => 'Javascript Choice Form',
  110.     'page callback' => 'poll_choice_js',
  111.     'access arguments' => array('access content'),
  112.     'type' => MENU_CALLBACK,
  113.   );
  114.  
  115.   return $items;
  116. }
  117.  
  118. /**
  119.  * Callback function to see if a node is acceptable for poll menu items.
  120.  */
  121. function _poll_menu_access($node, $perm, $inspect_allowvotes) {
  122.   return user_access($perm) && ($node->type == 'poll') && ($node->allowvotes || !$inspect_allowvotes);
  123. }
  124.  
  125. /**
  126.  * Implementation of hook_block().
  127.  *
  128.  * Generates a block containing the latest poll.
  129.  */
  130. function poll_block($op = 'list', $delta = 0) {
  131.   if (user_access('access content')) {
  132.     if ($op == 'list') {
  133.       $blocks[0]['info'] = t('Most recent poll');
  134.       return $blocks;
  135.     }
  136.     else if ($op == 'view') {
  137.       // Retrieve the latest poll.
  138.       $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");
  139.       $timestamp = db_result(db_query($sql));
  140.       if ($timestamp) {
  141.         $poll = node_load(array('type' => 'poll', 'created' => $timestamp, 'status' => 1));
  142.  
  143.         if ($poll->nid) {
  144.           $poll = poll_view($poll, TRUE, FALSE, TRUE);
  145.         }
  146.       }
  147.       $block['subject'] = t('Poll');
  148.       $block['content'] = drupal_render($poll->content);
  149.       return $block;
  150.     }
  151.   }
  152. }
  153.  
  154. /**
  155.  * Implementation of hook_cron().
  156.  *
  157.  * Closes polls that have exceeded their allowed runtime.
  158.  */
  159. function poll_cron() {
  160.   $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');
  161.   while ($poll = db_fetch_object($result)) {
  162.     db_query("UPDATE {poll} SET active = 0 WHERE nid = %d", $poll->nid);
  163.   }
  164. }
  165.  
  166. /**
  167.  * Implementation of hook_node_info().
  168.  */
  169. function poll_node_info() {
  170.   return array(
  171.     'poll' => array(
  172.       'name' => t('Poll'),
  173.       'module' => 'poll',
  174.       'description' => t('A <em>poll</em> is a question with a set of possible responses. A <em>poll</em>, once created, automatically provides a simple running count of the number of votes received for each response.'),
  175.       'title_label' => t('Question'),
  176.       'has_body' => FALSE,
  177.     )
  178.   );
  179. }
  180.  
  181. /**
  182.  * Implementation of hook_form().
  183.  */
  184. function poll_form(&$node, $form_state) {
  185.   global $user;
  186.  
  187.   $admin = user_access('administer nodes') || user_access('edit any poll content') || (user_access('edit own poll content') && $user->uid == $node->uid);
  188.  
  189.   $type = node_get_types('type', $node);
  190.  
  191.   $form = array(
  192.     '#cache' => TRUE,
  193.   );
  194.  
  195.   $form['title'] = array(
  196.     '#type' => 'textfield',
  197.     '#title' => check_plain($type->title_label),
  198.     '#required' => TRUE,
  199.     '#default_value' => $node->title,
  200.     '#weight' => -5,
  201.   );
  202.  
  203.   if (isset($form_state['choice_count'])) {
  204.     $choice_count = $form_state['choice_count'];
  205.   }
  206.   else {
  207.     $choice_count = max(2, empty($node->choice) ? 2 : count($node->choice));
  208.   }
  209.  
  210.   // Add a wrapper for the choices and more button.
  211.   $form['choice_wrapper'] = array(
  212.     '#tree' => FALSE,
  213.     '#weight' => -4,
  214.     '#prefix' => '<div class="clear-block" id="poll-choice-wrapper">',
  215.     '#suffix' => '</div>',
  216.   );
  217.  
  218.   // Container for just the poll choices.
  219.   $form['choice_wrapper']['choice'] = array(
  220.     '#prefix' => '<div id="poll-choices">',
  221.     '#suffix' => '</div>',
  222.     '#theme' => 'poll_choices',
  223.   );
  224.  
  225.   // Add the current choices to the form.
  226.   for ($delta = 0; $delta < $choice_count; $delta++) {
  227.     $text = isset($node->choice[$delta]['chtext']) ? $node->choice[$delta]['chtext'] : '';
  228.     $votes = isset($node->choice[$delta]['chvotes']) ? $node->choice[$delta]['chvotes'] : 0;
  229.  
  230.     $form['choice_wrapper']['choice'][$delta] = _poll_choice_form($delta, $text, $votes);
  231.   }
  232.  
  233.   // We name our button 'poll_more' to avoid conflicts with other modules using
  234.   // AHAH-enabled buttons with the id 'more'.
  235.   $form['choice_wrapper']['poll_more'] = array(
  236.     '#type' => 'submit',
  237.     '#value' => t('More choices'),
  238.     '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),
  239.     '#weight' => 1,
  240.     '#submit' => array('poll_more_choices_submit'), // If no javascript action.
  241.     '#ahah' => array(
  242.       'path' => 'poll/js',
  243.       'wrapper' => 'poll-choices',
  244.       'method' => 'replace',
  245.       'effect' => 'fade',
  246.     ),
  247.   );
  248.  
  249.   // Poll attributes
  250.   $_duration = array(0 => t('Unlimited')) + drupal_map_assoc(array(86400, 172800, 345600, 604800, 1209600, 2419200, 4838400, 9676800, 31536000), "format_interval");
  251.   $_active = array(0 => t('Closed'), 1 => t('Active'));
  252.  
  253.   if ($admin) {
  254.     $form['settings'] = array(
  255.       '#type' => 'fieldset',
  256.       '#collapsible' => TRUE,
  257.       '#title' => t('Poll settings'),
  258.       '#weight' => -3,
  259.     );
  260.  
  261.     $form['settings']['active'] = array(
  262.       '#type' => 'radios',
  263.       '#title' => t('Poll status'),
  264.       '#default_value' => isset($node->active) ? $node->active : 1,
  265.       '#options' => $_active,
  266.       '#description' => t('When a poll is closed, visitors can no longer vote for it.')
  267.     );
  268.   }
  269.   $form['settings']['runtime'] = array(
  270.     '#type' => 'select',
  271.     '#title' => t('Poll duration'),
  272.     '#default_value' => isset($node->runtime) ? $node->runtime : 0,
  273.     '#options' => $_duration,
  274.     '#description' => t('After this period, the poll will be closed automatically.'),
  275.   );
  276.  
  277.   return $form;
  278. }
  279.  
  280. /**
  281.  * Submit handler to add more choices to a poll form. This handler is used when
  282.  * javascript is not available. It makes changes to the form state and the
  283.  * entire form is rebuilt during the page reload.
  284.  */
  285. function poll_more_choices_submit($form, &$form_state) {
  286.   // Set the form to rebuild and run submit handlers.
  287.   node_form_submit_build_node($form, $form_state);
  288.  
  289.   // Make the changes we want to the form state.
  290.   if ($form_state['values']['poll_more']) {
  291.     $form_state['choice_count'] = count($form_state['values']['choice']) + 5;
  292.   }
  293. }
  294.  
  295. function _poll_choice_form($delta, $value = '', $votes = 0) {
  296.   $admin = user_access('administer nodes');
  297.  
  298.   $form = array(
  299.     '#tree' => TRUE,
  300.   );
  301.  
  302.   // We'll manually set the #parents property of these fields so that
  303.   // their values appear in the $form_state['values']['choice'] array.
  304.   $form['chtext'] = array(
  305.     '#type' => 'textfield',
  306.     '#title' => t('Choice @n', array('@n' => ($delta + 1))),
  307.     '#default_value' => $value,
  308.     '#parents' => array('choice', $delta, 'chtext'),
  309.   );
  310.  
  311.   if ($admin) {
  312.     $form['chvotes'] = array(
  313.       '#type' => 'textfield',
  314.       '#title' => t('Votes for choice @n', array('@n' => ($delta + 1))),
  315.       '#default_value' => $votes,
  316.       '#size' => 5,
  317.       '#maxlength' => 7,
  318.       '#parents' => array('choice', $delta, 'chvotes'),
  319.     );
  320.   }
  321.  
  322.   return $form;
  323. }
  324.  
  325. /**
  326.  * Menu callback for AHAH additions.
  327.  */
  328. function poll_choice_js() {
  329.   $delta = count($_POST['choice']);
  330.  
  331.   // Build our new form element.
  332.   $form_element = _poll_choice_form($delta);
  333.   drupal_alter('form', $form_element, array(), 'poll_choice_js');
  334.  
  335.   // Build the new form.
  336.   $form_state = array('submitted' => FALSE);
  337.   $form_build_id = $_POST['form_build_id'];
  338.   // Add the new element to the stored form. Without adding the element to the
  339.   // form, Drupal is not aware of this new elements existence and will not
  340.   // process it. We retreive the cached form, add the element, and resave.
  341.   $form = form_get_cache($form_build_id, $form_state);
  342.   $form['choice_wrapper']['choice'][$delta] = $form_element;
  343.   form_set_cache($form_build_id, $form, $form_state);
  344.   $form += array(
  345.     '#post' => $_POST,
  346.     '#programmed' => FALSE,
  347.   );
  348.  
  349.   // Rebuild the form.
  350.   $form = form_builder('poll_node_form', $form, $form_state);
  351.  
  352.   // Render the new output.
  353.   $choice_form = $form['choice_wrapper']['choice'];
  354.   unset($choice_form['#prefix'], $choice_form['#suffix']); // Prevent duplicate wrappers.
  355.   $choice_form[$delta]['#attributes']['class'] = empty($choice_form[$delta]['#attributes']['class']) ? 'ahah-new-content' : $choice_form[$delta]['#attributes']['class'] .' ahah-new-content';
  356.   $choice_form[$delta]['chvotes']['#value'] = 0;
  357.   $output = theme('status_messages') . drupal_render($choice_form);
  358.  
  359.   drupal_json(array('status' => TRUE, 'data' => $output));
  360. }
  361.  
  362. /**
  363.  * Implementation of hook_submit().
  364.  */
  365. function poll_node_form_submit(&$form, &$form_state) {
  366.   // Renumber fields
  367.   $form_state['values']['choice'] = array_values($form_state['values']['choice']);
  368.   $form_state['values']['teaser'] = poll_teaser((object)$form_state['values']);
  369. }
  370.  
  371. /**
  372.  * Implementation of hook_validate().
  373.  */
  374. function poll_validate($node) {
  375.   if (isset($node->title)) {
  376.     // Check for at least two options and validate amount of votes:
  377.     $realchoices = 0;
  378.     // Renumber fields
  379.     $node->choice = array_values($node->choice);
  380.     foreach ($node->choice as $i => $choice) {
  381.       if ($choice['chtext'] != '') {
  382.         $realchoices++;
  383.       }
  384.       if (isset($choice['chvotes']) && $choice['chvotes'] < 0) {
  385.         form_set_error("choice][$i][chvotes", t('Negative values are not allowed.'));
  386.       }
  387.     }
  388.  
  389.     if ($realchoices < 2) {
  390.       form_set_error("choice][$realchoices][chtext", t('You must fill in at least two choices.'));
  391.     }
  392.   }
  393. }
  394.  
  395. /**
  396.  * Implementation of hook_load().
  397.  */
  398. function poll_load($node) {
  399.   global $user;
  400.  
  401.   $poll = db_fetch_object(db_query("SELECT runtime, active FROM {poll} WHERE nid = %d", $node->nid));
  402.  
  403.   // Load the appropriate choices into the $poll object.
  404.   $result = db_query("SELECT chtext, chvotes, chorder FROM {poll_choices} WHERE nid = %d ORDER BY chorder", $node->nid);
  405.   while ($choice = db_fetch_array($result)) {
  406.     $poll->choice[$choice['chorder']] = $choice;
  407.   }
  408.  
  409.   // Determine whether or not this user is allowed to vote.
  410.   $poll->allowvotes = FALSE;
  411.   if (user_access('vote on polls') && $poll->active) {
  412.     if ($user->uid) {
  413.       $result = db_fetch_object(db_query('SELECT chorder FROM {poll_votes} WHERE nid = %d AND uid = %d', $node->nid, $user->uid));
  414.     }
  415.     else {
  416.       $result = db_fetch_object(db_query("SELECT chorder FROM {poll_votes} WHERE nid = %d AND hostname = '%s'", $node->nid, ip_address()));
  417.     }
  418.     if (isset($result->chorder)) {
  419.       $poll->vote = $result->chorder;
  420.     }
  421.     else {
  422.       $poll->vote = -1;
  423.       $poll->allowvotes = TRUE;
  424.     }
  425.   }
  426.   return $poll;
  427. }
  428.  
  429. /**
  430.  * Implementation of hook_insert().
  431.  */
  432. function poll_insert($node) {
  433.   if (!user_access('administer nodes')) {
  434.     // Make sure all votes are 0 initially
  435.     foreach ($node->choice as $i => $choice) {
  436.       $node->choice[$i]['chvotes'] = 0;
  437.     }
  438.     $node->active = 1;
  439.   }
  440.  
  441.   db_query("INSERT INTO {poll} (nid, runtime, active) VALUES (%d, %d, %d)", $node->nid, $node->runtime, $node->active);
  442.  
  443.   $i = 0;
  444.   foreach ($node->choice as $choice) {
  445.     if ($choice['chtext'] != '') {
  446.       db_query("INSERT INTO {poll_choices} (nid, chtext, chvotes, chorder) VALUES (%d, '%s', %d, %d)", $node->nid, $choice['chtext'], $choice['chvotes'], $i++);
  447.     }
  448.   }
  449. }
  450.  
  451. /**
  452.  * Implementation of hook_update().
  453.  */
  454. function poll_update($node) {
  455.   // Update poll settings.
  456.   db_query('UPDATE {poll} SET runtime = %d, active = %d WHERE nid = %d', $node->runtime, $node->active, $node->nid);
  457.  
  458.   // Clean poll choices.
  459.   db_query('DELETE FROM {poll_choices} WHERE nid = %d', $node->nid);
  460.  
  461.   // Poll choices come in the same order with the same numbers as they are in
  462.   // the database, but some might have an empty title, which signifies that
  463.   // they should be removed. We remove all votes to the removed options, so
  464.   // people who voted on them can vote again.
  465.   $new_chorder = 0;
  466.   foreach ($node->choice as $old_chorder => $choice) {
  467.     $chvotes = isset($choice['chvotes']) ? (int)$choice['chvotes'] : 0;
  468.     $chtext = $choice['chtext'];
  469.  
  470.     if (!empty($chtext)) {
  471.       db_query("INSERT INTO {poll_choices} (nid, chtext, chvotes, chorder) VALUES (%d, '%s', %d, %d)", $node->nid, $chtext, $chvotes, $new_chorder);
  472.       if ($new_chorder != $old_chorder) {
  473.         // We can only remove items in the middle, not add, so
  474.         // new_chorder is always <= old_chorder, making this safe.
  475.         db_query("UPDATE {poll_votes} SET chorder = %d WHERE nid = %d AND chorder = %d", $new_chorder, $node->nid, $old_chorder);
  476.       }
  477.       $new_chorder++;
  478.     }
  479.     else {
  480.       db_query("DELETE FROM {poll_votes} WHERE nid = %d AND chorder = %d", $node->nid, $old_chorder);
  481.     }
  482.   }
  483. }
  484.  
  485. /**
  486.  * Implementation of hook_delete().
  487.  */
  488. function poll_delete($node) {
  489.   db_query("DELETE FROM {poll} WHERE nid = %d", $node->nid);
  490.   db_query("DELETE FROM {poll_choices} WHERE nid = %d", $node->nid);
  491.   db_query("DELETE FROM {poll_votes} WHERE nid = %d", $node->nid);
  492. }
  493.  
  494. /**
  495.  * Implementation of hook_view().
  496.  *
  497.  * @param $block
  498.  *   An extra parameter that adapts the hook to display a block-ready
  499.  *   rendering of the poll.
  500.  */
  501. function poll_view($node, $teaser = FALSE, $page = FALSE, $block = FALSE) {
  502.   global $user;
  503.   $output = '';
  504.  
  505.   // Special display for side-block
  506.   if ($block) {
  507.     // No 'read more' link
  508.     $node->readmore = FALSE;
  509.  
  510.     $links = module_invoke_all('link', 'node', $node, 1);
  511.     $links[] = array('title' => t('Older polls'), 'href' => 'poll', 'attributes' => array('title' => t('View the list of polls on this site.')));
  512.     if ($node->allowvotes && $block) {
  513.       $links[] = array('title' => t('Results'), 'href' => 'node/'. $node->nid .'/results', 'attributes' => array('title' => t('View the current poll results.')));
  514.     }
  515.  
  516.     $node->links = $links;
  517.   }
  518.  
  519.   if (!empty($node->allowvotes) && ($block || empty($node->show_results))) {
  520.     $node->content['body'] = array(
  521.       '#value' => drupal_get_form('poll_view_voting', $node, $block),
  522.     );
  523.   }
  524.   else {
  525.     $node->content['body'] = array(
  526.       '#value' => poll_view_results($node, $teaser, $page, $block),
  527.     );
  528.   }
  529.   return $node;
  530. }
  531.  
  532. /**
  533.  * Creates a simple teaser that lists all the choices.
  534.  *
  535.  * This is primarily used for RSS.
  536.  */
  537. function poll_teaser($node) {
  538.   $teaser = NULL;
  539.   if (is_array($node->choice)) {
  540.     foreach ($node->choice as $k => $choice) {
  541.       if ($choice['chtext'] != '') {
  542.         $teaser .= '* '. check_plain($choice['chtext']) ."\n";
  543.       }
  544.     }
  545.   }
  546.   return $teaser;
  547. }
  548.  
  549. /**
  550.  * Generates the voting form for a poll.
  551.  *
  552.  * @ingroup forms
  553.  * @see poll_vote()
  554.  * @see phptemplate_preprocess_poll_vote()
  555.  */
  556. function poll_view_voting(&$form_state, $node, $block) {
  557.   if ($node->choice) {
  558.     $list = array();
  559.     foreach ($node->choice as $i => $choice) {
  560.       $list[$i] = check_plain($choice['chtext']);
  561.     }
  562.     $form['choice'] = array(
  563.       '#type' => 'radios',
  564.       '#default_value' => -1,
  565.       '#options' => $list,
  566.     );
  567.   }
  568.  
  569.   $form['vote'] = array(
  570.     '#type' => 'submit',
  571.     '#value' => t('Vote'),
  572.     '#submit' => array('poll_vote'),
  573.   );
  574.  
  575.   // Store the node so we can get to it in submit functions.
  576.   $form['#node'] = $node;
  577.   $form['#block'] = $block;
  578.  
  579.   // Set form caching because we could have multiple of these forms on
  580.   // the same page, and we want to ensure the right one gets picked.
  581.   $form['#cache'] = TRUE;
  582.  
  583.   // Provide a more cleanly named voting form theme.
  584.   $form['#theme'] = 'poll_vote';
  585.   return $form;
  586. }
  587.  
  588. /**
  589.  * Validation function for processing votes
  590.  */
  591. function poll_view_voting_validate($form, &$form_state) {
  592.   if ($form_state['values']['choice'] == -1) {
  593.     form_set_error( 'choice', t('Your vote could not be recorded because you did not select any of the choices.'));
  594.   }
  595. }
  596.  
  597. /**
  598.  * Submit handler for processing a vote
  599.  */
  600. function poll_vote($form, &$form_state) {
  601.   $node = $form['#node'];
  602.   $choice = $form_state['values']['choice'];
  603.  
  604.   global $user;
  605.   if ($user->uid) {
  606.     db_query('INSERT INTO {poll_votes} (nid, chorder, uid) VALUES (%d, %d, %d)', $node->nid, $choice, $user->uid);
  607.   }
  608.   else {
  609.     db_query("INSERT INTO {poll_votes} (nid, chorder, hostname) VALUES (%d, %d, '%s')", $node->nid, $choice, ip_address());
  610.   }
  611.  
  612.   // Add one to the votes.
  613.   db_query("UPDATE {poll_choices} SET chvotes = chvotes + 1 WHERE nid = %d AND chorder = %d", $node->nid, $choice);
  614.  
  615.   cache_clear_all();
  616.   drupal_set_message(t('Your vote was recorded.'));
  617.  
  618.   // Return the user to whatever page they voted from.
  619. }
  620.  
  621. /**
  622.  * Themes the voting form for a poll.
  623.  *
  624.  * Inputs: $form
  625.  */
  626. function template_preprocess_poll_vote(&$variables) {
  627.   $form = $variables['form'];
  628.   $variables['choice'] = drupal_render($form['choice']);
  629.   $variables['title'] = check_plain($form['#node']->title);
  630.   $variables['vote'] = drupal_render($form['vote']);
  631.   $variables['rest'] = drupal_render($form);
  632.   $variables['block'] = $form['#block'];
  633.   // If this is a block, allow a different tpl.php to be used.
  634.   if ($variables['block']) {
  635.     $variables['template_files'][] = 'poll-vote-block';
  636.   }
  637. }
  638.  
  639. /**
  640.  * Generates a graphical representation of the results of a poll.
  641.  */
  642. function poll_view_results(&$node, $teaser, $page, $block) {
  643.   // Count the votes and find the maximum
  644.   $total_votes = 0;
  645.   $max_votes = 0;
  646.   foreach ($node->choice as $choice) {
  647.     if (isset($choice['chvotes'])) {
  648.       $total_votes += $choice['chvotes'];
  649.       $max_votes = max($max_votes, $choice['chvotes']);
  650.     }
  651.   }
  652.  
  653.   $poll_results = '';
  654.   foreach ($node->choice as $i => $choice) {
  655.     if (!empty($choice['chtext'])) {
  656.       $chvotes = isset($choice['chvotes']) ? $choice['chvotes'] : NULL;
  657.       $poll_results .= theme('poll_bar', $choice['chtext'], $chvotes, $total_votes, isset($node->vote) && $node->vote == $i, $block);
  658.     }
  659.   }
  660.  
  661.   return theme('poll_results', $node->title, $poll_results, $total_votes, isset($node->links) ? $node->links : array(), $block, $node->nid, isset($node->vote) ? $node->vote : NULL);
  662. }
  663.  
  664.  
  665. /**
  666.  * Theme the admin poll form for choices.
  667.  *
  668.  * @ingroup themeable
  669.  */
  670. function theme_poll_choices($form) {
  671.   // Change the button title to reflect the behavior when using JavaScript.
  672.   drupal_add_js('if (Drupal.jsEnabled) { $(document).ready(function() { $("#edit-poll-more").val("'. t('Add another choice') .'"); }); }', 'inline');
  673.  
  674.   $rows = array();
  675.   $headers = array(
  676.     t('Choice'),
  677.     t('Vote count'),
  678.   );
  679.  
  680.   foreach (element_children($form) as $key) {
  681.     // No need to print the field title every time.
  682.     unset($form[$key]['chtext']['#title'], $form[$key]['chvotes']['#title']);
  683.  
  684.     // Build the table row.
  685.     $row = array(
  686.       'data' => array(
  687.         array('data' => drupal_render($form[$key]['chtext']), 'class' => 'poll-chtext'),
  688.         array('data' => drupal_render($form[$key]['chvotes']), 'class' => 'poll-chvotes'),
  689.       ),
  690.     );
  691.  
  692.     // Add additional attributes to the row, such as a class for this row.
  693.     if (isset($form[$key]['#attributes'])) {
  694.       $row = array_merge($row, $form[$key]['#attributes']);
  695.     }
  696.     $rows[] = $row;
  697.   }
  698.  
  699.   $output = theme('table', $headers, $rows);
  700.   $output .= drupal_render($form);
  701.   return $output;
  702. }
  703.  
  704. /**
  705.  * Preprocess the poll_results theme hook.
  706.  *
  707.  * Inputs: $raw_title, $results, $votes, $raw_links, $block, $nid, $vote. The
  708.  * $raw_* inputs to this are naturally unsafe; often safe versions are
  709.  * made to simply overwrite the raw version, but in this case it seems likely
  710.  * that the title and the links may be overridden by the theme layer, so they
  711.  * are left in with a different name for that purpose.
  712.  *
  713.  * @see poll-results.tpl.php
  714.  * @see poll-results-block.tpl.php
  715.  * @see theme_poll_results()
  716.  */
  717. function template_preprocess_poll_results(&$variables) {
  718.   $variables['links'] = theme('links', $variables['raw_links']);
  719.   if (isset($variables['vote']) && $variables['vote'] > -1 && user_access('cancel own vote')) {
  720.     $variables['cancel_form'] = drupal_get_form('poll_cancel_form', $variables['nid']);
  721.   }
  722.   $variables['title'] = check_plain($variables['raw_title']);
  723.  
  724.   // If this is a block, allow a different tpl.php to be used.
  725.   if ($variables['block']) {
  726.     $variables['template_files'][] = 'poll-results-block';
  727.   }
  728. }
  729.  
  730. /**
  731.  * Preprocess the poll_bar theme hook.
  732.  *
  733.  * Inputs: $title, $votes, $total_votes, $voted, $block
  734.  *
  735.  * @see poll-bar.tpl.php
  736.  * @see poll-bar-block.tpl.php
  737.  * @see theme_poll_bar()
  738.  */
  739. function template_preprocess_poll_bar(&$variables) {
  740.   if ($variables['block']) {
  741.     $variables['template_files'][] = 'poll-bar-block';
  742.   }
  743.   $variables['title'] = check_plain($variables['title']);
  744.   $variables['percentage'] = round($variables['votes'] * 100 / max($variables['total_votes'], 1));
  745. }
  746.  
  747. /**
  748.  * Builds the cancel form for a poll.
  749.  *
  750.  * @ingroup forms
  751.  * @see poll_cancel()
  752.  */
  753. function poll_cancel_form(&$form_state, $nid) {
  754.   // Store the nid so we can get to it in submit functions.
  755.   $form['#nid'] = $nid;
  756.  
  757.   $form['submit'] = array(
  758.     '#type' => 'submit',
  759.     '#value' => t('Cancel your vote'),
  760.     '#submit' => array('poll_cancel')
  761.   );
  762.  
  763.   $form['#cache'] = TRUE;
  764.  
  765.   return $form;
  766. }
  767.  
  768. /**
  769.  * Submit callback for poll_cancel_form
  770.  */
  771. function poll_cancel($form, &$form_state) {
  772.   $node = node_load($form['#nid']);
  773.   global $user;
  774.  
  775.   if ($user->uid) {
  776.     db_query('DELETE FROM {poll_votes} WHERE nid = %d and uid = %d', $node->nid, $user->uid);
  777.   }
  778.   else {
  779.     db_query("DELETE FROM {poll_votes} WHERE nid = %d and hostname = '%s'", $node->nid, ip_address());
  780.   }
  781.  
  782.   // Subtract from the votes.
  783.   db_query("UPDATE {poll_choices} SET chvotes = chvotes - 1 WHERE nid = %d AND chorder = %d", $node->nid, $node->vote);
  784. }
  785.  
  786. /**
  787.  * Implementation of hook_user().
  788.  */
  789. function poll_user($op, &$edit, &$user) {
  790.   if ($op == 'delete') {
  791.     db_query('UPDATE {poll_votes} SET uid = 0 WHERE uid = %d', $user->uid);
  792.   }
  793. }
  794.