poll.module 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. )
  180. );
  181. }
  182. /**
  183. * Implements hook_field_extra_fields().
  184. */
  185. function poll_field_extra_fields() {
  186. $extra['node']['poll'] = array(
  187. 'form' => array(
  188. 'choice_wrapper' => array(
  189. 'label' => t('Poll choices'),
  190. 'description' => t('Poll choices'),
  191. 'weight' => -4,
  192. ),
  193. 'settings' => array(
  194. 'label' => t('Poll settings'),
  195. 'description' => t('Poll module settings'),
  196. 'weight' => -3,
  197. ),
  198. ),
  199. 'display' => array(
  200. 'poll_view_voting' => array(
  201. 'label' => t('Poll vote'),
  202. 'description' => t('Poll vote'),
  203. 'weight' => 0,
  204. ),
  205. 'poll_view_results' => array(
  206. 'label' => t('Poll results'),
  207. 'description' => t('Poll results'),
  208. 'weight' => 0,
  209. ),
  210. )
  211. );
  212. return $extra;
  213. }
  214. /**
  215. * Implements hook_form().
  216. */
  217. function poll_form($node, &$form_state) {
  218. global $user;
  219. $admin = user_access('bypass node access') || user_access('edit any poll content') || (user_access('edit own poll content') && $user->uid == $node->uid);
  220. $type = node_type_get_type($node);
  221. // The submit handlers to add more poll choices require that this form is
  222. // cached, regardless of whether Ajax is used.
  223. $form_state['cache'] = TRUE;
  224. $form['title'] = array(
  225. '#type' => 'textfield',
  226. '#title' => check_plain($type->title_label),
  227. '#required' => TRUE,
  228. '#default_value' => $node->title,
  229. '#maxlength' => 255,
  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. '#options' => $list,
  658. );
  659. }
  660. $form['vote'] = array(
  661. '#type' => 'submit',
  662. '#value' => t('Vote'),
  663. '#submit' => array('poll_vote'),
  664. );
  665. // Store the node so we can get to it in submit functions.
  666. $form['#node'] = $node;
  667. $form['#block'] = $block;
  668. // Set form caching because we could have multiple of these forms on
  669. // the same page, and we want to ensure the right one gets picked.
  670. $form_state['cache'] = TRUE;
  671. // Provide a more cleanly named voting form theme.
  672. $form['#theme'] = 'poll_vote';
  673. return $form;
  674. }
  675. /**
  676. * Validation function for processing votes
  677. */
  678. function poll_view_voting_validate($form, &$form_state) {
  679. if (empty($form_state['values']['choice'])) {
  680. form_set_error( 'choice', t('Your vote could not be recorded because you did not select any of the choices.'));
  681. }
  682. }
  683. /**
  684. * Submit handler for processing a vote.
  685. */
  686. function poll_vote($form, &$form_state) {
  687. $node = $form['#node'];
  688. $choice = $form_state['values']['choice'];
  689. global $user;
  690. db_insert('poll_vote')
  691. ->fields(array(
  692. 'nid' => $node->nid,
  693. 'chid' => $choice,
  694. 'uid' => $user->uid,
  695. 'hostname' => ip_address(),
  696. 'timestamp' => REQUEST_TIME,
  697. ))
  698. ->execute();
  699. // Add one to the votes.
  700. db_update('poll_choice')
  701. ->expression('chvotes', 'chvotes + 1')
  702. ->condition('chid', $choice)
  703. ->execute();
  704. cache_clear_all();
  705. if (!$user->uid) {
  706. // The vote is recorded so the user gets the result view instead of the
  707. // voting form when viewing the poll. Saving a value in $_SESSION has the
  708. // convenient side effect of preventing the user from hitting the page
  709. // cache. When anonymous voting is allowed, the page cache should only
  710. // contain the voting form, not the results.
  711. $_SESSION['poll_vote'][$node->nid] = $choice;
  712. }
  713. drupal_set_message(t('Your vote was recorded.'));
  714. // Return the user to whatever page they voted from.
  715. }
  716. /**
  717. * Themes the voting form for a poll.
  718. *
  719. * Inputs: $form
  720. */
  721. function template_preprocess_poll_vote(&$variables) {
  722. $form = $variables['form'];
  723. $variables['choice'] = drupal_render($form['choice']);
  724. $variables['title'] = check_plain($form['#node']->title);
  725. $variables['vote'] = drupal_render($form['vote']);
  726. $variables['rest'] = drupal_render_children($form);
  727. $variables['block'] = $form['#block'];
  728. if ($variables['block']) {
  729. $variables['theme_hook_suggestions'][] = 'poll_vote__block';
  730. }
  731. }
  732. /**
  733. * Generates a graphical representation of the results of a poll.
  734. */
  735. function poll_view_results($node, $view_mode, $block = FALSE) {
  736. // Make sure that choices are ordered by their weight.
  737. uasort($node->choice, 'drupal_sort_weight');
  738. // Count the votes and find the maximum.
  739. $total_votes = 0;
  740. $max_votes = 0;
  741. foreach ($node->choice as $choice) {
  742. if (isset($choice['chvotes'])) {
  743. $total_votes += $choice['chvotes'];
  744. $max_votes = max($max_votes, $choice['chvotes']);
  745. }
  746. }
  747. $poll_results = '';
  748. foreach ($node->choice as $i => $choice) {
  749. if (!empty($choice['chtext'])) {
  750. $chvotes = isset($choice['chvotes']) ? $choice['chvotes'] : NULL;
  751. $poll_results .= theme('poll_bar', array('title' => $choice['chtext'], 'votes' => $chvotes, 'total_votes' => $total_votes, 'vote' => isset($node->vote) && $node->vote == $i, 'block' => $block));
  752. }
  753. }
  754. 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));
  755. }
  756. /**
  757. * Returns HTML for an admin poll form for choices.
  758. *
  759. * @param $variables
  760. * An associative array containing:
  761. * - form: A render element representing the form.
  762. *
  763. * @ingroup themeable
  764. */
  765. function theme_poll_choices($variables) {
  766. $form = $variables['form'];
  767. drupal_add_tabledrag('poll-choice-table', 'order', 'sibling', 'poll-weight');
  768. $is_admin= user_access('administer nodes');
  769. $delta = 0;
  770. $rows = array();
  771. $headers = array('', t('Choice'));
  772. if ($is_admin) {
  773. $headers[] = t('Vote count');
  774. }
  775. $headers[] = t('Weight');
  776. foreach (element_children($form) as $key) {
  777. $delta++;
  778. // Set special classes for drag and drop updating.
  779. $form[$key]['weight']['#attributes']['class'] = array('poll-weight');
  780. // Build the table row.
  781. $row = array(
  782. 'data' => array(
  783. array('class' => array('choice-flag')),
  784. drupal_render($form[$key]['chtext']),
  785. ),
  786. 'class' => array('draggable'),
  787. );
  788. if ($is_admin) {
  789. $row['data'][] = drupal_render($form[$key]['chvotes']);
  790. }
  791. $row['data'][] = drupal_render($form[$key]['weight']);
  792. // Add any additional classes set on the row.
  793. if (!empty($form[$key]['#attributes']['class'])) {
  794. $row['class'] = array_merge($row['class'], $form[$key]['#attributes']['class']);
  795. }
  796. $rows[] = $row;
  797. }
  798. $output = theme('table', array('header' => $headers, 'rows' => $rows, 'attributes' => array('id' => 'poll-choice-table')));
  799. $output .= drupal_render_children($form);
  800. return $output;
  801. }
  802. /**
  803. * Preprocess the poll_results theme hook.
  804. *
  805. * Inputs: $raw_title, $results, $votes, $raw_links, $block, $nid, $vote. The
  806. * $raw_* inputs to this are naturally unsafe; often safe versions are
  807. * made to simply overwrite the raw version, but in this case it seems likely
  808. * that the title and the links may be overridden by the theme layer, so they
  809. * are left in with a different name for that purpose.
  810. *
  811. * @see poll-results.tpl.php
  812. * @see poll-results--block.tpl.php
  813. */
  814. function template_preprocess_poll_results(&$variables) {
  815. $variables['links'] = theme('links__poll_results', array('links' => $variables['raw_links']));
  816. if (isset($variables['vote']) && $variables['vote'] > -1 && user_access('cancel own vote')) {
  817. $elements = drupal_get_form('poll_cancel_form', $variables['nid']);
  818. $variables['cancel_form'] = drupal_render($elements);
  819. }
  820. $variables['title'] = check_plain($variables['raw_title']);
  821. if ($variables['block']) {
  822. $variables['theme_hook_suggestions'][] = 'poll_results__block';
  823. }
  824. }
  825. /**
  826. * Preprocess the poll_bar theme hook.
  827. *
  828. * Inputs: $title, $votes, $total_votes, $voted, $block
  829. *
  830. * @see poll-bar.tpl.php
  831. * @see poll-bar--block.tpl.php
  832. */
  833. function template_preprocess_poll_bar(&$variables) {
  834. if ($variables['block']) {
  835. $variables['theme_hook_suggestions'][] = 'poll_bar__block';
  836. }
  837. $variables['title'] = check_plain($variables['title']);
  838. $variables['percentage'] = round($variables['votes'] * 100 / max($variables['total_votes'], 1));
  839. }
  840. /**
  841. * Builds the cancel form for a poll.
  842. *
  843. * @ingroup forms
  844. * @see poll_cancel()
  845. */
  846. function poll_cancel_form($form, &$form_state, $nid) {
  847. $form_state['cache'] = TRUE;
  848. // Store the nid so we can get to it in submit functions.
  849. $form['#nid'] = $nid;
  850. $form['actions'] = array('#type' => 'actions');
  851. $form['actions']['submit'] = array(
  852. '#type' => 'submit',
  853. '#value' => t('Cancel your vote'),
  854. '#submit' => array('poll_cancel')
  855. );
  856. return $form;
  857. }
  858. /**
  859. * Submit callback for poll_cancel_form().
  860. */
  861. function poll_cancel($form, &$form_state) {
  862. global $user;
  863. $node = node_load($form['#nid']);
  864. db_delete('poll_vote')
  865. ->condition('nid', $node->nid)
  866. ->condition($user->uid ? 'uid' : 'hostname', $user->uid ? $user->uid : ip_address())
  867. ->execute();
  868. // Subtract from the votes.
  869. db_update('poll_choice')
  870. ->expression('chvotes', 'chvotes - 1')
  871. ->condition('chid', $node->vote)
  872. ->execute();
  873. unset($_SESSION['poll_vote'][$node->nid]);
  874. drupal_set_message(t('Your vote was cancelled.'));
  875. }
  876. /**
  877. * Implements hook_user_cancel().
  878. */
  879. function poll_user_cancel($edit, $account, $method) {
  880. switch ($method) {
  881. case 'user_cancel_reassign':
  882. db_update('poll_vote')
  883. ->fields(array('uid' => 0))
  884. ->condition('uid', $account->uid)
  885. ->execute();
  886. break;
  887. }
  888. }
  889. /**
  890. * Implements hook_user_delete().
  891. */
  892. function poll_user_delete($account) {
  893. db_delete('poll_vote')
  894. ->condition('uid', $account->uid)
  895. ->execute();
  896. }
  897. /**
  898. * Implements hook_rdf_mapping().
  899. */
  900. function poll_rdf_mapping() {
  901. return array(
  902. array(
  903. 'type' => 'node',
  904. 'bundle' => 'poll',
  905. 'mapping' => array(
  906. 'rdftype' => array('sioc:Post', 'sioct:Poll'),
  907. ),
  908. ),
  909. );
  910. }