Projet

Général

Profil

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

root / drupal7 / modules / poll / poll.module @ b4adf10d

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
    '#maxlength' => 255,
253
    '#weight' => -5,
254
  );
255

    
256
  if (isset($form_state['choice_count'])) {
257
    $choice_count = $form_state['choice_count'];
258
  }
259
  else {
260
    $choice_count = max(2, empty($node->choice) ? 2 : count($node->choice));
261
  }
262

    
263
  // Add a wrapper for the choices and more button.
264
  $form['choice_wrapper'] = array(
265
    '#tree' => FALSE,
266
    '#weight' => -4,
267
    '#prefix' => '<div class="clearfix" id="poll-choice-wrapper">',
268
    '#suffix' => '</div>',
269
  );
270

    
271
  // Container for just the poll choices.
272
  $form['choice_wrapper']['choice'] = array(
273
    '#prefix' => '<div id="poll-choices">',
274
    '#suffix' => '</div>',
275
    '#theme' => 'poll_choices',
276
  );
277

    
278
  // Add the current choices to the form.
279
  $delta = 0;
280
  $weight = 0;
281
  if (isset($node->choice)) {
282
    $delta = count($node->choice);
283
    foreach ($node->choice as $chid => $choice) {
284
      $key = 'chid:' . $chid;
285
      $form['choice_wrapper']['choice'][$key] = _poll_choice_form($key, $choice['chid'], $choice['chtext'], $choice['chvotes'], $choice['weight'], $choice_count);
286
      $weight = max($choice['weight'], $weight);
287
    }
288
  }
289

    
290
  // Add initial or additional choices.
291
  $existing_delta = $delta;
292
  for ($delta; $delta < $choice_count; $delta++) {
293
    $key = 'new:' . ($delta - $existing_delta);
294
    // Increase the weight of each new choice.
295
    $weight++;
296
    $form['choice_wrapper']['choice'][$key] = _poll_choice_form($key, NULL, '', 0, $weight, $choice_count);
297
  }
298

    
299
  // We name our button 'poll_more' to avoid conflicts with other modules using
300
  // Ajax-enabled buttons with the id 'more'.
301
  $form['choice_wrapper']['poll_more'] = array(
302
    '#type' => 'submit',
303
    '#value' => t('More choices'),
304
    '#attributes' => array(
305
      'title' => t("If the amount of boxes above isn't enough, click here to add more choices."),
306
    ),
307
    '#weight' => 1,
308
    '#limit_validation_errors' => array(array('choice')),
309
    '#submit' => array('poll_more_choices_submit'),
310
    '#ajax' => array(
311
      'callback' => 'poll_choice_js',
312
      'wrapper' => 'poll-choices',
313
      'effect' => 'fade',
314
    ),
315
  );
316

    
317
  // Poll attributes
318
  $duration = array(
319
    // 1-6 days.
320
    86400, 2 * 86400, 3 * 86400, 4 * 86400, 5 * 86400, 6 * 86400,
321
    // 1-3 weeks (7 days).
322
    604800, 2 * 604800, 3 * 604800,
323
    // 1-3,6,9 months (30 days).
324
    2592000, 2 * 2592000, 3 * 2592000, 6 * 2592000, 9 * 2592000,
325
    // 1 year (365 days).
326
    31536000,
327
  );
328
  $duration = array(0 => t('Unlimited')) + drupal_map_assoc($duration, 'format_interval');
329
  $active = array(0 => t('Closed'), 1 => t('Active'));
330

    
331
  $form['settings'] = array(
332
    '#type' => 'fieldset',
333
    '#collapsible' => TRUE,
334
    '#title' => t('Poll settings'),
335
    '#weight' => -3,
336
    '#access' => $admin,
337
  );
338

    
339
  $form['settings']['active'] = array(
340
    '#type' => 'radios',
341
    '#title' => t('Poll status'),
342
    '#default_value' => isset($node->active) ? $node->active : 1,
343
    '#options' => $active,
344
    '#description' => t('When a poll is closed, visitors can no longer vote for it.'),
345
    '#access' => $admin,
346
  );
