Login  |  Register
HTML5 Icon HTML5 Icon HTML5 Icon
TP on Social Media

Recent

Welcome, Guest. Please login or register.
Did you miss your activation email?

August 12, 2022, 06:34:30 AM

Login with username, password and session length
Members
  • Total Members: 3842
  • Latest: Kokoro
Stats
  • Total Posts: 193479
  • Total Topics: 21088
  • Online today: 50
  • Online ever: 1035
  • (November 26, 2020, 04:45:12 AM)
Users Online
Users: 0
Guests: 58
Total: 58

Author Topic: Poll Block  (Read 10241 times)

0 Members and 1 Guest are viewing this topic.

Offline WillyP

  • Support Team
  • *
  • Posts: 769
    • Planet Descent
Poll Block
« on: July 02, 2011, 07:28:57 PM »
Link to my site: Planet Descent (shows the working SMF1.1.14 code)
SMF version: SMF 2.0
TP version: TP 1.104
Theme name and version: Default - Curve
Browser Name and Version: Firefox 5.0
Mods installed:
  • Aeva Media 1.4w
  • TinyPortal  1.104
  • Ultimate Profile  0.9.1
Related Error messages: See below...

Originally, JPDeni helped me modify this code to put a poll on the front page. It is different than what the codes do that are in the block code repository. It was originally written for smf 1, then updated for 2, and broken with upgrade to rc3. You can see the code working on the SMF 1.1.14 here: http://planetdescent.net

The code that works on SMF 1 but not on 2 gives this message:
Code: [Select]
Fatal error: Function name must be a string in /misc/22/149/079/938/2/user/web/pdtest2.shirlsworld.net/Sources/TPortal.php on line 3041See here: pdtest2.shirlsworld.net/
And the code is here:
Code: [Select]
echo'<h3>Poll:</h3><br />';

//////////////////////////////////////////////////////////
// Enhanced showPoll block
// Shows poll in block from specified topic,
// or the most recent from specified board
//
// Author: Greybrow
// Version: 2007-04-24 22:00
// Features:
// shows poll (or polls) that fits in a block
//         voting or scores (when voted or can't vote)
// shows question as a topic link
// shows poll from specified topic
// shows most recent poll from specified board
//
// based on ssi_showPoll();
// added block hacks by Raysr and Thurnok from:
//    http://tpblocks.ccs-net.com/index.php?topic=25
//    http://tpblocks.ccs-net.com/index.php?topic=40
//
// usage:
// - copy whole code to phpblock.
// - at the end of the code use function
// tp_showPoll(topic number or null, 'echo' or null, board number or null)
// or
// copy the function to SSI.php
// put only the function call in phpblock
//
// examples:
// show the poll from topic 34
// tp_showPoll(34);                     
//
// show the most recent poll from the board number 5
// tp_showPoll(null,'echo',5);           
//
// keep in mind, that if board is specified, topic is ignored
// so it will display the same as above
// tp_showPoll(34,'echo',5)             
//
// put the array with poll from board 5 into $thepoll variable
// $thepoll = tp_showPoll(null,null,5); 
//
// if you call the function more than once,
// with different options, block will show more polls
// but I'm not sure if voting would work correctly :(
///////////////////////////////////////////////////////

