Project

General

Profile

Paste
Download (30.1 KB) Statistics
| Branch: | Revision:

root / drupal7 / modules / poll / poll.module @ 582db59d

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
  global $user;
635
  $output = '';
636

    
637
  // This is necessary for shared objects because PHP doesn't copy objects, but
638
  // passes them by reference.  So when the objects are cached it can result in
639
  // the wrong output being displayed on subsequent calls.  The cloning and
640
  // unsetting of $node->content prevents the block output from being the same
641
  // as the node output.
642
  $node = clone $node;
643
  unset($node->content);
644

    
645
  // No 'read more' link.
646
  $node->readmore = FALSE;
647
  $node->teaser = '';
648

    
649
  $links = array();
650
  $links[] = array('title' => t('Older polls'), 'href' => 'poll', 'attributes' => array('title' => t('View the list of polls on this site.')));
651
  if ($node->allowvotes) {
652
    $links[] = array('title' => t('Results'), 'href' => 'node/' . $node->nid . '/results', 'attributes' => array('title' => t('View the current poll results.')));
653
  }
654

    
655
  $node->links = $links;
656

    
657
  if (!empty($node->allowvotes)) {
658
    $node->content['poll_view_voting'] = drupal_get_form('poll_view_voting', $node, TRUE);
659
    $node->content['links'] = array(
660
      '#theme' => 'links',
661
      '#links' => $node->links,
662
      '#weight' => 5,
663
    );
664
  }
665
  else {
666
    $node->content['poll_view_results'] = array('#markup' => poll_view_results($node, TRUE, TRUE));
667
  }
668

    
669
  return $node;
670
}
671

    
672

    
673
/**
674
 * Implements hook_view().
675
 */
676
function poll_view($node, $view_mode) {
677
  global $user;
678
  $output = '';
679

    
680
  if (!empty($node->allowvotes) && empty($node->show_results)) {
681
    $node->content['poll_view_voting'] = drupal_get_form('poll_view_voting', $node);
682
  }
683
  else {
684
    $node->content['poll_view_results'] = array('#markup' => poll_view_results($node, $view_mode));
685
  }
686
  return $node;
687
}
688

    
689
/**
690
 * Creates a simple teaser that lists all the choices.
691
 *
692
 * This is primarily used for RSS.
693
 */
694
function poll_teaser($node) {
695
  $teaser = NULL;
696
  if (is_array($node->choice)) {
697
    foreach ($node->choice as $k => $choice) {
698
      if ($choice['chtext'] != '') {
699
        $teaser .= '* ' . check_plain($choice['chtext']) . "\n";
700
      }
701
    }
702
  }
703
  return $teaser;
704
}
705

    
706
/**
707
 * Generates the voting form for a poll.
708
 *
709
 * @ingroup forms
710
 * @see poll_vote()
711
 * @see phptemplate_preprocess_poll_vote()
712
 */
713
function poll_view_voting($form, &$form_state, $node, $block = FALSE) {
714
  if ($node->choice) {
715
    $list = array();
716
    foreach ($node->choice as $i => $choice) {
717
      $list[$i] = check_plain($choice['chtext']);
718
    }
719
    $form['choice'] = array(
720
      '#type' => 'radios',
721
      '#title' => t('Choices'),
722
      '#title_display' => 'invisible',
723
      '#options' => $list,
724
    );
725
  }
726

    
727
  $form['vote'] = array(
728
    '#type' => 'submit',
729
    '#value' => t('Vote'),
730
    '#submit' => array('poll_vote'),
731
  );
732

    
733
  // Store the node so we can get to it in submit functions.
734
  $form['#node'] = $node;
735
  $form['#block'] = $block;
736

    
737
  // Set form caching because we could have multiple of these forms on
738
  // the same page, and we want to ensure the right one gets picked.
739
  $form_state['cache'] = TRUE;
740

    
741
  // Provide a more cleanly named voting form theme.
742
  $form['#theme'] = 'poll_vote';
743
  return $form;
744
}
745

    
746
/**
747
 * Validation function for processing votes
748
 */
749
function poll_view_voting_validate($form, &$form_state) {
750
  if (empty($form_state['values']['choice'])) {
751
    form_set_error( 'choice', t('Your vote could not be recorded because you did not select any of the choices.'));
752
  }
753
}
754

    
755
/**
756
 * Submit handler for processing a vote.
757
 */