347
  $form['settings']['runtime'] = array(
348
    '#type' => 'select',
349
    '#title' => t('Poll duration'),
350
    '#default_value' => isset($node->runtime) ? $node->runtime : 0,
351
    '#options' => $duration,
352
    '#description' => t('After this period, the poll will be closed automatically.'),
353
  );
354

    
355
  return $form;
356
}
357

    
358
/**
359
 * Submit handler to add more choices to a poll form.
360
 *
361
 * This handler is run regardless of whether JS is enabled or not. It makes
362
 * changes to the form state. If the button was clicked with JS disabled, then
363
 * the page is reloaded with the complete rebuilt form. If the button was
364
 * clicked with JS enabled, then ajax_form_callback() calls poll_choice_js() to
365
 * return just the changed part of the form.
366
 */
367
function poll_more_choices_submit($form, &$form_state) {
368
  // If this is a Ajax POST, add 1, otherwise add 5 more choices to the form.
369
  if ($form_state['values']['poll_more']) {
370
    $n = $_GET['q'] == 'system/ajax' ? 1 : 5;
371
    $form_state['choice_count'] = count($form_state['values']['choice']) + $n;
372
  }
373
  // Renumber the choices. This invalidates the corresponding key/value
374
  // associations in $form_state['input'], so clear that out. This requires
375
  // poll_form() to rebuild the choices with the values in
376
  // $form_state['node']->choice, which it does.
377
  $form_state['node']->choice = array_values($form_state['values']['choice']);
378
  unset($form_state['input']['choice']);
379
  $form_state['rebuild'] = TRUE;
380
}
381

    
382
function _poll_choice_form($key, $chid = NULL, $value = '', $votes = 0, $weight = 0, $size = 10) {
383
  $form = array(
384
    '#tree' => TRUE,
385
    '#weight' => $weight,
386
  );
387

    
388
  // We'll manually set the #parents property of these fields so that
389
  // their values appear in the $form_state['values']['choice'] array.
390
  $form['chid'] = array(
391
    '#type' => 'value',
392
    '#value' => $chid,
393
    '#parents' => array('choice', $key, 'chid'),
394
  );
395

    
396
  $form['chtext'] = array(
397
    '#type' => 'textfield',
398
    '#title' => $value !== '' ? t('Choice label') : t('New choice label'),
399
    '#title_display' => 'invisible',
400
    '#default_value' => $value,
401
    '#parents' => array('choice', $key, 'chtext'),
402
  );
403

    
404
  $form['chvotes'] = array(
405
    '#type' => 'textfield',
406
    '#title' => $value !== '' ? t('Vote count for choice @label', array('@label' => $value)) : t('Vote count for new choice'),
407
    '#title_display' => 'invisible',
408
    '#default_value' => $votes,
409
    '#size' => 5,
410
    '#maxlength' => 7,
411
    '#parents' => array('choice', $key, 'chvotes'),
412
    '#access' => user_access('administer nodes'),
413
    '#element_validate' => array('element_validate_integer'),
414
  );
415

    
416
  $form['weight'] = array(
417
    '#type' => 'weight',
418
    '#title' => $value !== '' ? t('Weight for choice @label', array('@label' => $value)) : t('Weight for new choice'),
419
    '#title_display' => 'invisible',
420
    '#default_value' => $weight,
421
    '#delta' => $size,
422
    '#parents' => array('choice', $key, 'weight'),
423
  );
424

    
425
  return $form;
426
}
427

    
428
/**
429
 * Ajax callback in response to new choices being added to the form.
430
 *
431
 * This returns the new page content to replace the page content made obsolete
432
 * by the form submission.
433
 *
434
 * @see poll_more_choices_submit()
435
 */
436
function poll_choice_js($form, $form_state) {
437
  return $form['choice_wrapper']['choice'];
438
}
439

    
440
/**
441
 * Form submit handler for node_form().
442
 *
443
 * Upon preview and final submission, we need to renumber poll choices and
444
 * create a teaser output.
445
 */