function tp_showPoll($topic = null, $output_method = 'echo', $board = null)
{
global $db_prefix, $txt, $ID_MEMBER, $settings, $boardurl, $sc, $user_info;
global $context, $scripturl;
///added: , $scripturl
$boardsAllowed = boardsAllowedTo('poll_view');

if (empty($boardsAllowed))
return array();

if ($topic === null && isset($_REQUEST['ssi_topic']))
$topic = (int) $_REQUEST['ssi_topic'];
else
$topic = (int) $topic;

if ($board === null)
{
// board not chosen, so get the one from specified topic
$request = db_query("
SELECT
p.ID_POLL, p.question, p.votingLocked, p.hideResults, p.expireTime, p.maxVotes, b.ID_BOARD
FROM ({$db_prefix}topics AS t, {$db_prefix}polls AS p, {$db_prefix}boards AS b)
WHERE p.ID_POLL = t.ID_POLL
AND t.ID_TOPIC = $topic
AND b.ID_BOARD = t.ID_BOARD
AND $user_info[query_see_board]" . (!in_array(0, $boardsAllowed) ? "
AND b.ID_BOARD IN (" . implode(', ', $boardsAllowed) . ")" : '') . "
LIMIT 1", __FILE__, __LINE__);
}
else
{
// board chosen, so lets try to get the most recent poll from it
$board = (int) $board;
$request = db_query("
SELECT
p.ID_POLL, p.question, p.votingLocked, p.hideResults, p.expireTime, p.maxVotes, b.ID_BOARD, t.ID_TOPIC
FROM ({$db_prefix}topics AS t, {$db_prefix}polls AS p, {$db_prefix}boards AS b)
WHERE p.ID_POLL = t.ID_POLL
AND b.ID_BOARD = t.ID_BOARD
AND b.ID_BOARD = $board
AND $user_info[query_see_board]" . (!in_array(0, $boardsAllowed) ? "
AND $board IN (" . implode(', ', $boardsAllowed) . ")" : '') . "
ORDER BY p.ID_POLL DESC
LIMIT 1", __FILE__, __LINE__);
}

// Either this topic has no poll, or the user cannot view it.
if (mysql_num_rows($request) == 0)
return array();

$row = mysql_fetch_assoc($request);
mysql_free_result($request);

if($topic == 0)
$topic = (int)$row['ID_TOPIC'];

// Check if they can vote.
if ((!empty($row['expireTime']) && $row['expireTime'] < time()) || $user_info['is_guest'] || !empty($row['votingLocked']) || !allowedTo('poll_vote', $row['ID_BOARD']))
$allow_vote = false;
else
{
$request = db_query("
SELECT ID_MEMBER
FROM {$db_prefix}log_polls
WHERE ID_POLL = $row[ID_POLL]
AND ID_MEMBER = $ID_MEMBER
LIMIT 1", __FILE__, __LINE__);
$allow_vote = mysql_num_rows($request) == 0;
mysql_free_result($request);
}
$request = db_query("
SELECT COUNT(DISTINCT ID_MEMBER)
FROM {$db_prefix}log_polls
WHERE ID_POLL = $row[ID_POLL]", __FILE__, __LINE__);
list ($total) = mysql_fetch_row($request);
mysql_free_result($request);

$request = db_query("
SELECT ID_CHOICE, label, votes
FROM {$db_prefix}poll_choices
WHERE ID_POLL = $row[ID_POLL]", __FILE__, __LINE__);
$options = array();
$total_votes = 0;
while ($rowChoice = mysql_fetch_assoc($request))
{
censorText($rowChoice['label']);

$options[$rowChoice['ID_CHOICE']] = array($rowChoice['label'], $rowChoice['votes']);
$total_votes += $rowChoice['votes'];
}
mysql_free_result($request);

$return = array(
'id' => $row['ID_POLL'],
'image' => empty($pollinfo['votingLocked']) ? 'poll' : 'locked_poll',
'question' => $row['question'],
'total_votes' => $total,
'is_locked' => !empty($pollinfo['votingLocked']),
'allow_vote' => $allow_vote,
'topic' => $topic
);

// Calculate the percentages and bar lengths...
$divisor = $total_votes == 0 ? 1 : $total_votes;
foreach ($options as $i => $option)
{
$bar = floor(($option[1] * 100) / $divisor);
$barWide = $bar == 0 ? 1 : floor(($bar * 5) / 6);
$return['options'][$i] = array(
'id' => 'options-' . $i,
'percent' => $bar,
'votes' => $option[1],
'bar' => '<span style="white-space: nowrap;"><img src="' . $settings['images_url'] . '/poll_left.gif" alt="" /><img src="' . $settings['images_url'] . '/poll_middle.gif" width="' . $barWide . '" height="12" alt="-" /><img src="' . $settings['images_url'] . '/poll_right.gif" alt="" /></span>',
'option' => parse_bbc($option[0]),
'vote_button' => '<input type="' . ($row['maxVotes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '" class="check" />'
);
}

$return['allowed_warning'] = $row['maxVotes'] > 1 ? sprintf($txt['poll_options6'], $row['maxVotes']) : '';

if ($output_method != 'echo')
return $return;

if ($return['allow_vote'])
{
echo '
<form action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
<input type="hidden" name="poll" value="', $return['id'], '" />
<table border="0" cellspacing="1" cellpadding="0" class="ssi_table">
<tr>
<td colspan="2" class="smalltext"><a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a></td>
</tr>
<tr>
<td class="smalltext">', $return['allowed_warning'], '</td>
</tr>';
foreach ($return['options'] as $option)
echo '
<tr>
<td class="smalltext"><label for="', $option['id'], '">', $option['vote_button'], '</td><td class="smalltext">', $option['option'], '</label></td>
</tr>';
echo '
<tr>
<td colspan="2" class="smalltext"><input type="submit" value="', $txt['smf23'], '" /></td>
</tr>
</table>
<input type="hidden" name="sc" value="', $sc, '" />
</form>';
}
///////////// /// added code by willyP, per jpdeni:
elseif ($user_info['is_guest'])
{
echo '

<a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a><br /><ul>';
foreach ($return['options'] as $option)
echo '
<li>', $option['option'], '</li>';
echo '
</ul>
If you would like to vote in this poll, please <a href="' . $scripturl . '?action=login">login</a> or <a href="' . $scripturl . '?action=register">register</a>.';
}

/////////////end added code by willyP

else
{
echo '
<table border="0" cellspacing="1" cellpadding="0" class="ssi_table">
<tr>
<td colspan="2" class="smalltext"><a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a></td>
</tr>';
foreach ($return['options'] as $option)
echo '
<tr>
<td colspan="2" align="left" valign="top" style="font-style: italic" class="smalltext">', $option['option'], '</td>
</tr>
<tr>
<td align="left" class="smalltext">', $option['bar'], '</td>
<td align="left" class="smalltext">', $option['votes'], ' (', $option['percent'], '%)</td>
</tr>';
echo '
<tr>
<td colspan="2" class="smalltext"><b>', $txt['smf24'], ': ', $return['total_votes'], '</b></td>
</tr>
</table>';
}
}

///////////////////////////////////////
// display most recent poll from board number 1
tp_showPoll(null,'echo',15);

echo'<hr>';
(see it working at http://planetdescent.net

The code that was working on SMF2RC2, but does not work in 2.0, and gives this message error message:
Code: [Select]
Fatal error: Call to undefined function tpdb_query() in /misc/22/149/079/938/2/user/web/test.planetdescent.net/Sources/Load.php(2105) : eval()'d code(114) : eval()'d code on line 82See at: http://www.test.planetdescent.net/
Code: [Select]
echo'<h3>Poll:</h3><br />';

//////////////////////////////////////////////////////////
// Enhanced showPoll block
// Shows poll in block from specified topic,
// or the most recent from specified board
//
// Author:   Greybrow
// Version:   2007-04-24 22:00
// Features:
//   shows poll (or polls) that fits in a block
//         voting or scores (when voted or can't vote)
//   shows question as a topic link
//   shows poll from specified topic
//   shows most recent poll from specified board
//
// based on ssi_showPoll();
// added block hacks by Raysr and Thurnok from:
//    http://tpblocks.ccs-net.com/index.php?topic=25
//    http://tpblocks.ccs-net.com/index.php?topic=40
//
// usage:
// - copy whole code to phpblock.
// - at the end of the code use function
// tp_showPoll(topic number or null, 'echo' or null, board number or null)
// or
// copy the function to SSI.php
// put only the function call in phpblock
//
// examples:
// show the poll from topic 34
// tp_showPoll(34);                     
//
// show the most recent poll from the board number 5
// tp_showPoll(null,'echo',5);           
//
// keep in mind, that if board is specified, topic is ignored
// so it will display the same as above
// tp_showPoll(34,'echo',5)             
//
// put the array with poll from board 5 into $thepoll variable
// $thepoll = tp_showPoll(null,null,5);
//
// if you call the function more than once,
// with different options, block will show more polls
// but I'm not sure if voting would work correctly :(
///////////////////////////////////////////////////////

function tp_showPoll($topic = null, $output_method = 'echo', $board = null)
{
   global $db_prefix, $txt, $settings, $boardurl, $sc, $user_info;
   global $context, $scripturl;
///added: , $scripturl
   $boardsAllowed = boardsAllowedTo('poll_view');

   if (empty($boardsAllowed))
      return array();

   if ($topic === null && isset($_REQUEST['ssi_topic']))
      $topic = (int) $_REQUEST['ssi_topic'];
   else
      $topic = (int) $topic;

   if ($board === null)
   {
      // board not chosen, so get the one from specified topic
      $request = tpdb_query("
         SELECT
            p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, b.id_board
         FROM ({$db_prefix}topics AS t, {$db_prefix}polls AS p, {$db_prefix}boards AS b)
         WHERE p.id_poll = t.id_poll
            AND t.id_topic = $topic
            AND b.id_board = t.id_board
            AND $user_info[query_see_board]" . (!in_array(0, $boardsAllowed) ? "
            AND b.id_board IN (" . implode(', ', $boardsAllowed) . ")" : '') . "
         LIMIT 1", __FILE__, __LINE__);
   }
   else
   {
      // board chosen, so lets try to get the most recent poll from it
      $board = (int) $board;
      $request = tpdb_query("
         SELECT
            p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, b.id_board, t.id_topic
         FROM ({$db_prefix}topics AS t, {$db_prefix}polls AS p, {$db_prefix}boards AS b)
         WHERE   p.id_poll = t.id_poll
            AND b.id_board = t.id_board
            AND b.id_board = $board
            AND $user_info[query_see_board]" . (!in_array(0, $boardsAllowed) ? "
            AND $board IN (" . implode(', ', $boardsAllowed) . ")" : '') . "
         ORDER BY p.id_poll DESC
         LIMIT 1", __FILE__, __LINE__);
   }

   // Either this topic has no poll, or the user cannot view it.
   if (mysql_num_rows($request) == 0)
      return array();

   $row = mysql_fetch_assoc($request);
   mysql_free_result($request);

   if($topic == 0)
      $topic = (int)$row['id_topic'];

   // Check if they can vote.
   if ((!empty($row['expire_time']) && $row['expire_time'] < time()) || $user_info['is_guest'] || !empty($row['voting_locked']) || !allowedTo('poll_vote', $row['id_board']))
      $allow_vote = false;
   else
   {
      $request = tpdb_query("
         SELECT id_member
         FROM {$db_prefix}log_polls
         WHERE id_poll = $row[id_poll]
            AND id_member = $user_info[id]
         LIMIT 1", __FILE__, __LINE__);
      $allow_vote = mysql_num_rows($request) == 0;
      mysql_free_result($request);
   }
   $request = tpdb_query("
      SELECT COUNT(DISTINCT id_member)
      FROM {$db_prefix}log_polls
      WHERE id_poll = $row[id_poll]", __FILE__, __LINE__);
   list ($total) = mysql_fetch_row($request);
   mysql_free_result($request);

   $request = tpdb_query("
      SELECT id_choice, label, votes
      FROM {$db_prefix}poll_choices
      WHERE id_poll = $row[id_poll]", __FILE__, __LINE__);
   $options = array();
   $total_votes = 0;
   while ($rowChoice = mysql_fetch_assoc($request))
   {
      censorText($rowChoice['label']);

      $options[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
      $total_votes += $rowChoice['votes'];
   }
   mysql_free_result($request);

   $return = array(
      'id' => $row['id_poll'],
      'image' => empty($pollinfo['voting_locked']) ? 'poll' : 'locked_poll',
      'question' => $row['question'],
      'total_votes' => $total,
      'is_locked' => !empty($pollinfo['voting_locked']),
      'allow_vote' => $allow_vote,
      'topic' => $topic
   );

   // Calculate the percentages and bar lengths...
   $divisor = $total_votes == 0 ? 1 : $total_votes;
   foreach ($options as $i => $option)
   {
      $bar = floor(($option[1] * 100) / $divisor);
      $barWide = $bar == 0 ? 1 : floor(($bar * 5) / 6);
      $return['options'][$i] = array(
         'id' => 'options-' . $i,
         'percent' => $bar,
         'votes' => $option[1],
         'bar' => '<span style="white-space: nowrap;"><img src="' . $settings['images_url'] . '/poll_left.gif" alt="" /><img src="' . $settings['images_url'] . '/poll_middle.gif" width="' . $barWide . '" height="12" alt="-" /><img src="' . $settings['images_url'] . '/poll_right.gif" alt="" /></span>',
         'option' => parse_bbc($option[0]),
         'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '" class="check" />'
      );
   }

   $return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options6'], $row['max_votes']) : '';

   if ($output_method != 'echo')
      return $return;

   if ($return['allow_vote'])
   {
      echo '
         <form action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
            <input type="hidden" name="poll" value="', $return['id'], '" />
            <table border="0" cellspacing="1" cellpadding="0" class="ssi_table">
               <tr>
                  <td colspan="2" class="smalltext"><a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a></td>
               </tr>
               <tr>
                  <td class="smalltext">', $return['allowed_warning'], '</td>
               </tr>';
      foreach ($return['options'] as $option)
         echo '
               <tr>
                  <td class="smalltext"><label for="', $option['id'], '">', $option['vote_button'], '</td><td class="smalltext">', $option['option'], '</label></td>
               </tr>';
      echo '
               <tr>
                  <td colspan="2" class="smalltext"><input type="submit" value="Submit Vote" /></td>
               </tr>
            </table>
            <input type="hidden" name="sc" value="', $sc, '" />
         </form>';
   }
/////////////   /// added code by willyP, per jpdeni:
   elseif ($user_info['is_guest'])
   {
      echo '
           
               <a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a><br /><ul>';
      foreach ($return['options'] as $option)
         echo '
               <li>', $option['option'], '</li>';
      echo '
            </ul>
         If you would like to vote in this poll, please <a href="' . $scripturl . '?action=login">login</a> or <a href="' . $scripturl . '?action=register">register</a>.';
   }

/////////////end added code by willyP

else
   {
      echo '
            <table border="0" cellspacing="1" cellpadding="0" class="ssi_table">
               <tr>
                  <td colspan="2" class="smalltext"><a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a></td>
               </tr>';
      foreach ($return['options'] as $option)
         echo '
               <tr>
                  <td colspan="2" align="left" valign="top" style="font-style: italic" class="smalltext">', $option['option'], '</td>
               </tr>
               <tr>
                  <td align="left" class="smalltext">', $option['bar'], '</td>
                  <td align="left" class="smalltext">', $option['votes'], ' (', $option['percent'], '%)</td>
               </tr>';
      echo '
               <tr>
                  <td colspan="2" class="smalltext"><b>Total Votes: ', $return['total_votes'], '</b></td>
               </tr>
            </table>';
   }
}

///////////////////////////////////////
// display most recent poll from board number 1
tp_showPoll(null,'echo',15);

echo'<hr>';
« Last Edit: July 05, 2011, 06:07:58 AM by WillyP »

Offline ZarPrime

  • Friends
  • *
  • Posts: 4653
Re: Poll Block
« Reply #1 on: July 02, 2011, 09:26:26 PM »
Yep, that's one of the snippets that will need to have the old TP DB queries changed to the new SMF ones for 2.0.  Hopefully Freddy will have a chance to look at this as I'm not quite up to speed on all the changes yet.

ZarPrime

Offline Freddy

  • Moderator
  • *
  • Posts: 1615
    • AiDreams
Re: Poll Block
« Reply #2 on: July 03, 2011, 06:56:09 AM »
Working on this now..

Offline Freddy

  • Moderator
  • *
  • Posts: 1615
    • AiDreams
Re: Poll Block
« Reply #3 on: July 03, 2011, 07:25:28 AM »
This may or may not work.  I can't test it right now :

Edit: I managed to test it a little although the SMF2 graphics for the bars don't seem to be in the images directory as they should be - even the SSI.php recent polls example does not work right.

So hopefully you have those graphics in your directories already.

Also had to change the FORM a little to use the session variable properly, so that you can vote from within the block.

Apart from the graphics I have it working on SMF2Gold and the latest TPRC2.

Code: [Select]
echo'<h3>Poll:</h3><br />';

//////////////////////////////////////////////////////////
// Enhanced showPoll block
// Shows poll in block from specified topic,
// or the most recent from specified board
//
// Author:   Greybrow
// Version:   2007-04-24 22:00
// Features:
//   shows poll (or polls) that fits in a block
//         voting or scores (when voted or can't vote)
//   shows question as a topic link
//   shows poll from specified topic
//   shows most recent poll from specified board
//
// based on ssi_showPoll();
// added block hacks by Raysr and Thurnok from:
//    http://tpblocks.ccs-net.com/index.php?topic=25
//    http://tpblocks.ccs-net.com/index.php?topic=40
//
// usage:
// - copy whole code to phpblock.
// - at the end of the code use function
// tp_showPoll(topic number or null, 'echo' or null, board number or null)
// or
// copy the function to SSI.php
// put only the function call in phpblock
//
// examples:
// show the poll from topic 34
// tp_showPoll(34);                     
//
// show the most recent poll from the board number 5
// tp_showPoll(null,'echo',5);           
//
// keep in mind, that if board is specified, topic is ignored
// so it will display the same as above
// tp_showPoll(34,'echo',5)             
//
// put the array with poll from board 5 into $thepoll variable
// $thepoll = tp_showPoll(null,null,5);
//
// if you call the function more than once,
// with different options, block will show more polls
// but I'm not sure if voting would work correctly :(
///////////////////////////////////////////////////////

function tp_showPoll($topic = null, $output_method = 'echo', $board = null)
{
global $db_prefix, $txt, $settings, $boardurl, $sc, $user_info;
global $context, $scripturl, $smcFunc;
///added: , $scripturl
$boardsAllowed = boardsAllowedTo('poll_view');

if (empty($boardsAllowed))
return array();

if ($topic === null && isset($_REQUEST['ssi_topic']))
$topic = (int) $_REQUEST['ssi_topic'];
else
$topic = (int) $topic;

if ($board === null)
{
// board not chosen, so get the one from specified topic
$request = $smcFunc['db_query']("", "
SELECT
p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, b.id_board
FROM ({db_prefix}topics AS t, {db_prefix}polls AS p, {db_prefix}boards AS b)
WHERE p.id_poll = t.id_poll
AND t.id_topic = {int:topic}
AND b.id_board = t.id_board
AND $user_info[query_see_board]
" . (!in_array(0, $boardsAllowed) ? "
AND b.id_board IN {array_int:boardsallowed}" : '') . "
LIMIT 1",
array(
'topic' => $topic,
'boardsallowed' => $boardsAllowed,

)
);
}
else
{
// board chosen, so lets try to get the most recent poll from it
$board = (int) $board;
$request = $smcFunc['db_query']("", "
SELECT
p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, b.id_board, t.id_topic
FROM ({db_prefix}topics AS t, {db_prefix}polls AS p, {db_prefix}boards AS b)
WHERE   p.id_poll = t.id_poll
AND b.id_board = t.id_board
AND b.id_board = {int:board}
AND $user_info[query_see_board]
" . (!in_array(0, $boardsAllowed) ? "
AND {int:board} IN {array_int:boardsallowed}" : '') . "
ORDER BY p.id_poll DESC
LIMIT 1",
array(
'board' => $board,
'boardsallowed' => $boardsAllowed,
)
);
}
echo 'One';
// Either this topic has no poll, or the user cannot view it.
if (mysql_num_rows($request) == 0)
return array();

$row = mysql_fetch_assoc($request);

$smcFunc['db_free_result']($request);

if($topic == 0)
$topic = (int)$row['id_topic'];

// Check if they can vote.
if ((!empty($row['expire_time']) && $row['expire_time'] < time()) || $user_info['is_guest'] || !empty($row['voting_locked']) || !allowedTo('poll_vote', $row['id_board']))
$allow_vote = false;
else
{
$request = $smcFunc['db_query']("", "
SELECT id_member
FROM {db_prefix}log_polls
WHERE id_poll = {int:idpoll}
AND id_member = {int:userinfo}
LIMIT 1",
array(
'idpoll' => $row['id_poll'],
'userinfo' => $user_info['id'],
)
);

$allow_vote = mysql_num_rows($request) == 0;
$smcFunc['db_free_result']($request);
}

$request = $smcFunc['db_query']("", "
SELECT COUNT(DISTINCT id_member)
FROM {db_prefix}log_polls
WHERE id_poll = {int:idpoll}",
array(
'idpoll' => $row['id_poll']
)
);

list ($total) = mysql_fetch_row($request);
$smcFunc['db_free_result']($request);

$request = $smcFunc['db_query']("", "
SELECT id_choice, label, votes
FROM {db_prefix}poll_choices
WHERE id_poll = {int:idpoll}",
array(
'idpoll' => $row['id_poll']
)
);

$options = array();
$total_votes = 0;
while ($rowChoice = mysql_fetch_assoc($request))
{
censorText($rowChoice['label']);

$options[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
$total_votes += $rowChoice['votes'];
}
$smcFunc['db_free_result']($request);

$return = array(
'id' => $row['id_poll'],
'image' => empty($pollinfo['voting_locked']) ? 'poll' : 'locked_poll',
'question' => $row['question'],
'total_votes' => $total,
'is_locked' => !empty($pollinfo['voting_locked']),
'allow_vote' => $allow_vote,
'topic' => $topic
);

// Calculate the percentages and bar lengths...
$divisor = $total_votes == 0 ? 1 : $total_votes;
foreach ($options as $i => $option)
{
$bar = floor(($option[1] * 100) / $divisor);
$barWide = $bar == 0 ? 1 : floor(($bar * 5) / 6);
$return['options'][$i] = array(
'id' => 'options-' . $i,
'percent' => $bar,
'votes' => $option[1],
'bar' => '<span style="white-space: nowrap;"><img src="' . $settings['images_url'] . '/poll_left.gif" alt="" /><img src="' . $settings['images_url'] . '/poll_middle.gif" width="' . $barWide . '" height="12" alt="-" /><img src="' . $settings['images_url'] . '/poll_right.gif" alt="" /></span>',
'option' => parse_bbc($option[0]),
'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '" class="check" />'
);
}

$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options6'], $row['max_votes']) : '';

if ($output_method != 'echo')
return $return;

if ($return['allow_vote'])
{
echo '
<form action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
<input type="hidden" name="poll" value="', $return['id'], '" />
<table border="0" cellspacing="1" cellpadding="0" class="ssi_table">
<tr>
<td colspan="2" class="smalltext"><a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a></td>
</tr>
<tr>
<td class="smalltext">', $return['allowed_warning'], '</td>
</tr>';
foreach ($return['options'] as $option)
echo '
<tr>
<td class="smalltext"><label for="', $option['id'], '">', $option['vote_button'], '</td><td class="smalltext">', $option['option'], '</label></td>
</tr>';
echo '
<tr>
<td colspan="2" class="smalltext"><input type="submit" value="Submit Vote" /></td>
</tr>
</table>
<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
</form>';
}
/////////////   /// added code by willyP, per jpdeni:
elseif ($user_info['is_guest'])
{
echo '

<a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a><br /><ul>';
foreach ($return['options'] as $option)
echo '
<li>', $option['option'], '</li>';
echo '
</ul>
If you would like to vote in this poll, please <a href="' . $scripturl . '?action=login">login</a> or <a href="' . $scripturl . '?action=register">register</a>.';
}

/////////////end added code by willyP

else
{
echo '
<table border="0" cellspacing="1" cellpadding="0" class="ssi_table">
<tr>
<td colspan="2" class="smalltext"><a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a></td>
</tr>';
foreach ($return['options'] as $option)
echo '
<tr>
<td colspan="2" align="left" valign="top" style="font-style: italic" class="smalltext">', $option['option'], '</td>
</tr>
<tr>
<td align="left" class="smalltext">', $option['bar'], '</td>
<td align="left" class="smalltext">', $option['votes'], ' (', $option['percent'], '%)</td>
</tr>';
echo '
<tr>
<td colspan="2" class="smalltext"><b>Total Votes: ', $return['total_votes'], '</b></td>
</tr>
</table>';
}
}

///////////////////////////////////////
// display most recent poll from board number 1
tp_showPoll(null,'echo',15);

echo'<hr>';
« Last Edit: July 03, 2011, 08:14:29 AM by Freddy »

Offline WillyP

  • Support Team
  • *
  • Posts: 769
    • Planet Descent
Re: Poll Block
« Reply #4 on: July 03, 2011, 12:35:03 PM »
Mint! Thank you very much!

Edit... OOPS, spoke to soon... If you log out you get "Database Error
Please try again. If you come back to this error screen, report the error to an administrator."

Offline Freddy

  • Moderator
  • *
  • Posts: 1615
    • AiDreams
Re: Poll Block
« Reply #5 on: July 03, 2011, 01:27:51 PM »
Look in the error log and tell me what the error says please Willy.  I will work on it tomorrow now.

Offline WillyP

  • Support Team
  • *
  • Posts: 769
    • Planet Descent
Re: Poll Block
« Reply #6 on: July 03, 2011, 02:19:43 PM »
Thanks, Freddy, here is the error log from the forum, the server log is empty:

Quote
http://pdtest2.shirlsworld.net/index.php?

Database Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '10, 1, 2, 3, 16, 4, 5, 6, 7, 8, 9, 11, 13, 14, 15
ORDER BY p.id_poll DESC
' at line 9

File: /misc/22/149/079/938/2/user/web/pdtest2.shirlsworld.net/Sources/Load.php(2173) : eval()'d code(114) : eval()'d code
Line: 105

This error shows up for every guest view of the front page, there are no errors generated when logged in.

Offline Freddy

  • Moderator
  • *
  • Posts: 1615
    • AiDreams
Re: Poll Block
« Reply #7 on: July 04, 2011, 06:34:38 AM »
Okay it looks like I missed out some brackets in the database queries. Try this..

Code: [Select]
echo'<h3>Poll:</h3><br />';

//////////////////////////////////////////////////////////
// Enhanced showPoll block
// Shows poll in block from specified topic,
// or the most recent from specified board
//
// Author:   Greybrow
// Version:   2007-04-24 22:00
// Features:
//   shows poll (or polls) that fits in a block
//         voting or scores (when voted or can't vote)
//   shows question as a topic link
//   shows poll from specified topic
//   shows most recent poll from specified board
//
// based on ssi_showPoll();
// added block hacks by Raysr and Thurnok from:
//    http://tpblocks.ccs-net.com/index.php?topic=25
//    http://tpblocks.ccs-net.com/index.php?topic=40
//
// usage:
// - copy whole code to phpblock.
// - at the end of the code use function
// tp_showPoll(topic number or null, 'echo' or null, board number or null)
// or
// copy the function to SSI.php
// put only the function call in phpblock
//
// examples:
// show the poll from topic 34
// tp_showPoll(34);                     
//
// show the most recent poll from the board number 5
// tp_showPoll(null,'echo',5);           
//
// keep in mind, that if board is specified, topic is ignored
// so it will display the same as above
// tp_showPoll(34,'echo',5)             
//
// put the array with poll from board 5 into $thepoll variable
// $thepoll = tp_showPoll(null,null,5);
//
// if you call the function more than once,
// with different options, block will show more polls
// but I'm not sure if voting would work correctly :(
///////////////////////////////////////////////////////

function tp_showPoll($topic = null, $output_method = 'echo', $board = null)
{
global $db_prefix, $txt, $settings, $boardurl, $sc, $user_info;
global $context, $scripturl, $smcFunc;
///added: , $scripturl
$boardsAllowed = boardsAllowedTo('poll_view');

if (empty($boardsAllowed))
return array();

if ($topic === null && isset($_REQUEST['ssi_topic']))
$topic = (int) $_REQUEST['ssi_topic'];
else
$topic = (int) $topic;

if ($board === null)
{
// board not chosen, so get the one from specified topic
$request = $smcFunc['db_query']("", "
SELECT
p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, b.id_board
FROM ({db_prefix}topics AS t, {db_prefix}polls AS p, {db_prefix}boards AS b)
WHERE p.id_poll = t.id_poll
AND t.id_topic = {int:topic}
AND b.id_board = t.id_board
AND $user_info[query_see_board]
" . (!in_array(0, $boardsAllowed) ? "
AND b.id_board IN ({array_int:boardsallowed})" : '') . "
LIMIT 1",
array(
'topic' => $topic,
'boardsallowed' => $boardsAllowed,

)
);
}
else
{
// board chosen, so lets try to get the most recent poll from it
$board = (int) $board;
$request = $smcFunc['db_query']("", "
SELECT
p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, b.id_board, t.id_topic
FROM ({db_prefix}topics AS t, {db_prefix}polls AS p, {db_prefix}boards AS b)
WHERE   p.id_poll = t.id_poll
AND b.id_board = t.id_board
AND b.id_board = {int:board}
AND $user_info[query_see_board]
" . (!in_array(0, $boardsAllowed) ? "
AND {int:board} IN ({array_int:boardsallowed})" : '') . "
ORDER BY p.id_poll DESC
LIMIT 1",
array(
'board' => $board,
'boardsallowed' => $boardsAllowed,
)
);
}

// Either this topic has no poll, or the user cannot view it.
if (mysql_num_rows($request) == 0)
return array();

$row = mysql_fetch_assoc($request);

$smcFunc['db_free_result']($request);

if($topic == 0)
$topic = (int)$row['id_topic'];

// Check if they can vote.
if ((!empty($row['expire_time']) && $row['expire_time'] < time()) || $user_info['is_guest'] || !empty($row['voting_locked']) || !allowedTo('poll_vote', $row['id_board']))
$allow_vote = false;
else
{
$request = $smcFunc['db_query']("", "
SELECT id_member
FROM {db_prefix}log_polls
WHERE id_poll = {int:idpoll}
AND id_member = {int:userinfo}
LIMIT 1",
array(
'idpoll' => $row['id_poll'],
'userinfo' => $user_info['id'],
)
);

$allow_vote = mysql_num_rows($request) == 0;
$smcFunc['db_free_result']($request);
}

$request = $smcFunc['db_query']("", "
SELECT COUNT(DISTINCT id_member)
FROM {db_prefix}log_polls
WHERE id_poll = {int:idpoll}",
array(
'idpoll' => $row['id_poll']
)
);

list ($total) = mysql_fetch_row($request);
$smcFunc['db_free_result']($request);

$request = $smcFunc['db_query']("", "
SELECT id_choice, label, votes
FROM {db_prefix}poll_choices
WHERE id_poll = {int:idpoll}",
array(
'idpoll' => $row['id_poll']
)
);

$options = array();
$total_votes = 0;
while ($rowChoice = mysql_fetch_assoc($request))
{
censorText($rowChoice['label']);

$options[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
$total_votes += $rowChoice['votes'];
}
$smcFunc['db_free_result']($request);

$return = array(
'id' => $row['id_poll'],
'image' => empty($pollinfo['voting_locked']) ? 'poll' : 'locked_poll',
'question' => $row['question'],
'total_votes' => $total,
'is_locked' => !empty($pollinfo['voting_locked']),
'allow_vote' => $allow_vote,
'topic' => $topic
);

// Calculate the percentages and bar lengths...
$divisor = $total_votes == 0 ? 1 : $total_votes;
foreach ($options as $i => $option)
{
$bar = floor(($option[1] * 100) / $divisor);
$barWide = $bar == 0 ? 1 : floor(($bar * 5) / 6);
$return['options'][$i] = array(
'id' => 'options-' . $i,
'percent' => $bar,
'votes' => $option[1],
'bar' => '<span style="white-space: nowrap;"><img src="' . $settings['images_url'] . '/poll_left.gif" alt="" /><img src="' . $settings['images_url'] . '/poll_middle.gif" width="' . $barWide . '" height="12" alt="-" /><img src="' . $settings['images_url'] . '/poll_right.gif" alt="" /></span>',
'option' => parse_bbc($option[0]),
'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '" class="check" />'
);
}

$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options6'], $row['max_votes']) : '';

if ($output_method != 'echo')
return $return;

if ($return['allow_vote'])
{
echo '
<form action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
<input type="hidden" name="poll" value="', $return['id'], '" />
<table border="0" cellspacing="1" cellpadding="0" class="ssi_table">
<tr>
<td colspan="2" class="smalltext"><a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a></td>
</tr>
<tr>
<td class="smalltext">', $return['allowed_warning'], '</td>
</tr>';
foreach ($return['options'] as $option)
echo '
<tr>
<td class="smalltext"><label for="', $option['id'], '">', $option['vote_button'], '</td><td class="smalltext">', $option['option'], '</label></td>
</tr>';
echo '
<tr>
<td colspan="2" class="smalltext"><input type="submit" value="Submit Vote" /></td>
</tr>
</table>
<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
</form>';
}
/////////////   /// added code by willyP, per jpdeni:
elseif ($user_info['is_guest'])
{
echo '

<a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a><br /><ul>';
foreach ($return['options'] as $option)
echo '
<li>', $option['option'], '</li>';
echo '
</ul>
If you would like to vote in this poll, please <a href="' . $scripturl . '?action=login">login</a> or <a href="' . $scripturl . '?action=register">register</a>.';
}

/////////////end added code by willyP

else
{
echo '
<table border="0" cellspacing="1" cellpadding="0" class="ssi_table">
<tr>
<td colspan="2" class="smalltext"><a href="', $boardurl, '/index.php?topic=', $return['topic'], '"><b>', $return['question'], '</b></a></td>
</tr>';
foreach ($return['options'] as $option)
echo '
<tr>
<td colspan="2" align="left" valign="top" style="font-style: italic" class="smalltext">', $option['option'], '</td>
</tr>
<tr>
<td align="left" class="smalltext">', $option['bar'], '</td>
<td align="left" class="smalltext">', $option['votes'], ' (', $option['percent'], '%)</td>
</tr>';
echo '
<tr>
<td colspan="2" class="smalltext"><b>Total Votes: ', $return['total_votes'], '</b></td>
</tr>
</table>';
}
}

///////////////////////////////////////
// display most recent poll from board number 1
tp_showPoll(null,'echo',15);

echo'<hr>';

Offline WillyP

  • Support Team
  • *
  • Posts: 769
    • Planet Descent
Re: Poll Block
« Reply #8 on: July 04, 2011, 07:05:49 AM »
Looks good!

Thanks for taking the time to help me with this, Freddy.

Any reason not to add this to the block codes repository here?

Offline Freddy

  • Moderator
  • *
  • Posts: 1615
    • AiDreams
Re: Poll Block
« Reply #9 on: July 04, 2011, 07:22:27 AM »
No problem and feel free  O0