poll.module 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. '#maxlength' => 255,
  231. '#weight' => -5,
  232. );
  233. if (isset($form_state['choice_count'])) {
  234. $choice_count = $form_state['choice_count'];
  235. }
  236. else {
  237. $choice_count = max(2, empty($node->choice) ? 2 : count($node->choice));
  238. }
  239. // Add a wrapper for the choices and more button.
  240. $form['choice_wrapper'] = array(
  241. '#tree' => FALSE,
  242. '#weight' => -4,
  243. '#prefix' => '<div class="clearfix" id="poll-choice-wrapper">',
  244. '#suffix' => '</div>',
  245. );
  246. // Container for just the poll choices.
  247. $form['choice_wrapper']['choice'] = array(
  248. '#prefix' => '<div id="poll-choices">',
  249. '#suffix' => '</div>',
  250. '#theme' => 'poll_choices',
  251. );
  252. // Add the current choices to the form.
  253. $delta = 0;
  254. $weight = 0;
  255. if (isset($node->choice)) {
  256. $delta = count($node->choice);
  257. foreach ($node->choice as $chid => $choice) {
  258. $key = 'chid:' . $chid;
  259. $form['choice_wrapper']['choice'][$key] = _poll_choice_form($key, $choice['chid'], $choice['chtext'], $choice['chvotes'], $choice['weight'], $choice_count);
  260. $weight = max($choice['weight'], $weight);
  261. }
  262. }
  263. // Add initial or additional choices.
  264. $existing_delta = $delta;
  265. for ($delta; $delta < $choice_count; $delta++) {
  266. $key = 'new:' . ($delta - $existing_delta);
  267. // Increase the weight of each new choice.
  268. $weight++;
  269. $form['choice_wrapper']['choice'][$key] = _poll_choice_form($key, NULL, '', 0, $weight, $choice_count);
  270. }
  271. // We name our button 'poll_more' to avoid conflicts with other modules using
  272. // Ajax-enabled buttons with the id 'more'.
  273. $form['choice_wrapper']['poll_more'] = array(
  274. '#type' => 'submit',
  275. '#value' => t('More choices'),
  276. '#attributes' => array(
  277. 'title' => t("If the amount of boxes above isn't enough, click here to add more choices."),
  278. ),
  279. '#weight' => 1,
  280. '#limit_validation_errors' => array(array('choice')),
  281. '#submit' => array('poll_more_choices_submit'),
  282. '#ajax' => array(
  283. 'callback' => 'poll_choice_js',
  284. 'wrapper' => 'poll-choices',
  285. 'effect' => 'fade',
  286. ),
  287. );
  288. // Poll attributes
  289. $duration = array(
  290. // 1-6 days.
  291. 86400, 2 * 86400, 3 * 86400, 4 * 86400, 5 * 86400, 6 * 86400,
  292. // 1-3 weeks (7 days).
  293. 604800, 2 * 604800, 3 * 604800,
  294. // 1-3,6,9 months (30 days).
  295. 2592000, 2 * 2592000, 3 * 2592000, 6 * 2592000, 9 * 2592000,
  296. // 1 year (365 days).
  297. 31536000,
  298. );
  299. $duration = array(0 => t('Unlimited')) + drupal_map_assoc($duration, 'format_interval');
  300. $active = array(0 => t('Closed'), 1 => t('Active'));
  301. $form['settings'] = array(
  302. '#type' => 'fieldset',
  303. '#collapsible' => TRUE,
  304. '#title' => t('Poll settings'),
  305. '#weight' => -3,
  306. '#access' => $admin,
  307. );
  308. $form['settings']['active'] = array(
  309. '#type' => 'radios',
  310. '#title' => t('Poll status'),
  311. '#default_value' => isset($node->active) ? $node->active : 1,
  312. '#options' => $active,
  313. '#description' => t('When a poll is closed, visitors can no longer vote for it.'),
  314. '#access' => $admin,
  315. );
  316. $form['settings']['runtime'] = array(
  317. '#type' => 'select',
  318. '#title' => t('Poll duration'),
  319. '#default_value' => isset($node->runtime) ? $node->runtime : 0,
  320. '#options' => $duration,
  321. '#description' => t('After this period, the poll will be closed automatically.'),
  322. );
  323. return $form;
  324. }
  325. /**
  326. * Submit handler to add more choices to a poll form.
  327. *
  328. * This handler is run regardless of whether JS is enabled or not. It makes
  329. * changes to the form state. If the button was clicked with JS disabled, then
  330. * the page is reloaded with the complete rebuilt form. If the button was
  331. * clicked with JS enabled, then ajax_form_callback() calls poll_choice_js() to
  332. * return just the changed part of the form.
  333. */
  334. function poll_more_choices_submit($form, &$form_state) {
  335. // If this is a Ajax POST, add 1, otherwise add 5 more choices to the form.
  336. if ($form_state['values']['poll_more']) {
  337. $n = $_GET['q'] == 'system/ajax' ? 1 : 5;
  338. $form_state['choice_count'] = count($form_state['values']['choice']) + $n;
  339. }
  340. // Renumber the choices. This invalidates the corresponding key/value
  341. // associations in $form_state['input'], so clear that out. This requires
  342. // poll_form() to rebuild the choices with the values in
  343. // $form_state['node']->choice, which it does.
  344. $form_state['node']->choice = array_values($form_state['values']['choice']);
  345. unset($form_state['input']['choice']);
  346. $form_state['rebuild'] = TRUE;
  347. }
  348. function _poll_choice_form($key, $chid = NULL, $value = '', $votes = 0, $weight = 0, $size = 10) {
  349. $form = array(
  350. '#tree' => TRUE,
  351. '#weight' => $weight,
  352. );
  353. // We'll manually set the #parents property of these fields so that
  354. // their values appear in the $form_state['values']['choice'] array.
  355. $form['chid'] = array(
  356. '#type' => 'value',
  357. '#value' => $chid,
  358. '#parents' => array('choice', $key, 'chid'),
  359. );
  360. $form['chtext'] = array(
  361. '#type' => 'textfield',
  362. '#title' => $value !== '' ? t('Choice label') : t('New choice label'),
  363. '#title_display' => 'invisible',
  364. '#default_value' => $value,
  365. '#parents' => array('choice', $key, 'chtext'),
  366. );
  367. $form['chvotes'] = array(
  368. '#type' => 'textfield',
  369. '#title' => $value !== '' ? t('Vote count for choice @label', array('@label' => $value)) : t('Vote count for new choice'),
  370. '#title_display' => 'invisible',
  371. '#default_value' => $votes,
  372. '#size' => 5,
  373. '#maxlength' => 7,
  374. '#parents' => array('choice', $key, 'chvotes'),
  375. '#access' => user_access('administer nodes'),
  376. '#element_validate' => array('element_validate_integer'),
  377. );
  378. $form['weight'] = array(
  379. '#type' => 'weight',
  380. '#title' => $value !== '' ? t('Weight for choice @label', array('@label' => $value)) : t('Weight for new choice'),
  381. '#title_display' => 'invisible',
  382. '#default_value' => $weight,
  383. '#delta' => $size,
  384. '#parents' => array('choice', $key, 'weight'),
  385. );
  386. return $form;
  387. }
  388. /**
  389. * Ajax callback in response to new choices being added to the form.
  390. *
  391. * This returns the new page content to replace the page content made obsolete
  392. * by the form submission.
  393. *
  394. * @see poll_more_choices_submit()
  395. */
  396. function poll_choice_js($form, $form_state) {
  397. return $form['choice_wrapper']['choice'];
  398. }
  399. /**
  400. * Form submit handler for node_form().
  401. *
  402. * Upon preview and final submission, we need to renumber poll choices and
  403. * create a teaser output.
  404. */
  405. function poll_node_form_submit(&$form, &$form_state) {
  406. // Renumber choices.
  407. $form_state['values']['choice'] = array_values($form_state['values']['choice']);
  408. $form_state['values']['teaser'] = poll_teaser((object) $form_state['values']);
  409. }
  410. /**
  411. * Implements hook_validate().
  412. */
  413. function poll_validate($node, $form) {
  414. if (isset($node->title)) {
  415. // Check for at least two options and validate amount of votes.
  416. $realchoices = 0;
  417. foreach ($node->choice as $i => $choice) {
  418. if ($choice['chtext'] != '') {
  419. $realchoices++;
  420. }
  421. if (isset($choice['chvotes']) && $choice['chvotes'] < 0) {
  422. form_set_error("choice][$i][chvotes", t('Negative values are not allowed.'));
  423. }
  424. }
  425. if ($realchoices < 2) {
  426. form_set_error("choice][$realchoices][chtext", t('You must fill in at least two choices.'));
  427. }
  428. }
  429. }
  430. /**
  431. * Implements hook_field_attach_prepare_translation_alter().
  432. */
  433. function poll_field_attach_prepare_translation_alter(&$entity, $context) {
  434. if ($context['entity_type'] == 'node' && $entity->type == 'poll') {
  435. $entity->choice = $context['source_entity']->choice;
  436. foreach ($entity->choice as $i => $options) {
  437. $entity->choice[$i]['chvotes'] = 0;
  438. }
  439. }
  440. }
  441. /**
  442. * Implements hook_load().
  443. */
  444. function poll_load($nodes) {
  445. global $user;
  446. foreach ($nodes as $node) {
  447. $poll = db_query("SELECT runtime, active FROM {poll} WHERE nid = :nid", array(':nid' => $node->nid))->fetchObject();
  448. if (empty($poll)) {
  449. $poll = new stdClass();
  450. }
  451. // Load the appropriate choices into the $poll object.
  452. $poll->choice = db_select('poll_choice', 'c')
  453. ->addTag('translatable')
  454. ->fields('c', array('chid', 'chtext', 'chvotes', 'weight'))
  455. ->condition('c.nid', $node->nid)
  456. ->orderBy('weight')
  457. ->execute()->fetchAllAssoc('chid', PDO::FETCH_ASSOC);
  458. // Determine whether or not this user is allowed to vote.
  459. $poll->allowvotes = FALSE;
  460. if (user_access('vote on polls') && $poll->active) {
  461. if ($user->uid) {
  462. // If authenticated, find existing vote based on uid.
  463. $poll->vote = db_query('SELECT chid FROM {poll_vote} WHERE nid = :nid AND uid = :uid', array(':nid' => $node->nid, ':uid' => $user->uid))->fetchField();
  464. if (empty($poll->vote)) {
  465. $poll->vote = -1;
  466. $poll->allowvotes = TRUE;
  467. }
  468. }
  469. elseif (!empty($_SESSION['poll_vote'][$node->nid])) {
  470. // Otherwise the user is anonymous. Look for an existing vote in the
  471. // user's session.
  472. $poll->vote = $_SESSION['poll_vote'][$node->nid];
  473. }
  474. else {
  475. // Finally, query the database for an existing vote based on anonymous
  476. // user's hostname.
  477. $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();
  478. }
  479. }
  480. foreach ($poll as $key => $value) {
  481. $nodes[$node->nid]->$key = $value;
  482. }
  483. }
  484. }
  485. /**
  486. * Implements hook_insert().
  487. */
  488. function poll_insert($node) {
  489. if (!user_access('administer nodes')) {
  490. // Make sure all votes are 0 initially
  491. foreach ($node->choice as $i => $choice) {
  492. $node->choice[$i]['chvotes'] = 0;
  493. }
  494. $node->active = 1;
  495. }
  496. db_insert('poll')
  497. ->fields(array(
  498. 'nid' => $node->nid,
  499. 'runtime' => $node->runtime,
  500. 'active' => $node->active,
  501. ))
  502. ->execute();
  503. foreach ($node->choice as $choice) {
  504. if ($choice['chtext'] != '') {
  505. db_insert('poll_choice')
  506. ->fields(array(
  507. 'nid' => $node->nid,
  508. 'chtext' => $choice['chtext'],
  509. 'chvotes' => $choice['chvotes'],
  510. 'weight' => $choice['weight'],
  511. ))
  512. ->execute();
  513. }
  514. }
  515. }
  516. /**
  517. * Implements hook_update().
  518. */
  519. function poll_update($node) {
  520. // Update poll settings.
  521. db_update('poll')
  522. ->fields(array(
  523. 'runtime' => $node->runtime,
  524. 'active' => $node->active,
  525. ))
  526. ->condition('nid', $node->nid)
  527. ->execute();
  528. // Poll choices with empty titles signifies removal. We remove all votes to
  529. // the removed options, so people who voted on them can vote again.
  530. foreach ($node->choice as $key => $choice) {
  531. if (!empty($choice['chtext'])) {
  532. db_merge('poll_choice')
  533. ->key(array('chid' => $choice['chid']))
  534. ->fields(array(
  535. 'chtext' => $choice['chtext'],
  536. 'chvotes' => (int) $choice['chvotes'],
  537. 'weight' => $choice['weight'],
  538. ))
  539. ->insertFields(array(
  540. 'nid' => $node->nid,
  541. 'chtext' => $choice['chtext'],
  542. 'chvotes' => (int) $choice['chvotes'],
  543. 'weight' => $choice['weight'],
  544. ))
  545. ->execute();
  546. }
  547. else {
  548. db_delete('poll_vote')
  549. ->condition('nid', $node->nid)
  550. ->condition('chid', $key)
  551. ->execute();
  552. db_delete('poll_choice')
  553. ->condition('nid', $node->nid)
  554. ->condition('chid', $choice['chid'])
  555. ->execute();
  556. }
  557. }
  558. }
  559. /**
  560. * Implements hook_delete().
  561. */
  562. function poll_delete($node) {
  563. db_delete('poll')
  564. ->condition('nid', $node->nid)
  565. ->execute();
  566. db_delete('poll_choice')
  567. ->condition('nid', $node->nid)
  568. ->execute();
  569. db_delete('poll_vote')
  570. ->condition('nid', $node->nid)
  571. ->execute();
  572. }
  573. /**
  574. * Return content for 'latest poll' block.
  575. *
  576. * @param $node
  577. * The node object to load.
  578. */
  579. function poll_block_latest_poll_view($node) {
  580. global $user;
  581. $output = '';
  582. // This is necessary for shared objects because PHP doesn't copy objects, but
  583. // passes them by reference. So when the objects are cached it can result in
  584. // the wrong output being displayed on subsequent calls. The cloning and
  585. // unsetting of $node->content prevents the block output from being the same
  586. // as the node output.
  587. $node = clone $node;
  588. unset($node->content);
  589. // No 'read more' link.
  590. $node->readmore = FALSE;
  591. $node->teaser = '';
  592. $links = array();
  593. $links[] = array('title' => t('Older polls'), 'href' => 'poll', 'attributes' => array('title' => t('View the list of polls on this site.')));
  594. if ($node->allowvotes) {
  595. $links[] = array('title' => t('Results'), 'href' => 'node/' . $node->nid . '/results', 'attributes' => array('title' => t('View the current poll results.')));
  596. }
  597. $node->links = $links;
  598. if (!empty($node->allowvotes)) {
  599. $node->content['poll_view_voting'] = drupal_get_form('poll_view_voting', $node, TRUE);
  600. $node->content['links'] = array(
  601. '#theme' => 'links',
  602. '#links' => $node->links,
  603. '#weight' => 5,
  604. );
  605. }
  606. else {
  607. $node->content['poll_view_results'] = array('#markup' => poll_view_results($node, TRUE, TRUE));
  608. }
  609. return $node;
  610. }
  611. /**
  612. * Implements hook_view().
  613. */
  614. function poll_view($node, $view_mode) {
  615. global $user;
  616. $output = '';
  617. if (!empty($node->allowvotes) && empty($node->show_results)) {
  618. $node->content['poll_view_voting'] = drupal_get_form('poll_view_voting', $node);
  619. }
  620. else {
  621. $node->content['poll_view_results'] = array('#markup' => poll_view_results($node, $view_mode));
  622. }
  623. return $node;
  624. }
  625. /**
  626. * Creates a simple teaser that lists all the choices.
  627. *
  628. * This is primarily used for RSS.
  629. */
  630. function poll_teaser($node) {
  631. $teaser = NULL;
  632. if (is_array($node->choice)) {
  633. foreach ($node->choice as $k => $choice) {
  634. if ($choice['chtext'] != '') {
  635. $teaser .= '* ' . check_plain($choice['chtext']) . "\n";
  636. }
  637. }
  638. }
  639. return $teaser;
  640. }
  641. /**
  642. * Generates the voting form for a poll.
  643. *
  644. * @ingroup forms
  645. * @see poll_vote()
  646. * @see phptemplate_preprocess_poll_vote()
  647. */
  648. function poll_view_voting($form, &$form_state, $node, $block = FALSE) {
  649. if ($node->choice) {
  650. $list = array();
  651. foreach ($node->choice as $i => $choice) {
  652. $list[$i] = check_plain($choice['chtext']);
  653. }
  654. $form['choice'] = array(
  655. '#type' => 'radios',
  656. '#title' => t('Choices'),
  657. '#title_display' => 'invisible',
  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 (empty($form_state['values']['choice'])) {
  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. */
  834. function template_preprocess_poll_bar(&$variables) {
  835. if ($variables['block']) {
  836. $variables['theme_hook_suggestions'][] = 'poll_bar__block';
  837. }
  838. $variables['title'] = check_plain($variables['title']);
  839. $variables['percentage'] = round($variables['votes'] * 100 / max($variables['total_votes'], 1));
  840. }
  841. /**
  842. * Builds the cancel form for a poll.
  843. *
  844. * @ingroup forms
  845. * @see poll_cancel()
  846. */
  847. function poll_cancel_form($form, &$form_state, $nid) {
  848. $form_state['cache'] = TRUE;
  849. // Store the nid so we can get to it in submit functions.
  850. $form['#nid'] = $nid;
  851. $form['actions'] = array('#type' => 'actions');
  852. $form['actions']['submit'] = array(
  853. '#type' => 'submit',
  854. '#value' => t('Cancel your vote'),
  855. '#submit' => array('poll_cancel')
  856. );
  857. return $form;
  858. }
  859. /**
  860. * Submit callback for poll_cancel_form().
  861. */
  862. function poll_cancel($form, &$form_state) {
  863. global $user;
  864. $node = node_load($form['#nid']);
  865. db_delete('poll_vote')
  866. ->condition('nid', $node->nid)
  867. ->condition($user->uid ? 'uid' : 'hostname', $user->uid ? $user->uid : ip_address())
  868. ->execute();
  869. // Subtract from the votes.
  870. db_update('poll_choice')
  871. ->expression('chvotes', 'chvotes - 1')
  872. ->condition('chid', $node->vote)
  873. ->execute();
  874. unset($_SESSION['poll_vote'][$node->nid]);
  875. drupal_set_message(t('Your vote was cancelled.'));
  876. }
  877. /**
  878. * Implements hook_user_cancel().
  879. */
  880. function poll_user_cancel($edit, $account, $method) {
  881. switch ($method) {
  882. case 'user_cancel_reassign':
  883. db_update('poll_vote')
  884. ->fields(array('uid' => 0))
  885. ->condition('uid', $account->uid)
  886. ->execute();
  887. break;
  888. }
  889. }
  890. /**
  891. * Implements hook_user_delete().
  892. */
  893. function poll_user_delete($account) {
  894. db_delete('poll_vote')
  895. ->condition('uid', $account->uid)
  896. ->execute();
  897. }
  898. /**
  899. * Implements hook_rdf_mapping().
  900. */
  901. function poll_rdf_mapping() {
  902. return array(
  903. array(
  904. 'type' => 'node',
  905. 'bundle' => 'poll',
  906. 'mapping' => array(
  907. 'rdftype' => array('sioc:Post', 'sioct:Poll'),
  908. ),
  909. ),
  910. );
  911. }