446
function poll_node_form_submit(&$form, &$form_state) {
447
  // Renumber choices.
448
  $form_state['values']['choice'] = array_values($form_state['values']['choice']);
449
  $form_state['values']['teaser'] = poll_teaser((object) $form_state['values']);
450
}
451

    
452
/**
453
 * Implements hook_validate().
454
 */
455
function poll_validate($node, $form) {
456
  if (isset($node->title)) {
457
    // Check for at least two options and validate amount of votes.
458
    $realchoices = 0;
459
    foreach ($node->choice as $i => $choice) {
460
      if ($choice['chtext'] != '') {
461
        $realchoices++;
462
      }
463
      if (isset($choice['chvotes']) && $choice['chvotes'] < 0) {
464
        form_set_error("choice][$i][chvotes", t('Negative values are not allowed.'));
465
      }
466
    }
467

    
468
    if ($realchoices < 2) {
469
      form_set_error("choice][$realchoices][chtext", t('You must fill in at least two choices.'));
470
    }
471
  }
472
}
473

    
474
/**
475
 * Implements hook_field_attach_prepare_translation_alter().
476
 */
477
function poll_field_attach_prepare_translation_alter(&$entity, $context) {
478
  if ($context['entity_type'] == 'node' && $entity->type == 'poll') {
479
    $entity->choice = $context['source_entity']->choice;
480
    foreach ($entity->choice as $i => $options) {
481
      $entity->choice[$i]['chvotes'] = 0;
482
    }
483
  }
484
}
485

    
486
/**
487
 * Implements hook_load().
488
 */
489
function poll_load($nodes) {
490
  global $user;
491
  foreach ($nodes as $node) {
492
    $poll = db_query("SELECT runtime, active FROM {poll} WHERE nid = :nid", array(':nid' => $node->nid))->fetchObject();
493

    
494
    if (empty($poll)) {
495
      $poll = new stdClass();
496
    }
497

    
498
    // Load the appropriate choices into the $poll object.
499
    $poll->choice = db_select('poll_choice', 'c')
500
      ->addTag('translatable')
501
      ->fields('c', array('chid', 'chtext', 'chvotes', 'weight'))
502
      ->condition('c.nid', $node->nid)
503
      ->orderBy('weight')
504
      ->execute()->fetchAllAssoc('chid', PDO::FETCH_ASSOC);
505

    
506
    // Determine whether or not this user is allowed to vote.
507
    $poll->allowvotes = FALSE;
508
    if (user_access('vote on polls') && $poll->active) {
509
      if ($user->uid) {
510
        // If authenticated, find existing vote based on uid.
511
        $poll->vote = db_query('SELECT chid FROM {poll_vote} WHERE nid = :nid AND uid = :uid', array(':nid' => $node->nid, ':uid' => $user->uid))->fetchField();
512
        if (empty($poll->vote)) {
513
          $poll->vote = -1;
514
          $poll->allowvotes = TRUE;
515
        }
516
      }
517
      elseif (!empty($_SESSION['poll_vote'][$node->nid])) {
518
        // Otherwise the user is anonymous. Look for an existing vote in the
519
        // user's session.
520
        $poll->vote = $_SESSION['poll_vote'][$node->nid];
521
      }
522
      else {
523
        // Finally, query the database for an existing vote based on anonymous
524
        // user's hostname.
525
        $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();
526
      }
527
    }
528
    foreach ($poll as $key => $value) {
529
      $nodes[$node->nid]->$key = $value;
530
    }
531
  }
532
}
533

    
534
/**
535
 * Implements hook_insert().
536
 */
