source: sipes/cord/modules/poll/poll.module @ b354002

stableversion-3.0
Last change on this file since b354002 was b354002, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se agrego el directorio del cord

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