Poll.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* This file contains the functions for voting, locking, removing and editing
  15. polls. Note that that posting polls is done in Post.php.
  16. void Vote()
  17. - is called to register a vote in a poll.
  18. - must be called with a topic and option specified.
  19. - uses the Post language file.
  20. - requires the poll_vote permission.
  21. - upon successful completion of action will direct user back to topic.
  22. - is accessed via ?action=vote.
  23. void LockVoting()
  24. - is called to lock or unlock voting on a poll.
  25. - must be called with a topic specified in the URL.
  26. - an admin always has over riding permission to lock a poll.
  27. - if not an admin must have poll_lock_any permission.
  28. - otherwise must be poll starter with poll_lock_own permission.
  29. - upon successful completion of action will direct user back to topic.
  30. - is accessed via ?action=lockvoting.
  31. void EditPoll()
  32. - is called to display screen for editing or adding a poll.
  33. - must be called with a topic specified in the URL.
  34. - if the user is adding a poll to a topic, must contain the variable
  35. 'add' in the url.
  36. - uses the Post language file.
  37. - uses the Poll template (main sub template.).
  38. - user must have poll_edit_any/poll_add_any permission for the relevant
  39. action.
  40. - otherwise must be poll starter with poll_edit_own permission for
  41. editing, or be topic starter with poll_add_any permission for adding.
  42. - is accessed via ?action=editpoll.
  43. void EditPoll2()
  44. - is called to update the settings for a poll, or add a new one.
  45. - must be called with a topic specified in the URL.
  46. - user must have poll_edit_any/poll_add_any permission for the relevant
  47. action.
  48. - otherwise must be poll starter with poll_edit_own permission for
  49. editing, or be topic starter with poll_add_any permission for adding.
  50. - in the case of an error will redirect back to EditPoll and display
  51. the relevant error message.
  52. - upon successful completion of action will direct user back to topic.
  53. - is accessed via ?action=editpoll2.
  54. void RemovePoll()
  55. - is called to remove a poll from a topic.
  56. - must be called with a topic specified in the URL.
  57. - user must have poll_remove_any permission.
  58. - otherwise must be poll starter with poll_remove_own permission.
  59. - upon successful completion of action will direct user back to topic.
  60. - is accessed via ?action=removepoll.
  61. */
  62. // Allow the user to vote.
  63. function Vote()
  64. {
  65. global $topic, $txt, $user_info, $smcFunc, $sourcedir, $modSettings;
  66. // Make sure you can vote.
  67. isAllowedTo('poll_vote');
  68. loadLanguage('Post');
  69. // Check if they have already voted, or voting is locked.
  70. $request = $smcFunc['db_query']('', '
  71. SELECT IFNULL(lp.id_choice, -1) AS selected, p.voting_locked, p.id_poll, p.expire_time, p.max_votes, p.change_vote,
  72. p.guest_vote, p.reset_poll, p.num_guest_voters
  73. FROM {db_prefix}topics AS t
  74. INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
  75. LEFT JOIN {db_prefix}log_polls AS lp ON (p.id_poll = lp.id_poll AND lp.id_member = {int:current_member} AND lp.id_member != {int:not_guest})
  76. WHERE t.id_topic = {int:current_topic}
  77. LIMIT 1',
  78. array(
  79. 'current_member' => $user_info['id'],
  80. 'current_topic' => $topic,
  81. 'not_guest' => 0,
  82. )
  83. );
  84. if ($smcFunc['db_num_rows']($request) == 0)
  85. fatal_lang_error('poll_error', false);
  86. $row = $smcFunc['db_fetch_assoc']($request);
  87. $smcFunc['db_free_result']($request);
  88. // If this is a guest can they vote?
  89. if ($user_info['is_guest'])
  90. {
  91. // Guest voting disabled?
  92. if (!$row['guest_vote'])
  93. fatal_lang_error('guest_vote_disabled');
  94. // Guest already voted?
  95. elseif (!empty($_COOKIE['guest_poll_vote']) && preg_match('~^[0-9,;]+$~', $_COOKIE['guest_poll_vote']) && strpos($_COOKIE['guest_poll_vote'], ';' . $row['id_poll'] . ',') !== false)
  96. {
  97. // ;id,timestamp,[vote,vote...]; etc
  98. $guestinfo = explode(';', $_COOKIE['guest_poll_vote']);
  99. // Find the poll we're after.
  100. foreach ($guestinfo as $i => $guestvoted)
  101. {
  102. $guestvoted = explode(',', $guestvoted);
  103. if ($guestvoted[0] == $row['id_poll'])
  104. break;
  105. }
  106. // Has the poll been reset since guest voted?
  107. if ($row['reset_poll'] > $guestvoted[1])
  108. {
  109. // Remove the poll info from the cookie to allow guest to vote again
  110. unset($guestinfo[$i]);
  111. if (!empty($guestinfo))
  112. $_COOKIE['guest_poll_vote'] = ';' . implode(';', $guestinfo);
  113. else
  114. unset($_COOKIE['guest_poll_vote']);
  115. }
  116. else
  117. fatal_lang_error('poll_error', false);
  118. unset($guestinfo, $guestvoted, $i);
  119. }
  120. }
  121. // Is voting locked or has it expired?
  122. if (!empty($row['voting_locked']) || (!empty($row['expire_time']) && time() > $row['expire_time']))
  123. fatal_lang_error('poll_error', false);
  124. // If they have already voted and aren't allowed to change their vote - hence they are outta here!
  125. if (!$user_info['is_guest'] && $row['selected'] != -1 && empty($row['change_vote']))
  126. fatal_lang_error('poll_error', false);
  127. // Otherwise if they can change their vote yet they haven't sent any options... remove their vote and redirect.
  128. elseif (!empty($row['change_vote']) && !$user_info['is_guest'])
  129. {
  130. checkSession('request');
  131. $pollOptions = array();
  132. // Find out what they voted for before.
  133. $request = $smcFunc['db_query']('', '
  134. SELECT id_choice
  135. FROM {db_prefix}log_polls
  136. WHERE id_member = {int:current_member}
  137. AND id_poll = {int:id_poll}',
  138. array(
  139. 'current_member' => $user_info['id'],
  140. 'id_poll' => $row['id_poll'],
  141. )
  142. );
  143. while ($choice = $smcFunc['db_fetch_row']($request))
  144. $pollOptions[] = $choice[0];
  145. $smcFunc['db_free_result']($request);
  146. // Just skip it if they had voted for nothing before.
  147. if (!empty($pollOptions))
  148. {
  149. // Update the poll totals.
  150. $smcFunc['db_query']('', '
  151. UPDATE {db_prefix}poll_choices
  152. SET votes = votes - 1
  153. WHERE id_poll = {int:id_poll}
  154. AND id_choice IN ({array_int:poll_options})
  155. AND votes > {int:votes}',
  156. array(
  157. 'poll_options' => $pollOptions,
  158. 'id_poll' => $row['id_poll'],
  159. 'votes' => 0,
  160. )
  161. );
  162. // Delete off the log.
  163. $smcFunc['db_query']('', '
  164. DELETE FROM {db_prefix}log_polls
  165. WHERE id_member = {int:current_member}
  166. AND id_poll = {int:id_poll}',
  167. array(
  168. 'current_member' => $user_info['id'],
  169. 'id_poll' => $row['id_poll'],
  170. )
  171. );
  172. }
  173. // Redirect back to the topic so the user can vote again!
  174. if (empty($_POST['options']))
  175. redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
  176. }
  177. checkSession('request');
  178. // Make sure the option(s) are valid.
  179. if (empty($_POST['options']))
  180. fatal_lang_error('didnt_select_vote', false);
  181. // Too many options checked!
  182. if (count($_REQUEST['options']) > $row['max_votes'])
  183. fatal_lang_error('poll_too_many_votes', false, array($row['max_votes']));
  184. $pollOptions = array();
  185. $inserts = array();
  186. foreach ($_REQUEST['options'] as $id)
  187. {
  188. $id = (int) $id;
  189. $pollOptions[] = $id;
  190. $inserts[] = array($row['id_poll'], $user_info['id'], $id);
  191. }
  192. // Add their vote to the tally.
  193. $smcFunc['db_insert']('insert',
  194. '{db_prefix}log_polls',
  195. array('id_poll' => 'int', 'id_member' => 'int', 'id_choice' => 'int'),
  196. $inserts,
  197. array('id_poll', 'id_member', 'id_choice')
  198. );
  199. $smcFunc['db_query']('', '
  200. UPDATE {db_prefix}poll_choices
  201. SET votes = votes + 1
  202. WHERE id_poll = {int:id_poll}
  203. AND id_choice IN ({array_int:poll_options})',
  204. array(
  205. 'poll_options' => $pollOptions,
  206. 'id_poll' => $row['id_poll'],
  207. )
  208. );
  209. // If it's a guest don't let them vote again.
  210. if ($user_info['is_guest'] && count($pollOptions) > 0)
  211. {
  212. // Time is stored in case the poll is reset later, plus what they voted for.
  213. $_COOKIE['guest_poll_vote'] = empty($_COOKIE['guest_poll_vote']) ? '' : $_COOKIE['guest_poll_vote'];
  214. // ;id,timestamp,[vote,vote...]; etc
  215. $_COOKIE['guest_poll_vote'] .= ';' . $row['id_poll'] . ',' . time() . ',' . (count($pollOptions) > 1 ? explode(',' . $pollOptions) : $pollOptions[0]);
  216. // Increase num guest voters count by 1
  217. $smcFunc['db_query']('', '
  218. UPDATE {db_prefix}polls
  219. SET num_guest_voters = num_guest_voters + 1
  220. WHERE id_poll = {int:id_poll}',
  221. array(
  222. 'id_poll' => $row['id_poll'],
  223. )
  224. );
  225. require_once($sourcedir . '/Subs-Auth.php');
  226. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  227. setcookie('guest_poll_vote', $_COOKIE['guest_poll_vote'], time() + 2500000, $cookie_url[1], $cookie_url[0], 0);
  228. }
  229. // Return to the post...
  230. redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
  231. }
  232. // Lock the voting for a poll.
  233. function LockVoting()
  234. {
  235. global $topic, $user_info, $smcFunc;
  236. checkSession('get');
  237. // Get the poll starter, ID, and whether or not it is locked.
  238. $request = $smcFunc['db_query']('', '
  239. SELECT t.id_member_started, t.id_poll, p.voting_locked
  240. FROM {db_prefix}topics AS t
  241. INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
  242. WHERE t.id_topic = {int:current_topic}
  243. LIMIT 1',
  244. array(
  245. 'current_topic' => $topic,
  246. )
  247. );
  248. list ($memberID, $pollID, $voting_locked) = $smcFunc['db_fetch_row']($request);
  249. // If the user _can_ modify the poll....
  250. if (!allowedTo('poll_lock_any'))
  251. isAllowedTo('poll_lock_' . ($user_info['id'] == $memberID ? 'own' : 'any'));
  252. // It's been locked by a non-moderator.
  253. if ($voting_locked == '1')
  254. $voting_locked = '0';
  255. // Locked by a moderator, and this is a moderator.
  256. elseif ($voting_locked == '2' && allowedTo('moderate_board'))
  257. $voting_locked = '0';
  258. // Sorry, a moderator locked it.
  259. elseif ($voting_locked == '2' && !allowedTo('moderate_board'))
  260. fatal_lang_error('locked_by_admin', 'user');
  261. // A moderator *is* locking it.
  262. elseif ($voting_locked == '0' && allowedTo('moderate_board'))
  263. $voting_locked = '2';
  264. // Well, it's gonna be locked one way or another otherwise...
  265. else
  266. $voting_locked = '1';
  267. // Lock! *Poof* - no one can vote.
  268. $smcFunc['db_query']('', '
  269. UPDATE {db_prefix}polls
  270. SET voting_locked = {int:voting_locked}
  271. WHERE id_poll = {int:id_poll}',
  272. array(
  273. 'voting_locked' => $voting_locked,
  274. 'id_poll' => $pollID,
  275. )
  276. );
  277. redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
  278. }
  279. // Ask what to change in a poll.
  280. function EditPoll()
  281. {
  282. global $txt, $user_info, $context, $topic, $board, $smcFunc, $sourcedir, $scripturl;
  283. if (empty($topic))
  284. fatal_lang_error('no_access', false);
  285. loadLanguage('Post');
  286. loadTemplate('Poll');
  287. $context['can_moderate_poll'] = isset($_REQUEST['add']) ? 1 : allowedTo('moderate_board');
  288. $context['start'] = (int) $_REQUEST['start'];
  289. $context['is_edit'] = isset($_REQUEST['add']) ? 0 : 1;
  290. // Check if a poll currently exists on this topic, and get the id, question and starter.
  291. $request = $smcFunc['db_query']('', '
  292. SELECT
  293. t.id_member_started, p.id_poll, p.question, p.hide_results, p.expire_time, p.max_votes, p.change_vote,
  294. m.subject, p.guest_vote, p.id_member AS poll_starter
  295. FROM {db_prefix}topics AS t
  296. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  297. LEFT JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
  298. WHERE t.id_topic = {int:current_topic}
  299. LIMIT 1',
  300. array(
  301. 'current_topic' => $topic,
  302. )
  303. );
  304. // Assume the the topic exists, right?
  305. if ($smcFunc['db_num_rows']($request) == 0)
  306. fatal_lang_error('no_board');
  307. // Get the poll information.
  308. $pollinfo = $smcFunc['db_fetch_assoc']($request);
  309. $smcFunc['db_free_result']($request);
  310. // If we are adding a new poll - make sure that there isn't already a poll there.
  311. if (!$context['is_edit'] && !empty($pollinfo['id_poll']))
  312. fatal_lang_error('poll_already_exists');
  313. // Otherwise, if we're editing it, it does exist I assume?
  314. elseif ($context['is_edit'] && empty($pollinfo['id_poll']))
  315. fatal_lang_error('poll_not_found');
  316. // Can you do this?
  317. if ($context['is_edit'] && !allowedTo('poll_edit_any'))
  318. isAllowedTo('poll_edit_' . ($user_info['id'] == $pollinfo['id_member_started'] || ($pollinfo['poll_starter'] != 0 && $user_info['id'] == $pollinfo['poll_starter']) ? 'own' : 'any'));
  319. elseif (!$context['is_edit'] && !allowedTo('poll_add_any'))
  320. isAllowedTo('poll_add_' . ($user_info['id'] == $pollinfo['id_member_started'] ? 'own' : 'any'));
  321. // Do we enable guest voting?
  322. require_once($sourcedir . '/Subs-Members.php');
  323. $groupsAllowedVote = groupsAllowedTo('poll_vote', $board);
  324. // Want to make sure before you actually submit? Must be a lot of options, or something.
  325. if (isset($_POST['preview']))
  326. {
  327. $question = $smcFunc['htmlspecialchars']($_POST['question']);
  328. // Basic theme info...
  329. $context['poll'] = array(
  330. 'id' => $pollinfo['id_poll'],
  331. 'question' => $question,
  332. 'hide_results' => empty($_POST['poll_hide']) ? 0 : $_POST['poll_hide'],
  333. 'change_vote' => isset($_POST['poll_change_vote']),
  334. 'guest_vote' => isset($_POST['poll_guest_vote']),
  335. 'guest_vote_allowed' => in_array(-1, $groupsAllowedVote['allowed']),
  336. 'max_votes' => empty($_POST['poll_max_votes']) ? '1' : max(1, $_POST['poll_max_votes']),
  337. );
  338. // Start at number one with no last id to speak of.
  339. $number = 1;
  340. $last_id = 0;
  341. // Get all the choices - if this is an edit.
  342. if ($context['is_edit'])
  343. {
  344. $request = $smcFunc['db_query']('', '
  345. SELECT label, votes, id_choice
  346. FROM {db_prefix}poll_choices
  347. WHERE id_poll = {int:id_poll}',
  348. array(
  349. 'id_poll' => $pollinfo['id_poll'],
  350. )
  351. );
  352. $context['choices'] = array();
  353. while ($row = $smcFunc['db_fetch_assoc']($request))
  354. {
  355. // Get the highest id so we can add more without reusing.
  356. if ($row['id_choice'] >= $last_id)
  357. $last_id = $row['id_choice'] + 1;
  358. // They cleared this by either omitting it or emptying it.
  359. if (!isset($_POST['options'][$row['id_choice']]) || $_POST['options'][$row['id_choice']] == '')
  360. continue;
  361. censorText($row['label']);
  362. // Add the choice!
  363. $context['choices'][$row['id_choice']] = array(
  364. 'id' => $row['id_choice'],
  365. 'number' => $number++,
  366. 'votes' => $row['votes'],
  367. 'label' => $row['label'],
  368. 'is_last' => false
  369. );
  370. }
  371. $smcFunc['db_free_result']($request);
  372. }
  373. // Work out how many options we have, so we get the 'is_last' field right...
  374. $totalPostOptions = 0;
  375. foreach ($_POST['options'] as $id => $label)
  376. if ($label != '')
  377. $totalPostOptions++;
  378. $count = 1;
  379. // If an option exists, update it. If it is new, add it - but don't reuse ids!
  380. foreach ($_POST['options'] as $id => $label)
  381. {
  382. $label = $smcFunc['htmlspecialchars']($label);
  383. censorText($label);
  384. if (isset($context['choices'][$id]))
  385. $context['choices'][$id]['label'] = $label;
  386. elseif ($label != '')
  387. $context['choices'][] = array(
  388. 'id' => $last_id++,
  389. 'number' => $number++,
  390. 'label' => $label,
  391. 'votes' => -1,
  392. 'is_last' => $count++ == $totalPostOptions && $totalPostOptions > 1 ? true : false,
  393. );
  394. }
  395. // Make sure we have two choices for sure!
  396. if ($totalPostOptions < 2)
  397. {
  398. // Need two?
  399. if ($totalPostOptions == 0)
  400. $context['choices'][] = array(
  401. 'id' => $last_id++,
  402. 'number' => $number++,
  403. 'label' => '',
  404. 'votes' => -1,
  405. 'is_last' => false
  406. );
  407. $poll_errors[] = 'poll_few';
  408. }
  409. // Always show one extra box...
  410. $context['choices'][] = array(
  411. 'id' => $last_id++,
  412. 'number' => $number++,
  413. 'label' => '',
  414. 'votes' => -1,
  415. 'is_last' => true
  416. );
  417. if ($context['can_moderate_poll'])
  418. $context['poll']['expiration'] = $_POST['poll_expire'];
  419. // Check the question/option count for errors.
  420. if (trim($_POST['question']) == '' && empty($context['poll_error']))
  421. $poll_errors[] = 'no_question';
  422. // No check is needed, since nothing is really posted.
  423. checkSubmitOnce('free');
  424. // Take a check for any errors... assuming we haven't already done so!
  425. if (!empty($poll_errors) && empty($context['poll_error']))
  426. {
  427. loadLanguage('Errors');
  428. $context['poll_error'] = array('messages' => array());
  429. foreach ($poll_errors as $poll_error)
  430. {
  431. $context['poll_error'][$poll_error] = true;
  432. $context['poll_error']['messages'][] = $txt['error_' . $poll_error];
  433. }
  434. }
  435. }
  436. else
  437. {
  438. // Basic theme info...
  439. $context['poll'] = array(
  440. 'id' => $pollinfo['id_poll'],
  441. 'question' => $pollinfo['question'],
  442. 'hide_results' => $pollinfo['hide_results'],
  443. 'max_votes' => $pollinfo['max_votes'],
  444. 'change_vote' => !empty($pollinfo['change_vote']),
  445. 'guest_vote' => !empty($pollinfo['guest_vote']),
  446. 'guest_vote_allowed' => in_array(-1, $groupsAllowedVote['allowed']),
  447. );
  448. // Poll expiration time?
  449. $context['poll']['expiration'] = empty($pollinfo['expire_time']) || !allowedTo('moderate_board') ? '' : ceil($pollinfo['expire_time'] <= time() ? -1 : ($pollinfo['expire_time'] - time()) / (3600 * 24));
  450. // Get all the choices - if this is an edit.
  451. if ($context['is_edit'])
  452. {
  453. $request = $smcFunc['db_query']('', '
  454. SELECT label, votes, id_choice
  455. FROM {db_prefix}poll_choices
  456. WHERE id_poll = {int:id_poll}',
  457. array(
  458. 'id_poll' => $pollinfo['id_poll'],
  459. )
  460. );
  461. $context['choices'] = array();
  462. $number = 1;
  463. while ($row = $smcFunc['db_fetch_assoc']($request))
  464. {
  465. censorText($row['label']);
  466. $context['choices'][$row['id_choice']] = array(
  467. 'id' => $row['id_choice'],
  468. 'number' => $number++,
  469. 'votes' => $row['votes'],
  470. 'label' => $row['label'],
  471. 'is_last' => false
  472. );
  473. }
  474. $smcFunc['db_free_result']($request);
  475. $last_id = max(array_keys($context['choices'])) + 1;
  476. // Add an extra choice...
  477. $context['choices'][] = array(
  478. 'id' => $last_id,
  479. 'number' => $number,
  480. 'votes' => -1,
  481. 'label' => '',
  482. 'is_last' => true
  483. );
  484. }
  485. // New poll?
  486. else
  487. {
  488. // Setup the default poll options.
  489. $context['poll'] = array(
  490. 'id' => 0,
  491. 'question' => '',
  492. 'hide_results' => 0,
  493. 'max_votes' => 1,
  494. 'change_vote' => 0,
  495. 'guest_vote' => 0,
  496. 'guest_vote_allowed' => in_array(-1, $groupsAllowedVote['allowed']),
  497. 'expiration' => '',
  498. );
  499. // Make all five poll choices empty.
  500. $context['choices'] = array(
  501. array('id' => 0, 'number' => 1, 'votes' => -1, 'label' => '', 'is_last' => false),
  502. array('id' => 1, 'number' => 2, 'votes' => -1, 'label' => '', 'is_last' => false),
  503. array('id' => 2, 'number' => 3, 'votes' => -1, 'label' => '', 'is_last' => false),
  504. array('id' => 3, 'number' => 4, 'votes' => -1, 'label' => '', 'is_last' => false),
  505. array('id' => 4, 'number' => 5, 'votes' => -1, 'label' => '', 'is_last' => true)
  506. );
  507. }
  508. }
  509. $context['page_title'] = $context['is_edit'] ? $txt['poll_edit'] : $txt['add_poll'];
  510. // Build the link tree.
  511. censorText($pollinfo['subject']);
  512. $context['linktree'][] = array(
  513. 'url' => $scripturl . '?topic=' . $topic . '.0',
  514. 'name' => $pollinfo['subject'],
  515. );
  516. $context['linktree'][] = array(
  517. 'name' => $context['page_title'],
  518. );
  519. // Register this form in the session variables.
  520. checkSubmitOnce('register');
  521. }
  522. // Change a poll...
  523. function EditPoll2()
  524. {
  525. global $txt, $topic, $board, $context;
  526. global $modSettings, $user_info, $smcFunc, $sourcedir;
  527. // Sneaking off, are we?
  528. if (empty($_POST))
  529. redirectexit('action=editpoll;topic=' . $topic . '.0');
  530. if (checkSession('post', '', false) != '')
  531. $poll_errors[] = 'session_timeout';
  532. if (isset($_POST['preview']))
  533. return EditPoll();
  534. // HACKERS (!!) can't edit :P.
  535. if (empty($topic))
  536. fatal_lang_error('no_access', false);
  537. // Is this a new poll, or editing an existing?
  538. $isEdit = isset($_REQUEST['add']) ? 0 : 1;
  539. // Get the starter and the poll's ID - if it's an edit.
  540. $request = $smcFunc['db_query']('', '
  541. SELECT t.id_member_started, t.id_poll, p.id_member AS poll_starter, p.expire_time
  542. FROM {db_prefix}topics AS t
  543. LEFT JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
  544. WHERE t.id_topic = {int:current_topic}
  545. LIMIT 1',
  546. array(
  547. 'current_topic' => $topic,
  548. )
  549. );
  550. if ($smcFunc['db_num_rows']($request) == 0)
  551. fatal_lang_error('no_board');
  552. $bcinfo = $smcFunc['db_fetch_assoc']($request);
  553. $smcFunc['db_free_result']($request);
  554. // Check their adding/editing is valid.
  555. if (!$isEdit && !empty($bcinfo['id_poll']))
  556. fatal_lang_error('poll_already_exists');
  557. // Are we editing a poll which doesn't exist?
  558. elseif ($isEdit && empty($bcinfo['id_poll']))
  559. fatal_lang_error('poll_not_found');
  560. // Check if they have the power to add or edit the poll.
  561. if ($isEdit && !allowedTo('poll_edit_any'))
  562. isAllowedTo('poll_edit_' . ($user_info['id'] == $bcinfo['id_member_started'] || ($bcinfo['poll_starter'] != 0 && $user_info['id'] == $bcinfo['poll_starter']) ? 'own' : 'any'));
  563. elseif (!$isEdit && !allowedTo('poll_add_any'))
  564. isAllowedTo('poll_add_' . ($user_info['id'] == $bcinfo['id_member_started'] ? 'own' : 'any'));
  565. $optionCount = 0;
  566. // Ensure the user is leaving a valid amount of options - there must be at least two.
  567. foreach ($_POST['options'] as $k => $option)
  568. {
  569. if (trim($option) != '')
  570. $optionCount++;
  571. }
  572. if ($optionCount < 2)
  573. $poll_errors[] = 'poll_few';
  574. // Also - ensure they are not removing the question.
  575. if (trim($_POST['question']) == '')
  576. $poll_errors[] = 'no_question';
  577. // Got any errors to report?
  578. if (!empty($poll_errors))
  579. {
  580. loadLanguage('Errors');
  581. // Previewing.
  582. $_POST['preview'] = true;
  583. $context['poll_error'] = array('messages' => array());
  584. foreach ($poll_errors as $poll_error)
  585. {
  586. $context['poll_error'][$poll_error] = true;
  587. $context['poll_error']['messages'][] = $txt['error_' . $poll_error];
  588. }
  589. return EditPoll();
  590. }
  591. // Prevent double submission of this form.
  592. checkSubmitOnce('check');
  593. // Now we've done all our error checking, let's get the core poll information cleaned... question first.
  594. $_POST['question'] = $smcFunc['htmlspecialchars']($_POST['question']);
  595. $_POST['question'] = $smcFunc['truncate']($_POST['question'], 255);
  596. $_POST['poll_hide'] = (int) $_POST['poll_hide'];
  597. $_POST['poll_expire'] = isset($_POST['poll_expire']) ? (int) $_POST['poll_expire'] : 0;
  598. $_POST['poll_change_vote'] = isset($_POST['poll_change_vote']) ? 1 : 0;
  599. $_POST['poll_guest_vote'] = isset($_POST['poll_guest_vote']) ? 1 : 0;
  600. // Make sure guests are actually allowed to vote generally.
  601. if ($_POST['poll_guest_vote'])
  602. {
  603. require_once($sourcedir . '/Subs-Members.php');
  604. $allowedGroups = groupsAllowedTo('poll_vote', $board);
  605. if (!in_array(-1, $allowedGroups['allowed']))
  606. $_POST['poll_guest_vote'] = 0;
  607. }
  608. // Ensure that the number options allowed makes sense, and the expiration date is valid.
  609. if (!$isEdit || allowedTo('moderate_board'))
  610. {
  611. $_POST['poll_expire'] = $_POST['poll_expire'] > 9999 ? 9999 : ($_POST['poll_expire'] < 0 ? 0 : $_POST['poll_expire']);
  612. if (empty($_POST['poll_expire']) && $_POST['poll_hide'] == 2)
  613. $_POST['poll_hide'] = 1;
  614. elseif (!$isEdit || $_POST['poll_expire'] != ceil($bcinfo['expire_time'] <= time() ? -1 : ($bcinfo['expire_time'] - time()) / (3600 * 24)))
  615. $_POST['poll_expire'] = empty($_POST['poll_expire']) ? '0' : time() + $_POST['poll_expire'] * 3600 * 24;
  616. else
  617. $_POST['poll_expire'] = $bcinfo['expire_time'];
  618. if (empty($_POST['poll_max_votes']) || $_POST['poll_max_votes'] <= 0)
  619. $_POST['poll_max_votes'] = 1;
  620. else
  621. $_POST['poll_max_votes'] = (int) $_POST['poll_max_votes'];
  622. }
  623. // If we're editing, let's commit the changes.
  624. if ($isEdit)
  625. {
  626. $smcFunc['db_query']('', '
  627. UPDATE {db_prefix}polls
  628. SET question = {string:question}, change_vote = {int:change_vote},' . (allowedTo('moderate_board') ? '
  629. hide_results = {int:hide_results}, expire_time = {int:expire_time}, max_votes = {int:max_votes},
  630. guest_vote = {int:guest_vote}' : '
  631. hide_results = CASE WHEN expire_time = {int:expire_time_zero} AND {int:hide_results} = 2 THEN 1 ELSE {int:hide_results} END') . '
  632. WHERE id_poll = {int:id_poll}',
  633. array(
  634. 'change_vote' => $_POST['poll_change_vote'],
  635. 'hide_results' => $_POST['poll_hide'],
  636. 'expire_time' => !empty($_POST['poll_expire']) ? $_POST['poll_expire'] : 0,
  637. 'max_votes' => !empty($_POST['poll_max_votes']) ? $_POST['poll_max_votes'] : 0,
  638. 'guest_vote' => $_POST['poll_guest_vote'],
  639. 'expire_time_zero' => 0,
  640. 'id_poll' => $bcinfo['id_poll'],
  641. 'question' => $_POST['question'],
  642. )
  643. );
  644. }
  645. // Otherwise, let's get our poll going!
  646. else
  647. {
  648. // Create the poll.
  649. $smcFunc['db_insert']('',
  650. '{db_prefix}polls',
  651. array(
  652. 'question' => 'string-255', 'hide_results' => 'int', 'max_votes' => 'int', 'expire_time' => 'int', 'id_member' => 'int',
  653. 'poster_name' => 'string-255', 'change_vote' => 'int', 'guest_vote' => 'int'
  654. ),
  655. array(
  656. $_POST['question'], $_POST['poll_hide'], $_POST['poll_max_votes'], $_POST['poll_expire'], $user_info['id'],
  657. $user_info['username'], $_POST['poll_change_vote'], $_POST['poll_guest_vote'],
  658. ),
  659. array('id_poll')
  660. );
  661. // Set the poll ID.
  662. $bcinfo['id_poll'] = $smcFunc['db_insert_id']('{db_prefix}polls', 'id_poll');
  663. // Link the poll to the topic
  664. $smcFunc['db_query']('', '
  665. UPDATE {db_prefix}topics
  666. SET id_poll = {int:id_poll}
  667. WHERE id_topic = {int:current_topic}',
  668. array(
  669. 'current_topic' => $topic,
  670. 'id_poll' => $bcinfo['id_poll'],
  671. )
  672. );
  673. }
  674. // Get all the choices. (no better way to remove all emptied and add previously non-existent ones.)
  675. $request = $smcFunc['db_query']('', '
  676. SELECT id_choice
  677. FROM {db_prefix}poll_choices
  678. WHERE id_poll = {int:id_poll}',
  679. array(
  680. 'id_poll' => $bcinfo['id_poll'],
  681. )
  682. );
  683. $choices = array();
  684. while ($row = $smcFunc['db_fetch_assoc']($request))
  685. $choices[] = $row['id_choice'];
  686. $smcFunc['db_free_result']($request);
  687. $delete_options = array();
  688. foreach ($_POST['options'] as $k => $option)
  689. {
  690. // Make sure the key is numeric for sanity's sake.
  691. $k = (int) $k;
  692. // They've cleared the box. Either they want it deleted, or it never existed.
  693. if (trim($option) == '')
  694. {
  695. // They want it deleted. Bye.
  696. if (in_array($k, $choices))
  697. $delete_options[] = $k;
  698. // Skip the rest...
  699. continue;
  700. }
  701. // Dress the option up for its big date with the database.
  702. $option = $smcFunc['htmlspecialchars']($option);
  703. // If it's already there, update it. If it's not... add it.
  704. if (in_array($k, $choices))
  705. $smcFunc['db_query']('', '
  706. UPDATE {db_prefix}poll_choices
  707. SET label = {string:option_name}
  708. WHERE id_poll = {int:id_poll}
  709. AND id_choice = {int:id_choice}',
  710. array(
  711. 'id_poll' => $bcinfo['id_poll'],
  712. 'id_choice' => $k,
  713. 'option_name' => $option,
  714. )
  715. );
  716. else
  717. $smcFunc['db_insert']('',
  718. '{db_prefix}poll_choices',
  719. array(
  720. 'id_poll' => 'int', 'id_choice' => 'int', 'label' => 'string-255', 'votes' => 'int',
  721. ),
  722. array(
  723. $bcinfo['id_poll'], $k, $option, 0,
  724. ),
  725. array()
  726. );
  727. }
  728. // I'm sorry, but... well, no one was choosing you. Poor options, I'll put you out of your misery.
  729. if (!empty($delete_options))
  730. {
  731. $smcFunc['db_query']('', '
  732. DELETE FROM {db_prefix}log_polls
  733. WHERE id_poll = {int:id_poll}
  734. AND id_choice IN ({array_int:delete_options})',
  735. array(
  736. 'delete_options' => $delete_options,
  737. 'id_poll' => $bcinfo['id_poll'],
  738. )
  739. );
  740. $smcFunc['db_query']('', '
  741. DELETE FROM {db_prefix}poll_choices
  742. WHERE id_poll = {int:id_poll}
  743. AND id_choice IN ({array_int:delete_options})',
  744. array(
  745. 'delete_options' => $delete_options,
  746. 'id_poll' => $bcinfo['id_poll'],
  747. )
  748. );
  749. }
  750. // Shall I reset the vote count, sir?
  751. if (isset($_POST['resetVoteCount']))
  752. {
  753. $smcFunc['db_query']('', '
  754. UPDATE {db_prefix}polls
  755. SET num_guest_voters = {int:no_votes}, reset_poll = {int:time}
  756. WHERE id_poll = {int:id_poll}',
  757. array(
  758. 'no_votes' => 0,
  759. 'id_poll' => $bcinfo['id_poll'],
  760. 'time' => time(),
  761. )
  762. );
  763. $smcFunc['db_query']('', '
  764. UPDATE {db_prefix}poll_choices
  765. SET votes = {int:no_votes}
  766. WHERE id_poll = {int:id_poll}',
  767. array(
  768. 'no_votes' => 0,
  769. 'id_poll' => $bcinfo['id_poll'],
  770. )
  771. );
  772. $smcFunc['db_query']('', '
  773. DELETE FROM {db_prefix}log_polls
  774. WHERE id_poll = {int:id_poll}',
  775. array(
  776. 'id_poll' => $bcinfo['id_poll'],
  777. )
  778. );
  779. }
  780. // Off we go.
  781. redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
  782. }
  783. // Remove a poll from a topic without removing the topic.
  784. function RemovePoll()
  785. {
  786. global $topic, $user_info, $smcFunc;
  787. // Make sure the topic is not empty.
  788. if (empty($topic))
  789. fatal_lang_error('no_access', false);
  790. // Verify the session.
  791. checkSession('get');
  792. // Check permissions.
  793. if (!allowedTo('poll_remove_any'))
  794. {
  795. $request = $smcFunc['db_query']('', '
  796. SELECT t.id_member_started, p.id_member AS poll_starter
  797. FROM {db_prefix}topics AS t
  798. INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
  799. WHERE t.id_topic = {int:current_topic}
  800. LIMIT 1',
  801. array(
  802. 'current_topic' => $topic,
  803. )
  804. );
  805. if ($smcFunc['db_num_rows']($request) == 0)
  806. fatal_lang_error('no_access', false);
  807. list ($topicStarter, $pollStarter) = $smcFunc['db_fetch_row']($request);
  808. $smcFunc['db_free_result']($request);
  809. isAllowedTo('poll_remove_' . ($topicStarter == $user_info['id'] || ($pollStarter != 0 && $user_info['id'] == $pollStarter) ? 'own' : 'any'));
  810. }
  811. // Retrieve the poll ID.
  812. $request = $smcFunc['db_query']('', '
  813. SELECT id_poll
  814. FROM {db_prefix}topics
  815. WHERE id_topic = {int:current_topic}
  816. LIMIT 1',
  817. array(
  818. 'current_topic' => $topic,
  819. )
  820. );
  821. list ($pollID) = $smcFunc['db_fetch_row']($request);
  822. $smcFunc['db_free_result']($request);
  823. // Remove all user logs for this poll.
  824. $smcFunc['db_query']('', '
  825. DELETE FROM {db_prefix}log_polls
  826. WHERE id_poll = {int:id_poll}',
  827. array(
  828. 'id_poll' => $pollID,
  829. )
  830. );
  831. // Remove all poll choices.
  832. $smcFunc['db_query']('', '
  833. DELETE FROM {db_prefix}poll_choices
  834. WHERE id_poll = {int:id_poll}',
  835. array(
  836. 'id_poll' => $pollID,
  837. )
  838. );
  839. // Remove the poll itself.
  840. $smcFunc['db_query']('', '
  841. DELETE FROM {db_prefix}polls
  842. WHERE id_poll = {int:id_poll}',
  843. array(
  844. 'id_poll' => $pollID,
  845. )
  846. );
  847. // Finally set the topic poll ID back to 0!
  848. $smcFunc['db_query']('', '
  849. UPDATE {db_prefix}topics
  850. SET id_poll = {int:no_poll}
  851. WHERE id_topic = {int:current_topic}',
  852. array(
  853. 'current_topic' => $topic,
  854. 'no_poll' => 0,
  855. )
  856. );
  857. // Take the moderator back to the topic.
  858. redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
  859. }
  860. ?>