poll.module

You are here

  1. 7 modules/poll/poll.module
  2. 4.6 modules/poll.module
  3. 4.7 modules/poll.module
  4. 5 modules/poll/poll.module
  5. 6 modules/poll/poll.module

Enables your site to capture votes on different topics in the form of multiple choice questions.

Functions

Namesort descending Description
poll_block_info Implements hook_block_info().
poll_block_latest_poll_view Return content for 'latest poll' block.
poll_block_view Implements hook_block_view().
poll_cancel Submit callback for poll_cancel_form().
poll_cancel_form Builds the cancel form for a poll.
poll_choice_js Ajax callback in response to new choices being added to the form.
poll_cron Implements hook_cron().
poll_delete Implements hook_delete().
poll_field_attach_prepare_translation_alter Implements hook_field_attach_prepare_translation_alter().
poll_field_extra_fields Implements hook_field_extra_fields().
poll_form Implements hook_form().
poll_help Implements hook_help().
poll_insert Implements hook_insert().
poll_load Implements hook_load().
poll_menu Implements hook_menu().
poll_more_choices_submit Submit handler to add more choices to a poll form.
poll_node_form_submit Form submit handler for node_form().
poll_node_info Implements hook_node_info().
poll_permission Implements hook_permission().
poll_rdf_mapping Implements hook_rdf_mapping().
poll_teaser Creates a simple teaser that lists all the choices.
poll_theme Implements hook_theme().
poll_update Implements hook_update().
poll_user_cancel Implements hook_user_cancel().
poll_user_delete Implements hook_user_delete().
poll_validate Implements hook_validate().
poll_view Implements hook_view().
poll_view_results Generates a graphical representation of the results of a poll.
poll_view_voting Generates the voting form for a poll.
poll_view_voting_validate Validation function for processing votes
poll_vote Submit handler for processing a vote.
template_preprocess_poll_bar Preprocess the poll_bar theme hook.
template_preprocess_poll_results Preprocess the poll_results theme hook.
template_preprocess_poll_vote Themes the voting form for a poll.
theme_poll_choices Returns HTML for an admin poll form for choices.
_poll_choice_form
_poll_menu_access Callback function to see if a node is acceptable for poll menu items.

File

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

Comments

What about multiple question polls?

As in situations where the user can choose 2 or 3 or n items in a poll. So instead of a binary radio button, the ability to check up to 'n' check boxes with 'n' configurable per poll.

Additionally, an ability to write-in a value is a need that my clients have so that while there would be fixed choices, there could be an 'other' where the poll would capture the typed in values and tally these variables as it does the other fixed values.

I absolutely second the idea of multiply choice and write-ins.