758
function poll_vote($form, &$form_state) {
759
  $node = $form['#node'];
760
  $choice = $form_state['values']['choice'];
761

    
762
  global $user;
763
  db_insert('poll_vote')
764
    ->fields(array(
765
      'nid' => $node->nid,
766
      'chid' => $choice,
767
      'uid' => $user->uid,
768
      'hostname' => ip_address(),
769
      'timestamp' => REQUEST_TIME,
770
    ))
771
    ->execute();
772

    
773
  // Add one to the votes.
774
  db_update('poll_choice')
775
    ->expression('chvotes', 'chvotes + 1')
776
    ->condition('chid', $choice)
777
    ->execute();
778

    
779
  cache_clear_all();
780

    
781
  if (!$user->uid) {
782
    // The vote is recorded so the user gets the result view instead of the
783
    // voting form when viewing the poll. Saving a value in $_SESSION has the
784
    // convenient side effect of preventing the user from hitting the page
785
    // cache. When anonymous voting is allowed, the page cache should only
786
    // contain the voting form, not the results.
787
    $_SESSION['poll_vote'][$node->nid] = $choice;
788
  }
789

    
790
  drupal_set_message(t('Your vote was recorded.'));
791

    
792
  // Return the user to whatever page they voted from.
793
}
794

    
795
/**
796
 * Themes the voting form for a poll.
797
 *
798
 * Inputs: $form
799
 */
800
function template_preprocess_poll_vote(&$variables) {
801
  $form = $variables['form'];
802
  $variables['choice'] = drupal_render($form['choice']);
803
  $variables['title'] = check_plain($form['#node']->title);
804
  $variables['vote'] = drupal_render($form['vote']);
805
  $variables['rest'] = drupal_render_children($form);
806
  $variables['block'] = $form['#block'];
807
  if ($variables['block']) {
808
    $variables['theme_hook_suggestions'][] = 'poll_vote__block';
809
  }
810
}
811

    
812
/**
813
 * Generates a graphical representation of the results of a poll.
814
 */
815
function poll_view_results($node, $view_mode, $block = FALSE) {
816
  // Make sure that choices are ordered by their weight.
817
  uasort($node->choice, 'drupal_sort_weight');
818

    
819
  // Count the votes and find the maximum.
820
  $total_votes = 0;
821
  $max_votes = 0;
822
  foreach ($node->choice as $choice) {
823
    if (isset($choice['chvotes'])) {
824
      $total_votes += $choice['chvotes'];
825
      $max_votes = max($max_votes, $choice['chvotes']);
826
    }
827
  }
828

    
829
  $poll_results = '';
830
  foreach ($node->choice as $i => $choice) {
831
    if (!empty($choice['chtext'])) {
832
      $chvotes = isset($choice['chvotes']) ? $choice['chvotes'] : NULL;
833
      $poll_results .= theme('poll_bar', array('title' => $choice['chtext'], 'votes' => $chvotes, 'total_votes' => $total_votes, 'vote' => isset($node->vote) && $node->vote == $i, 'block' => $block));
834
    }
835
  }
836

    
837
  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));
838
}
839

    
840

    
841
/**
842
 * Returns HTML for an admin poll form for choices.
843
 *
844
 * @param $variables
845
 *   An associative array containing:
846
 *   - form: A render element representing the form.
847
 *
848
 * @ingroup themeable
849
 */
850
function theme_poll_choices($variables) {
851
  $form = $variables['form'];
852

    
853
  drupal_add_tabledrag('poll-choice-table', 'order', 'sibling', 'poll-weight');
854

    
855
  $is_admin= user_access('administer nodes');
856
  $delta = 0;
857
  $rows = array();
858
  $headers = array('', t('Choice'));
859
  if ($is_admin) {
860
    $headers[] = t('Vote count');
861
  }
862
  $headers[] = t('Weight');
863

    
864
  foreach (element_children($form) as $key) {
865
    $delta++;
866
    // Set special classes for drag and drop updating.
867
    $form[$key]['weight']['#attributes']['class'] = array('poll-weight');
868

    
869
    // Build the table row.
870
    $row = array(
871
      'data' => array(
872
        array('class' => array('choice-flag')),
873
        drupal_render($form[$key]['chtext']),
874
      ),
875
      'class' => array('draggable'),
876
    );
877
    if ($is_admin) {
878
      $row['data'][] = drupal_render($form[$key]['chvotes']);
879
    }
880
    $row['data'][] = drupal_render($form[$key]['weight']);
881

    
882
    // Add any additional classes set on the row.
883
    if (!empty($form[$key]['#attributes']['class'])) {
884
      $row['class'] = array_merge($row['class'], $form[$key]['#attributes']['class']);
885
    }
886

    
887
    $rows[] = $row;
888
  }
889

    
890
  $output = theme('table', array('header' => $headers, 'rows' => $rows, 'attributes' => array('id' => 'poll-choice-table')));
891
  $output .= drupal_render_children($form);
892
  return $output;
893
}
894

    
895
/**
896
 * Preprocess the poll_results theme hook.
897
 *
898
 * Inputs: $raw_title, $results, $votes, $raw_links, $block, $nid, $vote. The
899
 * $raw_* inputs to this are naturally unsafe; often safe versions are
900
 * made to simply overwrite the raw version, but in this case it seems likely
901
 * that the title and the links may be overridden by the theme layer, so they
902
 * are left in with a different name for that purpose.
903
 *
904
 * @see poll-results.tpl.php
905
 * @see poll-results--block.tpl.php
906
 */
