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