537
function poll_insert($node) {
538
  if (!user_access('administer nodes')) {
539
    // Make sure all votes are 0 initially
540
    foreach ($node->choice as $i => $choice) {
541
      $node->choice[$i]['chvotes'] = 0;
542
    }
543
    $node->active = 1;
544
  }
545

    
546
  db_insert('poll')
547
    ->fields(array(
548
      'nid' => $node->nid,
549
      'runtime' => $node->runtime,
550
      'active' => $node->active,
551
    ))
552
    ->execute();
553

    
554
  foreach ($node->choice as $choice) {
555
    if ($choice['chtext'] != '') {
556
      db_insert('poll_choice')
557
        ->fields(array(
558
          'nid' => $node->nid,
559
          'chtext' => $choice['chtext'],
560
          'chvotes' => $choice['chvotes'],
561
          'weight' => $choice['weight'],
562
        ))
563
        ->execute();
564
    }
565
  }
566
}
567

    
568
/**
569
 * Implements hook_update().
570
 */
571
function poll_update($node) {
572
  // Update poll settings.
573
  db_update('poll')
574
    ->fields(array(
575
      'runtime' => $node->runtime,
576
      'active' => $node->active,
577
    ))
578
    ->condition('nid', $node->nid)
579
    ->execute();
580

    
581
  // Poll choices with empty titles signifies removal. We remove all votes to
582
  // the removed options, so people who voted on them can vote again.
583
  foreach ($node->choice as $key => $choice) {
584
    if (!empty($choice['chtext'])) {
585
      db_merge('poll_choice')
586
        ->key(array('chid' => $choice['chid']))
587
        ->fields(array(
588
          'chtext' => $choice['chtext'],
589
          'chvotes' => (int) $choice['chvotes'],
590
          'weight' => $choice['weight'],
591
        ))
592
        ->insertFields(array(
593
          'nid' => $node->nid,
594
          'chtext' => $choice['chtext'],
595
          'chvotes' => (int) $choice['chvotes'],
596
          'weight' => $choice['weight'],
597
        ))
598
        ->execute();
599
    }
600
    else {
601
      db_delete('poll_vote')
602
        ->condition('nid', $node->nid)
603
        ->condition('chid', $key)
604
        ->execute();
605
      db_delete('poll_choice')
606
        ->condition('nid', $node->nid)
607
        ->condition('chid', $choice['chid'])
608
        ->execute();
609
    }
610
  }
611
}
612

    
613
/**
614
 * Implements hook_delete().
615
 */
616
function poll_delete($node) {
617
  db_delete('poll')
618
    ->condition('nid', $node->nid)
619
    ->execute();
620
  db_delete('poll_choice')
621
    ->condition('nid', $node->nid)
622
    ->execute();
623
  db_delete('poll_vote')
624
    ->condition('nid', $node->nid)
625
    ->execute();
626
}
627

    
628
/**
629
 * Return content for 'latest poll' block.
630
 *
631
 * @param $node
632
 *   The node object to load.
633
 */
634
function poll_block_latest_poll_view($node) {
635
  global $user;
636
  $output = '';
637

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

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

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

    
656
  $node->links = $links;
657

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

    
670
  return $node;
671
}
672

    
673

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

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

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

    
707
/**
708
 * Generates the voting form for a poll.
709
 *
710
 * @ingroup forms
711
 * @see poll_vote()
712
 * @see phptemplate_preprocess_poll_vote()
713
 */
714
function poll_view_voting($form, &$form_state, $node, $block = FALSE) {
715
  if ($node->choice) {
716
    $list = array();
717
    foreach ($node->choice as $i => $choice) {
718
      $list[$i] = check_plain($choice['chtext']);
719
    }
720
    $form['choice'] = array(
721
      '#type' => 'radios',
722
      '#title' => t('Choices'),
723
      '#title_display' => 'invisible',
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 (empty($form_state['values']['choice'])) {
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
 */
929
function template_preprocess_poll_bar(&$variables) {
930
  if ($variables['block']) {
931
    $variables['theme_hook_suggestions'][] = 'poll_bar__block';
932
  }
933
  $variables['title'] = check_plain($variables['title']);
934
  $variables['percentage'] = round($variables['votes'] * 100 / max($variables['total_votes'], 1));
935
}
936

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

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

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

    
956
  return $form;
957
}
958

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

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

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

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

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

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

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

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