907
function template_preprocess_poll_results(&$variables) {
908
  $variables['links'] = theme('links__poll_results', array('links' => $variables['raw_links']));
909
  if (isset($variables['vote']) && $variables['vote'] > -1 && user_access('cancel own vote')) {
910
    $elements = drupal_get_form('poll_cancel_form', $variables['nid']);
911
    $variables['cancel_form'] = drupal_render($elements);
912
  }
913
  $variables['title'] = check_plain($variables['raw_title']);
914

    
915
  if ($variables['block']) {
916
    $variables['theme_hook_suggestions'][] = 'poll_results__block';
917
  }
918
}
919

    
920
/**
921
 * Preprocess the poll_bar theme hook.
922
 *
923
 * Inputs: $title, $votes, $total_votes, $voted, $block
924
 *
925
 * @see poll-bar.tpl.php
926
 * @see poll-bar--block.tpl.php
927
 */
928
function template_preprocess_poll_bar(&$variables) {
929
  if ($variables['block']) {
930
    $variables['theme_hook_suggestions'][] = 'poll_bar__block';
931
  }
932
  $variables['title'] = check_plain($variables['title']);
933
  $variables['percentage'] = round($variables['votes'] * 100 / max($variables['total_votes'], 1));
934
}
935

    
936
/**
937
 * Builds the cancel form for a poll.
938
 *
939
 * @ingroup forms
940
 * @see poll_cancel()
941
 */
942
function poll_cancel_form($form, &$form_state, $nid) {
943
  $form_state['cache'] = TRUE;
944

    
945
  // Store the nid so we can get to it in submit functions.
946
  $form['#nid'] = $nid;
947

    
948
  $form['actions'] = array('#type' => 'actions');
949
  $form['actions']['submit'] = array(
950
    '#type' => 'submit',
951
    '#value' => t('Cancel your vote'),
952
    '#submit' => array('poll_cancel')
953
  );
954

    
955
  return $form;
956
}
957

    
958
/**
959
 * Submit callback for poll_cancel_form().
960
 */
961
function poll_cancel($form, &$form_state) {
962
  global $user;
963
  $node = node_load($form['#nid']);
964

    
965
  db_delete('poll_vote')
966
    ->condition('nid', $node->nid)
967
    ->condition($user->uid ? 'uid' : 'hostname', $user->uid ? $user->uid : ip_address())
968
    ->execute();
969

    
970
  // Subtract from the votes.
971
  db_update('poll_choice')
972
    ->expression('chvotes', 'chvotes - 1')
973
    ->condition('chid', $node->vote)
974
    ->execute();
975

    
976
  unset($_SESSION['poll_vote'][$node->nid]);
977

    
978
  drupal_set_message(t('Your vote was cancelled.'));
979
}
980

    
981
/**
982
 * Implements hook_user_cancel().
983
 */
984
function poll_user_cancel($edit, $account, $method) {
985
  switch ($method) {
986
    case 'user_cancel_reassign':
987
      db_update('poll_vote')
988
        ->fields(array('uid' => 0))
989
        ->condition('uid', $account->uid)
990
        ->execute();
991
      break;
992
  }
993
}
994

    
995
/**
996
 * Implements hook_user_delete().
997
 */
998
function poll_user_delete($account) {
999
  db_delete('poll_vote')
1000
    ->condition('uid', $account->uid)
1001
    ->execute();
1002
}
1003

    
1004
/**
1005
 * Implements hook_rdf_mapping().
1006
 */
1007
function poll_rdf_mapping() {
1008
  return array(
1009
    array(
1010
      'type' => 'node',
1011
      'bundle' => 'poll',
1012
      'mapping' => array(
1013
        'rdftype' => array('sioc:Post', 'sioct:Poll'),
1014
      ),
1015
    ),
1016
  );
1017
}