Projet

Général

Profil

Paste
Télécharger (30,1 ko) Statistiques
| Branche: | Révision:

root / htmltest / modules / poll / poll.module @ 85ad3d82

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
      'has_body' => FALSE,
195
    )
196
  );
197
}
198

    
199
/**
200
 * Implements hook_field_extra_fields().
201
 */
202
function poll_field_extra_fields() {
203
  $extra['node']['poll'] = array(
204
    'form' => array(
205
      'choice_wrapper' => array(
206
        'label' => t('Poll choices'),
207
        'description' => t('Poll choices'),
208
        'weight' => -4,
209
      ),
210
      'settings' => array(
211
        'label' => t('Poll settings'),
212
        'description' => t('Poll module settings'),
213
        'weight' => -3,
214
      ),
215
    ),
216
    'display' => array(
217
      'poll_view_voting' => array(
218
        'label' => t('Poll vote'),
219
        'description' => t('Poll vote'),
220
        'weight' => 0,
221
      ),
222
      'poll_view_results' => array(
223
        'label' => t('Poll results'),
224
        'description' => t('Poll results'),
225
        'weight' => 0,
226
      ),
227
    )
228
  );
229

    
230
  return $extra;
231
}
232

    
233
/**
234
 * Implements hook_form().
235
 */
236
function poll_form($node, &$form_state) {
237
  global $user;
238

    
239
  $admin = user_access('bypass node access') || user_access('edit any poll content') || (user_access('edit own poll content') && $user->uid == $node->uid);
240

    
241
  $type = node_type_get_type($node);
242

    
243
  // The submit handlers to add more poll choices require that this form is
244
  // cached, regardless of whether Ajax is used.
245
  $form_state['cache'] = TRUE;
246

    
247
  $form['title'] = array(
248
    '#type' => 'textfield',
249
    '#title' => check_plain($type->title_label),
250
    '#required' => TRUE,
251
    '#default_value' => $node->title,
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
      '#default_value' => -1,
724
      '#options' => $list,
725
    );
726
  }
727

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

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

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

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

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

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

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

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

    
780
  cache_clear_all();
781

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

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

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

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

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

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

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

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

    
841

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
957
  return $form;
958
}
959

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

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

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

    
978
  unset($_SESSION['poll_vote'][$node->nid]);
979

    
980
  drupal_set_message(t('Your vote was cancelled.'));
981
}
982

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

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

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