cms/drupal/modules/poll/poll.module
changeset 541 e756a8c72c3d
equal deleted inserted replaced
540:07239de796bb 541:e756a8c72c3d
       
     1 <?php
       
     2 
       
     3 /**
       
     4  * @file
       
     5  * Enables your site to capture votes on different topics in the form of multiple
       
     6  * choice questions.
       
     7  */
       
     8 
       
     9 /**
       
    10  * Implements hook_help().
       
    11  */
       
    12 function poll_help($path, $arg) {
       
    13   switch ($path) {
       
    14     case 'admin/help#poll':
       
    15       $output = '';
       
    16       $output .= '<h3>' . t('About') . '</h3>';
       
    17       $output .= '<p>' . t('The Poll module can be used to create simple surveys or questionnaires that display cumulative results. A poll is a good way to receive feedback from site users and community members. For more information, see the online handbook entry for the <a href="@poll">Poll module</a>.', array('@poll' => 'http://drupal.org/documentation/modules/poll/')) . '</p>';
       
    18       $output .= '<h3>' . t('Uses') . '</h3>';
       
    19       $output .= '<dl>';
       
    20       $output .= '<dt>' . t('Creating a poll') . '</dt>';
       
    21       $output .= '<dd>' . t('Users can create a poll by clicking on Poll on the <a href="@add-content">Add new content</a> page, and entering the question being posed, the answer choices, and beginning vote counts for each choice. The status (closed or active) and duration (length of time the poll remains active for new votes) can also be specified.', array('@add-content' => url('node/add'))) . '</dd>';
       
    22       $output .= '<dt>' . t('Viewing polls') . '</dt>';
       
    23       $output .= '<dd>' . t('You can visit the <a href="@poll">Polls</a> page to view all current polls, or alternately enable the <em>Most recent poll</em> block on the <a href="@blocks">Blocks administration page</a>. To vote in or view the results of a specific poll, you can click on the poll itself.', array('@poll' => url('poll'), '@blocks' => url('admin/structure/block'))) . '</dd>';
       
    24       $output .= '</dl>';
       
    25       return $output;
       
    26   }
       
    27 }
       
    28 
       
    29 /**
       
    30  * Implements hook_theme().
       
    31  */
       
    32 function poll_theme() {
       
    33   $theme_hooks = array(
       
    34     'poll_vote' => array(
       
    35       'template' => 'poll-vote',
       
    36       'render element' => 'form',
       
    37     ),
       
    38     'poll_choices' => array(
       
    39       'render element' => 'form',
       
    40     ),
       
    41     'poll_results' => array(
       
    42       'template' => 'poll-results',
       
    43       'variables' => array('raw_title' => NULL, 'results' => NULL, 'votes' => NULL, 'raw_links' => NULL, 'block' => NULL, 'nid' => NULL, 'vote' => NULL),
       
    44     ),
       
    45     'poll_bar' => array(
       
    46       'template' => 'poll-bar',
       
    47       'variables' => array('title' => NULL, 'votes' => NULL, 'total_votes' => NULL, 'vote' => NULL, 'block' => NULL),
       
    48     ),
       
    49   );
       
    50   // The theme system automatically discovers the theme's functions and
       
    51   // templates that implement more targeted "suggestions" of generic theme
       
    52   // hooks. But suggestions implemented by a module must be explicitly
       
    53   // registered.
       
    54   $theme_hooks += array(
       
    55     'poll_results__block' => array(
       
    56       'template' => 'poll-results--block',
       
    57       'variables' => $theme_hooks['poll_results']['variables'],
       
    58     ),
       
    59     'poll_bar__block' => array(
       
    60       'template' => 'poll-bar--block',
       
    61       'variables' => $theme_hooks['poll_bar']['variables'],
       
    62     ),
       
    63   );
       
    64   return $theme_hooks;
       
    65 }
       
    66 
       
    67 /**
       
    68  * Implements hook_permission().
       
    69  */
       
    70 function poll_permission() {
       
    71   $perms = array(
       
    72     'vote on polls' => array(
       
    73       'title' => t('Vote on polls'),
       
    74     ),
       
    75     'cancel own vote' => array(
       
    76       'title' => t('Cancel and change own votes'),
       
    77     ),
       
    78     'inspect all votes' => array(
       
    79       'title' => t('View details for all votes'),
       
    80     ),
       
    81   );
       
    82 
       
    83   return $perms;
       
    84 }
       
    85 
       
    86 /**
       
    87  * Implements hook_menu().
       
    88  */
       
    89 function poll_menu() {
       
    90   $items['poll'] = array(
       
    91     'title' => 'Polls',
       
    92     'page callback' => 'poll_page',
       
    93     'access arguments' => array('access content'),
       
    94     'type' => MENU_SUGGESTED_ITEM,
       
    95     'file' => 'poll.pages.inc',
       
    96   );
       
    97 
       
    98   $items['node/%node/votes'] = array(
       
    99     'title' => 'Votes',
       
   100     'page callback' => 'poll_votes',
       
   101     'page arguments' => array(1),
       
   102     'access callback' => '_poll_menu_access',
       
   103     'access arguments' => array(1, 'inspect all votes', FALSE),
       
   104     'weight' => 3,
       
   105     'type' => MENU_LOCAL_TASK,
       
   106     'file' => 'poll.pages.inc',
       
   107   );
       
   108 
       
   109   $items['node/%node/results'] = array(
       
   110     'title' => 'Results',
       
   111     'page callback' => 'poll_results',
       
   112     'page arguments' => array(1),
       
   113     'access callback' => '_poll_menu_access',
       
   114     'access arguments' => array(1, 'access content', TRUE),
       
   115     'weight' => 3,
       
   116     'type' => MENU_LOCAL_TASK,
       
   117     'file' => 'poll.pages.inc',
       
   118   );
       
   119 
       
   120   return $items;
       
   121 }
       
   122 
       
   123 /**
       
   124  * Callback function to see if a node is acceptable for poll menu items.
       
   125  */
       
   126 function _poll_menu_access($node, $perm, $inspect_allowvotes) {
       
   127   return user_access($perm) && ($node->type == 'poll') && ($node->allowvotes || !$inspect_allowvotes);
       
   128 }
       
   129 
       
   130 /**
       
   131  * Implements hook_block_info().
       
   132  */
       
   133 function poll_block_info() {
       
   134   $blocks['recent']['info'] = t('Most recent poll');
       
   135   $blocks['recent']['properties']['administrative'] = TRUE;
       
   136   return $blocks;
       
   137 }
       
   138 
       
   139 /**
       
   140  * Implements hook_block_view().
       
   141  *
       
   142  * Generates a block containing the latest poll.
       
   143  */
       
   144 function poll_block_view($delta = '') {
       
   145   if (user_access('access content')) {
       
   146     // Retrieve the latest poll.
       
   147     $select = db_select('node', 'n');
       
   148     $select->join('poll', 'p', 'p.nid = n.nid');
       
   149     $select->fields('n', array('nid'))
       
   150       ->condition('n.status', 1)
       
   151       ->condition('p.active', 1)
       
   152       ->orderBy('n.created', 'DESC')
       
   153       ->range(0, 1)
       
   154       ->addTag('node_access');
       
   155 
       
   156     $record = $select->execute()->fetchObject();
       
   157     if ($record) {
       
   158       $poll = node_load($record->nid);
       
   159       if ($poll->nid) {
       
   160         $poll = poll_block_latest_poll_view($poll);
       
   161         $block['subject'] = t('Poll');
       
   162         $block['content'] = $poll->content;
       
   163         return $block;
       
   164       }
       
   165     }
       
   166   }
       
   167 }
       
   168 
       
   169 /**
       
   170  * Implements hook_cron().
       
   171  *
       
   172  * Closes polls that have exceeded their allowed runtime.
       
   173  */
       
   174 function poll_cron() {
       
   175   $nids = db_query('SELECT p.nid FROM {poll} p INNER JOIN {node} n ON p.nid = n.nid WHERE (n.created + p.runtime) < :request_time AND p.active = :active AND p.runtime <> :runtime', array(':request_time' => REQUEST_TIME, ':active' => 1, ':runtime' => 0))->fetchCol();
       
   176   if (!empty($nids)) {
       
   177     db_update('poll')
       
   178       ->fields(array('active' => 0))
       
   179       ->condition('nid', $nids, 'IN')
       
   180       ->execute();
       
   181   }
       
   182 }
       
   183 
       
   184 /**
       
   185  * Implements hook_node_info().
       
   186  */
       
   187 function poll_node_info() {
       
   188   return array(
       
   189     'poll' => array(
       
   190       'name' => t('Poll'),
       
   191       'base' => 'poll',
       
   192       '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.'),
       
   193       'title_label' => t('Question'),
       
   194     )
       
   195   );
       
   196 }
       
   197 
       
   198 /**
       
   199  * Implements hook_field_extra_fields().
       
   200  */
       
   201 function poll_field_extra_fields() {
       
   202   $extra['node']['poll'] = array(
       
   203     'form' => array(
       
   204       'choice_wrapper' => array(
       
   205         'label' => t('Poll choices'),
       
   206         'description' => t('Poll choices'),
       
   207         'weight' => -4,
       
   208       ),
       
   209       'settings' => array(
       
   210         'label' => t('Poll settings'),
       
   211         'description' => t('Poll module settings'),
       
   212         'weight' => -3,
       
   213       ),
       
   214     ),
       
   215     'display' => array(
       
   216       'poll_view_voting' => array(
       
   217         'label' => t('Poll vote'),
       
   218         'description' => t('Poll vote'),
       
   219         'weight' => 0,
       
   220       ),
       
   221       'poll_view_results' => array(
       
   222         'label' => t('Poll results'),
       
   223         'description' => t('Poll results'),
       
   224         'weight' => 0,
       
   225       ),
       
   226     )
       
   227   );
       
   228 
       
   229   return $extra;
       
   230 }
       
   231 
       
   232 /**
       
   233  * Implements hook_form().
       
   234  */
       
   235 function poll_form($node, &$form_state) {
       
   236   global $user;
       
   237 
       
   238   $admin = user_access('bypass node access') || user_access('edit any poll content') || (user_access('edit own poll content') && $user->uid == $node->uid);
       
   239 
       
   240   $type = node_type_get_type($node);
       
   241 
       
   242   // The submit handlers to add more poll choices require that this form is
       
   243   // cached, regardless of whether Ajax is used.
       
   244   $form_state['cache'] = TRUE;
       
   245 
       
   246   $form['title'] = array(
       
   247     '#type' => 'textfield',
       
   248     '#title' => check_plain($type->title_label),
       
   249     '#required' => TRUE,
       
   250     '#default_value' => $node->title,
       
   251     '#maxlength' => 255,
       
   252     '#weight' => -5,
       
   253   );
       
   254 
       
   255   if (isset($form_state['choice_count'])) {
       
   256     $choice_count = $form_state['choice_count'];
       
   257   }
       
   258   else {
       
   259     $choice_count = max(2, empty($node->choice) ? 2 : count($node->choice));
       
   260   }
       
   261 
       
   262   // Add a wrapper for the choices and more button.
       
   263   $form['choice_wrapper'] = array(
       
   264     '#tree' => FALSE,
       
   265     '#weight' => -4,
       
   266     '#prefix' => '<div class="clearfix" id="poll-choice-wrapper">',
       
   267     '#suffix' => '</div>',
       
   268   );
       
   269 
       
   270   // Container for just the poll choices.
       
   271   $form['choice_wrapper']['choice'] = array(
       
   272     '#prefix' => '<div id="poll-choices">',
       
   273     '#suffix' => '</div>',
       
   274     '#theme' => 'poll_choices',
       
   275   );
       
   276 
       
   277   // Add the current choices to the form.
       
   278   $delta = 0;
       
   279   $weight = 0;
       
   280   if (isset($node->choice)) {
       
   281     $delta = count($node->choice);
       
   282     foreach ($node->choice as $chid => $choice) {
       
   283       $key = 'chid:' . $chid;
       
   284       $form['choice_wrapper']['choice'][$key] = _poll_choice_form($key, $choice['chid'], $choice['chtext'], $choice['chvotes'], $choice['weight'], $choice_count);
       
   285       $weight = max($choice['weight'], $weight);
       
   286     }
       
   287   }
       
   288 
       
   289   // Add initial or additional choices.
       
   290   $existing_delta = $delta;
       
   291   for ($delta; $delta < $choice_count; $delta++) {
       
   292     $key = 'new:' . ($delta - $existing_delta);
       
   293     // Increase the weight of each new choice.
       
   294     $weight++;
       
   295     $form['choice_wrapper']['choice'][$key] = _poll_choice_form($key, NULL, '', 0, $weight, $choice_count);
       
   296   }
       
   297 
       
   298   // We name our button 'poll_more' to avoid conflicts with other modules using
       
   299   // Ajax-enabled buttons with the id 'more'.
       
   300   $form['choice_wrapper']['poll_more'] = array(
       
   301     '#type' => 'submit',
       
   302     '#value' => t('More choices'),
       
   303     '#attributes' => array(
       
   304       'title' => t("If the amount of boxes above isn't enough, click here to add more choices."),
       
   305     ),
       
   306     '#weight' => 1,
       
   307     '#limit_validation_errors' => array(array('choice')),
       
   308     '#submit' => array('poll_more_choices_submit'),
       
   309     '#ajax' => array(
       
   310       'callback' => 'poll_choice_js',
       
   311       'wrapper' => 'poll-choices',
       
   312       'effect' => 'fade',
       
   313     ),
       
   314   );
       
   315 
       
   316   // Poll attributes
       
   317   $duration = array(
       
   318     // 1-6 days.
       
   319     86400, 2 * 86400, 3 * 86400, 4 * 86400, 5 * 86400, 6 * 86400,
       
   320     // 1-3 weeks (7 days).
       
   321     604800, 2 * 604800, 3 * 604800,
       
   322     // 1-3,6,9 months (30 days).
       
   323     2592000, 2 * 2592000, 3 * 2592000, 6 * 2592000, 9 * 2592000,
       
   324     // 1 year (365 days).
       
   325     31536000,
       
   326   );
       
   327   $duration = array(0 => t('Unlimited')) + drupal_map_assoc($duration, 'format_interval');
       
   328   $active = array(0 => t('Closed'), 1 => t('Active'));
       
   329 
       
   330   $form['settings'] = array(
       
   331     '#type' => 'fieldset',
       
   332     '#collapsible' => TRUE,
       
   333     '#title' => t('Poll settings'),
       
   334     '#weight' => -3,
       
   335     '#access' => $admin,
       
   336   );
       
   337 
       
   338   $form['settings']['active'] = array(
       
   339     '#type' => 'radios',
       
   340     '#title' => t('Poll status'),
       
   341     '#default_value' => isset($node->active) ? $node->active : 1,
       
   342     '#options' => $active,
       
   343     '#description' => t('When a poll is closed, visitors can no longer vote for it.'),
       
   344     '#access' => $admin,
       
   345   );
       
   346   $form['settings']['runtime'] = array(
       
   347     '#type' => 'select',
       
   348     '#title' => t('Poll duration'),
       
   349     '#default_value' => isset($node->runtime) ? $node->runtime : 0,
       
   350     '#options' => $duration,
       
   351     '#description' => t('After this period, the poll will be closed automatically.'),
       
   352   );
       
   353 
       
   354   return $form;
       
   355 }
       
   356 
       
   357 /**
       
   358  * Submit handler to add more choices to a poll form.
       
   359  *
       
   360  * This handler is run regardless of whether JS is enabled or not. It makes
       
   361  * changes to the form state. If the button was clicked with JS disabled, then
       
   362  * the page is reloaded with the complete rebuilt form. If the button was
       
   363  * clicked with JS enabled, then ajax_form_callback() calls poll_choice_js() to
       
   364  * return just the changed part of the form.
       
   365  */
       
   366 function poll_more_choices_submit($form, &$form_state) {
       
   367   // If this is a Ajax POST, add 1, otherwise add 5 more choices to the form.
       
   368   if ($form_state['values']['poll_more']) {
       
   369     $n = $_GET['q'] == 'system/ajax' ? 1 : 5;
       
   370     $form_state['choice_count'] = count($form_state['values']['choice']) + $n;
       
   371   }
       
   372   // Renumber the choices. This invalidates the corresponding key/value
       
   373   // associations in $form_state['input'], so clear that out. This requires
       
   374   // poll_form() to rebuild the choices with the values in
       
   375   // $form_state['node']->choice, which it does.
       
   376   $form_state['node']->choice = array_values($form_state['values']['choice']);
       
   377   unset($form_state['input']['choice']);
       
   378   $form_state['rebuild'] = TRUE;
       
   379 }
       
   380 
       
   381 function _poll_choice_form($key, $chid = NULL, $value = '', $votes = 0, $weight = 0, $size = 10) {
       
   382   $form = array(
       
   383     '#tree' => TRUE,
       
   384     '#weight' => $weight,
       
   385   );
       
   386 
       
   387   // We'll manually set the #parents property of these fields so that
       
   388   // their values appear in the $form_state['values']['choice'] array.
       
   389   $form['chid'] = array(
       
   390     '#type' => 'value',
       
   391     '#value' => $chid,
       
   392     '#parents' => array('choice', $key, 'chid'),
       
   393   );
       
   394 
       
   395   $form['chtext'] = array(
       
   396     '#type' => 'textfield',
       
   397     '#title' => $value !== '' ? t('Choice label') : t('New choice label'),
       
   398     '#title_display' => 'invisible',
       
   399     '#default_value' => $value,
       
   400     '#parents' => array('choice', $key, 'chtext'),
       
   401   );
       
   402 
       
   403   $form['chvotes'] = array(
       
   404     '#type' => 'textfield',
       
   405     '#title' => $value !== '' ? t('Vote count for choice @label', array('@label' => $value)) : t('Vote count for new choice'),
       
   406     '#title_display' => 'invisible',
       
   407     '#default_value' => $votes,
       
   408     '#size' => 5,
       
   409     '#maxlength' => 7,
       
   410     '#parents' => array('choice', $key, 'chvotes'),
       
   411     '#access' => user_access('administer nodes'),
       
   412     '#element_validate' => array('element_validate_integer'),
       
   413   );
       
   414 
       
   415   $form['weight'] = array(
       
   416     '#type' => 'weight',
       
   417     '#title' => $value !== '' ? t('Weight for choice @label', array('@label' => $value)) : t('Weight for new choice'),
       
   418     '#title_display' => 'invisible',
       
   419     '#default_value' => $weight,
       
   420     '#delta' => $size,
       
   421     '#parents' => array('choice', $key, 'weight'),
       
   422   );
       
   423 
       
   424   return $form;
       
   425 }
       
   426 
       
   427 /**
       
   428  * Ajax callback in response to new choices being added to the form.
       
   429  *
       
   430  * This returns the new page content to replace the page content made obsolete
       
   431  * by the form submission.
       
   432  *
       
   433  * @see poll_more_choices_submit()
       
   434  */
       
   435 function poll_choice_js($form, $form_state) {
       
   436   return $form['choice_wrapper']['choice'];
       
   437 }
       
   438 
       
   439 /**
       
   440  * Form submit handler for node_form().
       
   441  *
       
   442  * Upon preview and final submission, we need to renumber poll choices and
       
   443  * create a teaser output.
       
   444  */
       
   445 function poll_node_form_submit(&$form, &$form_state) {
       
   446   // Renumber choices.
       
   447   $form_state['values']['choice'] = array_values($form_state['values']['choice']);
       
   448   $form_state['values']['teaser'] = poll_teaser((object) $form_state['values']);
       
   449 }
       
   450 
       
   451 /**
       
   452  * Implements hook_validate().
       
   453  */
       
   454 function poll_validate($node, $form) {
       
   455   if (isset($node->title)) {
       
   456     // Check for at least two options and validate amount of votes.
       
   457     $realchoices = 0;
       
   458     foreach ($node->choice as $i => $choice) {
       
   459       if ($choice['chtext'] != '') {
       
   460         $realchoices++;
       
   461       }
       
   462       if (isset($choice['chvotes']) && $choice['chvotes'] < 0) {
       
   463         form_set_error("choice][$i][chvotes", t('Negative values are not allowed.'));
       
   464       }
       
   465     }
       
   466 
       
   467     if ($realchoices < 2) {
       
   468       form_set_error("choice][$realchoices][chtext", t('You must fill in at least two choices.'));
       
   469     }
       
   470   }
       
   471 }
       
   472 
       
   473 /**
       
   474  * Implements hook_field_attach_prepare_translation_alter().
       
   475  */
       
   476 function poll_field_attach_prepare_translation_alter(&$entity, $context) {
       
   477   if ($context['entity_type'] == 'node' && $entity->type == 'poll') {
       
   478     $entity->choice = $context['source_entity']->choice;
       
   479     foreach ($entity->choice as $i => $options) {
       
   480       $entity->choice[$i]['chvotes'] = 0;
       
   481     }
       
   482   }
       
   483 }
       
   484 
       
   485 /**
       
   486  * Implements hook_load().
       
   487  */
       
   488 function poll_load($nodes) {
       
   489   global $user;
       
   490   foreach ($nodes as $node) {
       
   491     $poll = db_query("SELECT runtime, active FROM {poll} WHERE nid = :nid", array(':nid' => $node->nid))->fetchObject();
       
   492 
       
   493     if (empty($poll)) {
       
   494       $poll = new stdClass();
       
   495     }
       
   496 
       
   497     // Load the appropriate choices into the $poll object.
       
   498     $poll->choice = db_select('poll_choice', 'c')
       
   499       ->addTag('translatable')
       
   500       ->fields('c', array('chid', 'chtext', 'chvotes', 'weight'))
       
   501       ->condition('c.nid', $node->nid)
       
   502       ->orderBy('weight')
       
   503       ->execute()->fetchAllAssoc('chid', PDO::FETCH_ASSOC);
       
   504 
       
   505     // Determine whether or not this user is allowed to vote.
       
   506     $poll->allowvotes = FALSE;
       
   507     if (user_access('vote on polls') && $poll->active) {
       
   508       if ($user->uid) {
       
   509         // If authenticated, find existing vote based on uid.
       
   510         $poll->vote = db_query('SELECT chid FROM {poll_vote} WHERE nid = :nid AND uid = :uid', array(':nid' => $node->nid, ':uid' => $user->uid))->fetchField();
       
   511         if (empty($poll->vote)) {
       
   512           $poll->vote = -1;
       
   513           $poll->allowvotes = TRUE;
       
   514         }
       
   515       }
       
   516       elseif (!empty($_SESSION['poll_vote'][$node->nid])) {
       
   517         // Otherwise the user is anonymous. Look for an existing vote in the
       
   518         // user's session.
       
   519         $poll->vote = $_SESSION['poll_vote'][$node->nid];
       
   520       }
       
   521       else {
       
   522         // Finally, query the database for an existing vote based on anonymous
       
   523         // user's hostname.
       
   524         $poll->allowvotes = !db_query("SELECT 1 FROM {poll_vote} WHERE nid = :nid AND hostname = :hostname AND uid = 0", array(':nid' => $node->nid, ':hostname' => ip_address()))->fetchField();
       
   525       }
       
   526     }
       
   527     foreach ($poll as $key => $value) {
       
   528       $nodes[$node->nid]->$key = $value;
       
   529     }
       
   530   }
       
   531 }
       
   532 
       
   533 /**
       
   534  * Implements hook_insert().
       
   535  */
       
   536 function poll_insert($node) {
       
   537   if (!user_access('administer nodes')) {
       
   538     // Make sure all votes are 0 initially
       
   539     foreach ($node->choice as $i => $choice) {
       
   540       $node->choice[$i]['chvotes'] = 0;
       
   541     }
       
   542     $node->active = 1;
       
   543   }
       
   544 
       
   545   db_insert('poll')
       
   546     ->fields(array(
       
   547       'nid' => $node->nid,
       
   548       'runtime' => $node->runtime,
       
   549       'active' => $node->active,
       
   550     ))
       
   551     ->execute();
       
   552 
       
   553   foreach ($node->choice as $choice) {
       
   554     if ($choice['chtext'] != '') {
       
   555       db_insert('poll_choice')
       
   556         ->fields(array(
       
   557           'nid' => $node->nid,
       
   558           'chtext' => $choice['chtext'],
       
   559           'chvotes' => $choice['chvotes'],
       
   560           'weight' => $choice['weight'],
       
   561         ))
       
   562         ->execute();
       
   563     }
       
   564   }
       
   565 }
       
   566 
       
   567 /**
       
   568  * Implements hook_update().
       
   569  */
       
   570 function poll_update($node) {
       
   571   // Update poll settings.
       
   572   db_update('poll')
       
   573     ->fields(array(
       
   574       'runtime' => $node->runtime,
       
   575       'active' => $node->active,
       
   576     ))
       
   577     ->condition('nid', $node->nid)
       
   578     ->execute();
       
   579 
       
   580   // Poll choices with empty titles signifies removal. We remove all votes to
       
   581   // the removed options, so people who voted on them can vote again.
       
   582   foreach ($node->choice as $key => $choice) {
       
   583     if (!empty($choice['chtext'])) {
       
   584       db_merge('poll_choice')
       
   585         ->key(array('chid' => $choice['chid']))
       
   586         ->fields(array(
       
   587           'chtext' => $choice['chtext'],
       
   588           'chvotes' => (int) $choice['chvotes'],
       
   589           'weight' => $choice['weight'],
       
   590         ))
       
   591         ->insertFields(array(
       
   592           'nid' => $node->nid,
       
   593           'chtext' => $choice['chtext'],
       
   594           'chvotes' => (int) $choice['chvotes'],
       
   595           'weight' => $choice['weight'],
       
   596         ))
       
   597         ->execute();
       
   598     }
       
   599     else {
       
   600       db_delete('poll_vote')
       
   601         ->condition('nid', $node->nid)
       
   602         ->condition('chid', $key)
       
   603         ->execute();
       
   604       db_delete('poll_choice')
       
   605         ->condition('nid', $node->nid)
       
   606         ->condition('chid', $choice['chid'])
       
   607         ->execute();
       
   608     }
       
   609   }
       
   610 }
       
   611 
       
   612 /**
       
   613  * Implements hook_delete().
       
   614  */
       
   615 function poll_delete($node) {
       
   616   db_delete('poll')
       
   617     ->condition('nid', $node->nid)
       
   618     ->execute();
       
   619   db_delete('poll_choice')
       
   620     ->condition('nid', $node->nid)
       
   621     ->execute();
       
   622   db_delete('poll_vote')
       
   623     ->condition('nid', $node->nid)
       
   624     ->execute();
       
   625 }
       
   626 
       
   627 /**
       
   628  * Return content for 'latest poll' block.
       
   629  *
       
   630  * @param $node
       
   631  *   The node object to load.
       
   632  */
       
   633 function poll_block_latest_poll_view($node) {
       
   634   // This is necessary for shared objects because PHP doesn't copy objects, but
       
   635   // passes them by reference.  So when the objects are cached it can result in
       
   636   // the wrong output being displayed on subsequent calls.  The cloning and
       
   637   // unsetting of $node->content prevents the block output from being the same
       
   638   // as the node output.
       
   639   $node = clone $node;
       
   640   unset($node->content);
       
   641 
       
   642   // No 'read more' link.
       
   643   $node->readmore = FALSE;
       
   644   $node->teaser = '';
       
   645 
       
   646   $links = array();
       
   647   $links[] = array('title' => t('Older polls'), 'href' => 'poll', 'attributes' => array('title' => t('View the list of polls on this site.')));
       
   648   if ($node->allowvotes) {
       
   649     $links[] = array('title' => t('Results'), 'href' => 'node/' . $node->nid . '/results', 'attributes' => array('title' => t('View the current poll results.')));
       
   650   }
       
   651 
       
   652   $node->links = $links;
       
   653 
       
   654   if (!empty($node->allowvotes)) {
       
   655     $node->content['poll_view_voting'] = drupal_get_form('poll_view_voting', $node, TRUE);
       
   656     $node->content['links'] = array(
       
   657       '#theme' => 'links',
       
   658       '#links' => $node->links,
       
   659       '#weight' => 5,
       
   660     );
       
   661   }
       
   662   else {
       
   663     $node->content['poll_view_results'] = array('#markup' => poll_view_results($node, TRUE, TRUE));
       
   664   }
       
   665 
       
   666   return $node;
       
   667 }
       
   668 
       
   669 
       
   670 /**
       
   671  * Implements hook_view().
       
   672  */
       
   673 function poll_view($node, $view_mode) {
       
   674   if (!empty($node->allowvotes) && empty($node->show_results)) {
       
   675     $node->content['poll_view_voting'] = drupal_get_form('poll_view_voting', $node);
       
   676   }
       
   677   else {
       
   678     $node->content['poll_view_results'] = array('#markup' => poll_view_results($node, $view_mode));
       
   679   }
       
   680   return $node;
       
   681 }
       
   682 
       
   683 /**
       
   684  * Creates a simple teaser that lists all the choices.
       
   685  *
       
   686  * This is primarily used for RSS.
       
   687  */
       
   688 function poll_teaser($node) {
       
   689   $teaser = NULL;
       
   690   if (is_array($node->choice)) {
       
   691     foreach ($node->choice as $choice) {
       
   692       if ($choice['chtext'] != '') {
       
   693         $teaser .= '* ' . check_plain($choice['chtext']) . "\n";
       
   694       }
       
   695     }
       
   696   }
       
   697   return $teaser;
       
   698 }
       
   699 
       
   700 /**
       
   701  * Generates the voting form for a poll.
       
   702  *
       
   703  * @ingroup forms
       
   704  * @see poll_vote()
       
   705  * @see phptemplate_preprocess_poll_vote()
       
   706  */
       
   707 function poll_view_voting($form, &$form_state, $node, $block = FALSE) {
       
   708   if ($node->choice) {
       
   709     $list = array();
       
   710     foreach ($node->choice as $i => $choice) {
       
   711       $list[$i] = check_plain($choice['chtext']);
       
   712     }
       
   713     $form['choice'] = array(
       
   714       '#type' => 'radios',
       
   715       '#title' => t('Choices'),
       
   716       '#title_display' => 'invisible',
       
   717       '#options' => $list,
       
   718     );
       
   719   }
       
   720 
       
   721   $form['vote'] = array(
       
   722     '#type' => 'submit',
       
   723     '#value' => t('Vote'),
       
   724     '#submit' => array('poll_vote'),
       
   725   );
       
   726 
       
   727   // Store the node so we can get to it in submit functions.
       
   728   $form['#node'] = $node;
       
   729   $form['#block'] = $block;
       
   730 
       
   731   // Set form caching because we could have multiple of these forms on
       
   732   // the same page, and we want to ensure the right one gets picked.
       
   733   $form_state['cache'] = TRUE;
       
   734 
       
   735   // Provide a more cleanly named voting form theme.
       
   736   $form['#theme'] = 'poll_vote';
       
   737   return $form;
       
   738 }
       
   739 
       
   740 /**
       
   741  * Validation function for processing votes
       
   742  */
       
   743 function poll_view_voting_validate($form, &$form_state) {
       
   744   if (empty($form_state['values']['choice'])) {
       
   745     form_set_error( 'choice', t('Your vote could not be recorded because you did not select any of the choices.'));
       
   746   }
       
   747 }
       
   748 
       
   749 /**
       
   750  * Submit handler for processing a vote.
       
   751  */
       
   752 function poll_vote($form, &$form_state) {
       
   753   $node = $form['#node'];
       
   754   $choice = $form_state['values']['choice'];
       
   755 
       
   756   global $user;
       
   757   db_insert('poll_vote')
       
   758     ->fields(array(
       
   759       'nid' => $node->nid,
       
   760       'chid' => $choice,
       
   761       'uid' => $user->uid,
       
   762       'hostname' => ip_address(),
       
   763       'timestamp' => REQUEST_TIME,
       
   764     ))
       
   765     ->execute();
       
   766 
       
   767   // Add one to the votes.
       
   768   db_update('poll_choice')
       
   769     ->expression('chvotes', 'chvotes + 1')
       
   770     ->condition('chid', $choice)
       
   771     ->execute();
       
   772 
       
   773   cache_clear_all();
       
   774 
       
   775   if (!$user->uid) {
       
   776     // The vote is recorded so the user gets the result view instead of the
       
   777     // voting form when viewing the poll. Saving a value in $_SESSION has the
       
   778     // convenient side effect of preventing the user from hitting the page
       
   779     // cache. When anonymous voting is allowed, the page cache should only
       
   780     // contain the voting form, not the results.
       
   781     $_SESSION['poll_vote'][$node->nid] = $choice;
       
   782   }
       
   783 
       
   784   drupal_set_message(t('Your vote was recorded.'));
       
   785 
       
   786   // Return the user to whatever page they voted from.
       
   787 }
       
   788 
       
   789 /**
       
   790  * Themes the voting form for a poll.
       
   791  *
       
   792  * Inputs: $form
       
   793  */
       
   794 function template_preprocess_poll_vote(&$variables) {
       
   795   $form = $variables['form'];
       
   796   $variables['choice'] = drupal_render($form['choice']);
       
   797   $variables['title'] = check_plain($form['#node']->title);
       
   798   $variables['vote'] = drupal_render($form['vote']);
       
   799   $variables['rest'] = drupal_render_children($form);
       
   800   $variables['block'] = $form['#block'];
       
   801   if ($variables['block']) {
       
   802     $variables['theme_hook_suggestions'][] = 'poll_vote__block';
       
   803   }
       
   804 }
       
   805 
       
   806 /**
       
   807  * Generates a graphical representation of the results of a poll.
       
   808  */
       
   809 function poll_view_results($node, $view_mode, $block = FALSE) {
       
   810   // Make sure that choices are ordered by their weight.
       
   811   uasort($node->choice, 'drupal_sort_weight');
       
   812 
       
   813   // Count the votes and find the maximum.
       
   814   $total_votes = 0;
       
   815   $max_votes = 0;
       
   816   foreach ($node->choice as $choice) {
       
   817     if (isset($choice['chvotes'])) {
       
   818       $total_votes += $choice['chvotes'];
       
   819       $max_votes = max($max_votes, $choice['chvotes']);
       
   820     }
       
   821   }
       
   822 
       
   823   $poll_results = '';
       
   824   foreach ($node->choice as $i => $choice) {
       
   825     if (!empty($choice['chtext'])) {
       
   826       $chvotes = isset($choice['chvotes']) ? $choice['chvotes'] : NULL;
       
   827       $poll_results .= theme('poll_bar', array('title' => $choice['chtext'], 'votes' => $chvotes, 'total_votes' => $total_votes, 'vote' => isset($node->vote) && $node->vote == $i, 'block' => $block));
       
   828     }
       
   829   }
       
   830 
       
   831   return theme('poll_results', array('raw_title' => $node->title, 'results' => $poll_results, 'votes' => $total_votes, 'raw_links' => isset($node->links) ? $node->links : array(), 'block' => $block, 'nid' => $node->nid, 'vote' => isset($node->vote) ? $node->vote : NULL));
       
   832 }
       
   833 
       
   834 
       
   835 /**
       
   836  * Returns HTML for an admin poll form for choices.
       
   837  *
       
   838  * @param $variables
       
   839  *   An associative array containing:
       
   840  *   - form: A render element representing the form.
       
   841  *
       
   842  * @ingroup themeable
       
   843  */
       
   844 function theme_poll_choices($variables) {
       
   845   $form = $variables['form'];
       
   846 
       
   847   drupal_add_tabledrag('poll-choice-table', 'order', 'sibling', 'poll-weight');
       
   848 
       
   849   $is_admin= user_access('administer nodes');
       
   850   $delta = 0;
       
   851   $rows = array();
       
   852   $headers = array('', t('Choice'));
       
   853   if ($is_admin) {
       
   854     $headers[] = t('Vote count');
       
   855   }
       
   856   $headers[] = t('Weight');
       
   857 
       
   858   foreach (element_children($form) as $key) {
       
   859     $delta++;
       
   860     // Set special classes for drag and drop updating.
       
   861     $form[$key]['weight']['#attributes']['class'] = array('poll-weight');
       
   862 
       
   863     // Build the table row.
       
   864     $row = array(
       
   865       'data' => array(
       
   866         array('class' => array('choice-flag')),
       
   867         drupal_render($form[$key]['chtext']),
       
   868       ),
       
   869       'class' => array('draggable'),
       
   870     );
       
   871     if ($is_admin) {
       
   872       $row['data'][] = drupal_render($form[$key]['chvotes']);
       
   873     }
       
   874     $row['data'][] = drupal_render($form[$key]['weight']);
       
   875 
       
   876     // Add any additional classes set on the row.
       
   877     if (!empty($form[$key]['#attributes']['class'])) {
       
   878       $row['class'] = array_merge($row['class'], $form[$key]['#attributes']['class']);
       
   879     }
       
   880 
       
   881     $rows[] = $row;
       
   882   }
       
   883 
       
   884   $output = theme('table', array('header' => $headers, 'rows' => $rows, 'attributes' => array('id' => 'poll-choice-table')));
       
   885   $output .= drupal_render_children($form);
       
   886   return $output;
       
   887 }
       
   888 
       
   889 /**
       
   890  * Preprocess the poll_results theme hook.
       
   891  *
       
   892  * Inputs: $raw_title, $results, $votes, $raw_links, $block, $nid, $vote. The
       
   893  * $raw_* inputs to this are naturally unsafe; often safe versions are
       
   894  * made to simply overwrite the raw version, but in this case it seems likely
       
   895  * that the title and the links may be overridden by the theme layer, so they
       
   896  * are left in with a different name for that purpose.
       
   897  *
       
   898  * @see poll-results.tpl.php
       
   899  * @see poll-results--block.tpl.php
       
   900  */
       
   901 function template_preprocess_poll_results(&$variables) {
       
   902   $variables['links'] = theme('links__poll_results', array('links' => $variables['raw_links']));
       
   903   if (isset($variables['vote']) && $variables['vote'] > -1 && user_access('cancel own vote')) {
       
   904     $elements = drupal_get_form('poll_cancel_form', $variables['nid']);
       
   905     $variables['cancel_form'] = drupal_render($elements);
       
   906   }
       
   907   $variables['title'] = check_plain($variables['raw_title']);
       
   908 
       
   909   if ($variables['block']) {
       
   910     $variables['theme_hook_suggestions'][] = 'poll_results__block';
       
   911   }
       
   912 }
       
   913 
       
   914 /**
       
   915  * Preprocess the poll_bar theme hook.
       
   916  *
       
   917  * Inputs: $title, $votes, $total_votes, $voted, $block
       
   918  *
       
   919  * @see poll-bar.tpl.php
       
   920  * @see poll-bar--block.tpl.php
       
   921  */
       
   922 function template_preprocess_poll_bar(&$variables) {
       
   923   if ($variables['block']) {
       
   924     $variables['theme_hook_suggestions'][] = 'poll_bar__block';
       
   925   }
       
   926   $variables['title'] = check_plain($variables['title']);
       
   927   $variables['percentage'] = round($variables['votes'] * 100 / max($variables['total_votes'], 1));
       
   928 }
       
   929 
       
   930 /**
       
   931  * Builds the cancel form for a poll.
       
   932  *
       
   933  * @ingroup forms
       
   934  * @see poll_cancel()
       
   935  */
       
   936 function poll_cancel_form($form, &$form_state, $nid) {
       
   937   $form_state['cache'] = TRUE;
       
   938 
       
   939   // Store the nid so we can get to it in submit functions.
       
   940   $form['#nid'] = $nid;
       
   941 
       
   942   $form['actions'] = array('#type' => 'actions');
       
   943   $form['actions']['submit'] = array(
       
   944     '#type' => 'submit',
       
   945     '#value' => t('Cancel your vote'),
       
   946     '#submit' => array('poll_cancel')
       
   947   );
       
   948 
       
   949   return $form;
       
   950 }
       
   951 
       
   952 /**
       
   953  * Submit callback for poll_cancel_form().
       
   954  */
       
   955 function poll_cancel($form, &$form_state) {
       
   956   global $user;
       
   957   $node = node_load($form['#nid']);
       
   958 
       
   959   db_delete('poll_vote')
       
   960     ->condition('nid', $node->nid)
       
   961     ->condition($user->uid ? 'uid' : 'hostname', $user->uid ? $user->uid : ip_address())
       
   962     ->execute();
       
   963 
       
   964   // Subtract from the votes.
       
   965   db_update('poll_choice')
       
   966     ->expression('chvotes', 'chvotes - 1')
       
   967     ->condition('chid', $node->vote)
       
   968     ->execute();
       
   969 
       
   970   unset($_SESSION['poll_vote'][$node->nid]);
       
   971 
       
   972   drupal_set_message(t('Your vote was cancelled.'));
       
   973 }
       
   974 
       
   975 /**
       
   976  * Implements hook_user_cancel().
       
   977  */
       
   978 function poll_user_cancel($edit, $account, $method) {
       
   979   switch ($method) {
       
   980     case 'user_cancel_reassign':
       
   981       db_update('poll_vote')
       
   982         ->fields(array('uid' => 0))
       
   983         ->condition('uid', $account->uid)
       
   984         ->execute();
       
   985       break;
       
   986   }
       
   987 }
       
   988 
       
   989 /**
       
   990  * Implements hook_user_delete().
       
   991  */
       
   992 function poll_user_delete($account) {
       
   993   db_delete('poll_vote')
       
   994     ->condition('uid', $account->uid)
       
   995     ->execute();
       
   996 }
       
   997 
       
   998 /**
       
   999  * Implements hook_rdf_mapping().
       
  1000  */
       
  1001 function poll_rdf_mapping() {
       
  1002   return array(
       
  1003     array(
       
  1004       'type' => 'node',
       
  1005       'bundle' => 'poll',
       
  1006       'mapping' => array(
       
  1007         'rdftype' => array('sioc:Post', 'sioct:Poll'),
       
  1008       ),
       
  1009     ),
       
  1010   );
       
  1011 }