<?php
/*
Plugin Name: Democracy (de)
Plugin URI: http://blog.jalenack.com/archives/democracy//
Description: Ajax Umfrage Plugin
Version: 1.0 RC 1
Author: Andrew Sutherland, deVersion: Frank Bueltge
Author URI: http://blog.jalenack.com/ , deVersion: http://bueltge.de/
*/

// With hat tips from Denis de Bernhardy
// http://semiologic.com

// Released under the CC GPL 2.0:
// http://creativecommons.org/licenses/GPL/2.0/

// The current version of this plugin
$jal_dem_version "1.0 RC 1";

// Required user level to access admin panel
$jal_dem_admin_level 8;

// When viewing results, order the answers by votes or by id?
// To order by votes, set this to TRUE
$jal_order_answers FALSE;

// HTML to go around the poll's question
// Depending on your theme, you may want '<strong>';
$jal_before_question '<h2 id="poll-question">';

// Closing tags for the HTML around the question
// '</strong>'
$jal_after_question '</h2>';

// Graph percentages as a percent of the total votes or of the winner
// If it is false, then the winning vote will be 100% of the graph, and the other answers will be a percent of that,
$jal_graph_from_total TRUE;

// The length of time, in *seconds*, that cookies should remain. Default: 3 months
// Note that IP logging will still be in effect when you lower this number
// To take away IP stopping functionality, comment out the checkIP() calls at the bottom
$jal_cookietime 60*60*24*30*3;
// Change it in the js file as well



/*/\\//\\//\\//\\//\\//\\//\\//

    No edits needed below here
     
//\\//\\//\\//\\//\\//\\//\\/*/

function jal_edit_poll () {
    global 
$wpdb$table_prefix$user_level$jal_dem_admin_level;
    
    
// Security
    
get_currentuserinfo();
    if (
$user_level <  $jal_dem_admin_level) { die('Nice try, you cheeky monkey!'); }
    
    
// read which aids are in this poll
    
$edits explode(" "$_POST['editable']);
    
    
// Allow users to edit poll?
    
$allowusers = (isset($_POST['allowNewAnswers'])) ? "1" "0";
    
    
// update the question
    
$wpdb->query("UPDATE ".$table_prefix."democracyQ SET question='".$wpdb->escape($_POST['question'])."', allowusers = '".$allowusers."' WHERE id = ".$wpdb->escape($_POST['poll_id']));
    
    
// loop for how many existing answers
    
for($i 0$i count($edits); $i++) {
        
// if the field is empty, delete it.
        
if (empty($_POST['answer'.$edits[$i]])) {
            
$wpdb->query("DELETE FROM ".$table_prefix."democracyA WHERE qid = ".$_POST['poll_id']." AND aid =".$edits[$i]);
        
// otherwise, make changes
        
} else {
            
$wpdb->query("UPDATE ".$table_prefix."democracyA SET answers='".$wpdb->escape($_POST['answer'.$edits[$i]])."' WHERE qid = ".$wpdb->escape($_POST['poll_id'])." AND aid =".$wpdb->escape($edits[$i]));
        }
    }
    
    
// check for new answers
    
while ($i 16) {   
        if(!empty(
$_POST['new'.$i])) {
            
$wpdb->query("INSERT INTO ".$table_prefix."democracyA (qid, answers, votes) VALUES (".$wpdb->escape($_POST['poll_id']).", '".$wpdb->escape($_POST['new'.$i])."', 0)");
        }
        
$i++;
    }
}

// Why does the htmlentities bomb &ap; ?
function jal_htmlentities_ap ($s) {
    
$s htmlentities($sENT_QUOTES'UTF-8');
    return 
str_replace("&ap;""&#8776;"$s);
}


function 
jal_activate_poll () {
    global 
$wpdb$table_prefix$user_level$jal_dem_admin_level;
    
    
// Security
    
get_currentuserinfo();
    if (
$user_level <  $jal_dem_admin_level) { die('Nice try, you cheeky monkey!'); }

    
// Deactivate the old active poll
    
$wpdb->query("UPDATE ".$table_prefix."democracyQ SET active='0' WHERE active = '1'");
    
// Activate the new poll
    
$wpdb->query("UPDATE ".$table_prefix."democracyQ SET active='1' WHERE id = ".$wpdb->escape($_GET['poll_id']));
}

function 
jal_deactivate_poll () {
    global 
$wpdb$table_prefix$user_level$jal_dem_admin_level;
    
    
// Security
    
get_currentuserinfo();
    if (
$user_level <  $jal_dem_admin_level) { die('Nice try, you cheeky monkey!'); }

    
// Deactivate the old active poll
    
$wpdb->query("UPDATE ".$table_prefix."democracyQ SET active='0' WHERE active = '1'");
}

function 
jal_delete_poll () {
    global 
$wpdb$table_prefix$user_level$jal_dem_admin_level;
    
    
// Security
    
get_currentuserinfo();
    if (
$user_level <  $jal_dem_admin_level) { die('Nice try, you cheeky monkey!'); }
    
    
// Delete the poll question and its answers
    
$wpdb->query('DELETE FROM '.$table_prefix.'democracyQ WHERE id = '.$wpdb->escape($_GET['poll_id']));
    
$wpdb->query('DELETE FROM '.$table_prefix.'democracyA WHERE qid = '.$wpdb->escape($_GET['poll_id']));
    
}

function 
jal_add_question () {
    global 
$wpdb$table_prefix$user_level$jal_dem_admin_level;
        
    
// Security
    
get_currentuserinfo();
    if (
$user_level <  $jal_dem_admin_level) { die('Nice try, you cheeky monkey!'); }

    
// deactive old poll
    
$qry "UPDATE ".$table_prefix."democracyQ SET active='0' WHERE active='1'";
    
$wpdb->query($qry);
    
    
// Let users add their own answers?
    
$allow_users_to_add = (isset($_POST['allowNewAnswers'])) ? "1" "0";

    
// Add a new question and activate it
    
$qry "INSERT INTO ".$table_prefix."democracyQ (question, timestamp, allowusers, active) VALUES ('".$wpdb->escape($_POST['jal_dem_question'])."', '".time()."', '".$allow_users_to_add."', '1');";
    
    
$wpdb->query($qry);
    
    
// Get the id of that new question
    
$new_q $wpdb->get_var("SELECT id FROM ".$table_prefix."democracyQ WHERE active = '1'");
        
    
// Add the questions
    
for($i 1$i < ($_POST['qnum'] +1); $i++) {
        if (!empty(
$_POST['answer'.$i])) 
            
$sql[] = "INSERT INTO ".$table_prefix."democracyA (qid, answers, votes) VALUES (".$new_q.", '".$wpdb->escape($_POST['answer'.$i])."', 0);";
    }
    
    foreach(
$sql as $query) {
        
$wpdb->query($query);
    }
}

function 
jal_dem_admin_head() { 
if (
$_REQUEST['page'] == "democracy") {
?>
    <script type="text/javascript" src="<?php echo get_bloginfo('wpurl') . "/wp-content/plugins/democracy/admin.js"?>"></script>
<?php } }

function 
jal_dem_admin_page() {
global 
$wpdb$table_prefix;
 
?>

<?php if (isset($_GET['jal_dem_delete'])) { ?>
<div class="updated">
    <p>Poll #<?php echo $_GET['poll_id']; ?> was deleted successfully</p>
</div>
<?php ?>

<?php if (isset($_POST['jal_dem_edit'])) { ?>
<div class="updated">
    <p>Poll #<?php echo $_POST['poll_id']; ?> was edited successfully</p>
</div>
<?php ?>



<?php if (!empty($_GET['edit'])) { ?>

<div class="wrap">


    <h2>Edit Poll #<?php echo $_GET['poll_id']; ?></h2>

    <?php
    
    $latest 
$wpdb->get_var("SELECT id FROM ".$table_prefix."democracyQ ORDER BY id DESC LIMIT 1");
    
$question $wpdb->get_row("SELECT question, allowusers FROM ".$table_prefix."democracyQ WHERE id = ".$_GET['poll_id'], ARRAY_A);
    
$results $wpdb->get_results("SELECT * FROM ".$table_prefix."democracyA WHERE qid = ".$_GET['poll_id']." ORDER BY aid");
    
    
// convert into editable HTML
    
    
?>
    <p>Um eine Antwort zu loeschen, lass das Feld leer. <br />
    </p>
        <form action="edit.php?page=democracy" method="post" onsubmit="return jal_validate();">
    <strong>Frage: <input id="question" type="text" name="question" value="<?php echo $question['question']; ?>" /></strong>
    <ol id="choicelist">
    <?php 
    $count 
1;
    
$loop "";
    foreach (
$results as $r) {
    
        
// Add to the list of answers in the hidden input element
        
$loop $loop ." "$r->aid;
        
        
$r->answers jal_htmlentities_ap(stripslashes($r->answers));

     
?>
        <li id="answer<?php echo $count?>"><input type="text" id="choice<?php echo $count?>" value="<?php echo $r->answers?>" name="answer<?php echo $r->aid?>" /></li>
    <?php $end $count$count++; }    
    while (
$count 16) { ?>
        <li id="answer<?php echo $count?>" style="display: none"><input type="text" id="choice<?php echo $count?>" value="" name="new<?php echo $count?>" /></li>
    <?php $count++; } ?>
    
    </ol>
    <p>
        <label for="allowNewAnswers"><input type="checkbox" <?php if ($question['allowusers'] == 1) { echo 'checked="checked"'; } ?> value="true" name="allowNewAnswers" id="allowNewAnswers" /> Allow users to add answers</label><br /><br />
        <a href="javascript: addQuestion(<?php echo $end+1?>);" id="adder">Antwort hinzufuegen</a>&nbsp;&nbsp;
        <a href="javascript: eatQuestion(<?php echo $end?>);" id="subtractor">Antwort loeschen</a>&nbsp;

        <input type="hidden" id="qnum" name="qnum" value="<?php echo $count?>" />
        <input type="hidden" name="jal_dem_edit" value="true" />
        <input type="hidden" name="editable" value="<?php echo trim($loop); ?>" />
        <input type="hidden" name="poll_id" value="<?php echo $_GET['poll_id']; ?>" />
        <input type="submit" value="Edit" />
    </p>
    </form>
    



   <?php } else { ?>

    <?php 
    
// get the current poll
    
$current $wpdb->get_var("SELECT id FROM ".$table_prefix."democracyQ WHERE active = '1'");

    if (!
$current) { ?>
        <div class="updated">
            <p style="font-weight: bold">Es gibt keine aktiven Abstimmungen! Das Plugin zeigt nichts an, es sei denn, Sie aktivieren eine Abstimmung.</p>
        </div>
    <?php ?>

<div class="wrap">


    <h2>Umfrage managen</h2>
    
    <table width="100%" border="0" cellspacing="3" cellpadding="3">
        <tr>
            <th scope="col">ID</th>
            <th scope="col">Frage</th>
            <th scope="col">Total Votes</th>
            <th scope="col">Ergebniss</th>
            <th scope="col">Hinzugefuegt am</th>
            <th scope="col">Aktion</th>
        </tr>
<?php 


    $x 
$wpdb->get_results("SELECT * from ".$table_prefix."democracyQ ORDER BY id");
        
    
$alt true;
    if (
$x) {
    foreach (
$x as $r) {
        
$winner $wpdb->get_var("SELECT answers FROM ".$table_prefix."democracyA WHERE qid = ".$r->id." ORDER BY votes DESC LIMIT 1"); 

        
$total_votes $wpdb->get_var("SELECT SUM(votes) FROM ".$table_prefix."democracyA WHERE qid = ".$r->id);

        if (
$total_votes == 0$winner "No votes yet.";

        
$alt = ($alt == true) ? FALSE TRUE;
?>
        <tr<?php if ($current == $r->id) { echo ' class="active"'; } if ($alt == true && $current !== $r->id) { echo ' class="alternate"';  } ?>>
           <td style="text-align: center"><?php echo $r->id?></td>
           <td style="text-align: center"><?php echo jal_htmlentities_ap(stripslashes($r->question)); ?></td>
           <td style="text-align: center"><?php if ($current == $r->id) { echo "So far, "; } echo $total_votes?></td>
           <td style="text-align: center"><?php echo jal_htmlentities_ap(stripslashes($winner)); ?>
           <td style="text-align: center"><?php echo date(get_settings('date_format'), $r->timestamp); ?></td>
           <td style="text-align: center">
               <form action="" method="get">
                   <div>
                       <input type="hidden" name="page" value="democracy" />
                       <input type="hidden" name="poll_id" value="<?php echo $r->id?>" />
                       <?php if ($current !== $r->id) :  ?>
                           <input type="submit" value="Aktivieren" name="jal_dem_activate" />
                       <?php else : ?>
                           <input type="submit" value="Deaktivieren" name="jal_dem_deactivate" />
                       <?php endif; ?>
                       <input type="submit" value="Editieren" name="edit">
                       <input type="submit" value="Loeschen" onclick="return confirm('You are about to delete this poll.\n  \'Cancel\' to stop, \'OK\' to delete.');" name="jal_dem_delete" class="delete" />
                   </div>
               </form>
           </td>
        </tr>
    <?php } } else { echo "<br />You have no polls in the database. Add a new one!<br /><br />"; } ?>
        
    </table>
    <h2>Neue Umfrage hinzufuegen</h2>
    <form action="edit.php?page=democracy" method="post" onsubmit="return jal_validate();">
    <div id="form_questions">

    <label for="allowNewAnswers"><input type="checkbox" value="true" name="allowNewAnswers" id="allowNewAnswers" /> Alle duerfen Antworten hinzufuegen</label><br /><br />
    <a href="javascript: addQuestion(5);" id="adder">Antwort hinzufuegen</a><br />
    <a href="javascript: eatQuestion(4);" id="subtractor">Antwort loeschen</a><br />
    <br />
    <label for="question">
        <strong>Frage:</strong>
    </label>

        <input type="text" name="jal_dem_question" value="" id="question" />
    
    <?php for($i 1$i 16$i++) { ?>
    <div id="answer<?php echo $i?>"<?php if ($i 4) { echo ' style="display: none"'; } ?>>
        <br />
        Antwort <?php echo $i?>:

        <input type="text" value="" id="choice<?php echo $i?>" name="answer<?php echo $i?>" />
    </div>
    <?php ?>
    <br />
    <input type="hidden" id="qnum" value="5" name="qnum" />
    <input type="submit" value="Hinzufuegen" />
    </div>
    </form>
    <?php // end of Edit conditional ?>

    
</div>

<? }

// Adds the Democracy Poll Plugin tab to the admin navigation
function jal_add_page() {
    global 
$jal_dem_admin_level;
    
add_management_page('Democracy''Democracy'$jal_dem_admin_level'democracy''jal_dem_admin_page');
}

// Add the javascript to the head of the page
function jal_add_js () {
    global 
$jal_dem_version;

    echo 
'
    <!-- Added By Democracy Plugin. Version '
.$jal_dem_version.' -->
    <script type="text/javascript" src="'
.get_bloginfo('wpurl') . '/wp-content/plugins/democracy/js.php"></script>
    <link rel="stylesheet" href="'
.get_bloginfo('wpurl') . '/wp-content/plugins/democracy/democracy.css" type="text/css">
        '
;
}


// Run a check of visitors IP to make sure they haven't voted already.
// This process is usually silent, cookies take care of the design
function jal_checkIP ($poll_id 0) {
    global 
$wpdb$table_prefix;
    
    
$where = ($poll_id == 0) ? "active = '1'" "id = '".$poll_id."'";
    
    
$all_ips $wpdb->get_var("SELECT voters FROM ".$table_prefix."democracyQ WHERE ".$where);

    
$results unserialize($all_ips);
    
// make sure there have been votes
    
if ($results) {
        
//check the ip address, and quit if there's a match
        
if (in_array($_SERVER['REMOTE_ADDR'], $results)) {
            die(
"Schon gewählt!");
        }
    }
        
// add the new IP address to the array
        
$results[] = $_SERVER['REMOTE_ADDR'];
        
$final $wpdb->escape(serialize($results));
      
        
$wpdb->query("UPDATE ".$table_prefix."democracyQ SET voters = '".$final."' WHERE ".$where);
}

// Print the poll html
function jal_democracy($poll_id 0) {
 global 
$wpdb$table_prefix$jal_before_question$jal_after_question;
 
    
$where = ($poll_id == 0) ? "active = '1'" "id = '".$poll_id."'";
     
$poll_question $wpdb->get_row("SELECT id, question, voters, allowusers FROM ".$table_prefix."democracyQ WHERE ".$where);

// Check if they've voted
 
if ($_GET['jal_no_js'] || isset($_COOKIE['demVoted_'.$poll_question->id])) {
    
jal_SeeResults($poll_question->id);
    
 } else {
        
$wpdb->hide_errors();
        
$poll_answers $wpdb->get_results("SELECT aid, answers, added_by FROM ".$table_prefix."democracyA WHERE qid = ".$poll_question->id." ORDER BY aid");
        
$wpdb->show_errors();
        if (empty(
$poll_question) || empty($poll_answers)) { echo "<!-- There are no active polls in the database, or there was an error in finding one -->"; } else {
        
        
// Check if there are already arguments in the URL
        
$x = (strstr($_SERVER['REQUEST_URI'], '?')) ? "&amp;" "?";
 
         
$latestaid $wpdb->get_var("SELECT aid FROM ".$table_prefix."democracyA ORDER BY aid DESC LIMIT 1");
 
         
$total_votes $wpdb->get_var("SELECT SUM(votes) FROM ".$table_prefix."democracyA WHERE qid = ".$poll_question->id);
    
?>
     <form action="<?php echo get_bloginfo('wpurl') . '/wp-content/plugins/democracy/democracy.php?jal_nojs=true'?>" method="post" id="democracyForm" onsubmit="return ReadVote();">
        <div id="democracy">
        <?php echo $jal_before_question jal_htmlentities_ap(stripslashes($poll_question->question)) . $jal_after_question?>

        <ul>
          <?php foreach ( $poll_answers as $r) { ?>
            <li>
                <label for="choice_<?php echo $r->aid?>">
                    <input type="radio" id="choice_<?php echo $r->aid?>" value="<?php echo $r->aid?>" name="poll_aid" />
                    <?php echo jal_htmlentities_ap(stripslashes($r->answers)); ?><?php if ($r->added_by == "1") { echo '<sup title="Added by users">1</sup>'$user_added TRUE; }?>
                </label>
            </li>
          <?php }
          if ( 
$poll_question->allowusers == 1) {
           
?>
          
              
            <?php /* No-JS users */ if (isset($_GET['jal_add_user_answer'])) { ?>

            <li>
            <input type="radio" name="poll_aid" id="jalAddAnswerRadio" value="newAnswer" checked="checked" />
            <input type="text" size="15" id="jalAddAnswerInput" name="poll_vote" value="" />

            </li>

            <?php } else { ?>
            <li>
                <a href="<?php echo $_SERVER['REQUEST_URI'].$x?>jal_add_user_answer=true" id="jalAddAnswer">Antwort hinzufuegen</a>
                <input type="radio" name="poll_aid" id="jalAddAnswerRadio" value="<?php echo $latestaid 1?>" style="display: none" /> <input type="text" size="15" style="display: none" id="jalAddAnswerInput" />
            </li>
            
            <?php } } ?>
        </ul>
        <p><input class="centered" type="hidden" id="poll_id" name="poll_id" value="<?php echo $poll_question->id?>" /><input type="submit" name="vote" value="Abstimmen" /></p>
        <p><?php if ($total_votes 0) { 
            
// For non-js users...JS users get this link changed onload
        
?>
            <a class="centered" id="view-results" href="<?php echo $_SERVER['REQUEST_URI'].$x?>jal_no_js=true&amp;poll_id=<?php echo $poll_question->id?>">Ergebnisse ansehen</a>
            <?php if ($user_added) echo "<br /><small><sup>1</sup> = Duch einen Gast hinzugefuegt</small>"?>
        <?php } else { echo "Noch kein Voting"; } ?></p>
       </div>
    </form>

<?php } } 
}

// Installs the tables needed for polls
// Check the codex article for more info
// http://codex.wordpress.org/creating_tables_with_plugins
function jal_dem_install () {
   global 
$table_prefix$wpdb$user_level,  $jal_dem_admin_level;

   
$table_name $table_prefix "democracyQ";
  
//  $wpdb->query('DROP TABLE '.$table_prefix."democracyQ");
//    $wpdb->query('DROP TABLE '.$table_prefix."democracyA");

   
get_currentuserinfo();
   if (
$user_level <  $jal_dem_admin_level) { return; }

   
$result mysql_list_tables(DB_NAME);
   
$tables = array();

   while (
$row mysql_fetch_row($result)) { $tables[] = $row[0]; }
  
   
$first_install false;
  
   if (!
in_array($table_name$tables)) {
      
$first_install true;
   }


   
// PRIMARY KEY has 2 spaces on purpose ... some weird dbDelta thing...

   
$qry "CREATE TABLE ".$table_prefix."democracyA (
            aid int(10) unsigned NOT NULL auto_increment,
            qid int(10) NOT NULL default '0',
            answers varchar(200) NOT NULL default '',
            votes int(10) NOT NULL default '0',
            added_by enum('1','0') NOT NULL default '0',
            PRIMARY KEY  (aid)
           );
 
           CREATE TABLE "
.$table_prefix."democracyQ (
            id int(10) unsigned NOT NULL auto_increment,
            question varchar(200) NOT NULL default '',
            timestamp int(10) NOT NULL default '',
            voters text NULL default '',
            allowusers enum('0','1') NOT NULL default '0',
            active enum('0','1') NOT NULL default '0',
            PRIMARY KEY  (id)
           ); "
;

    require_once(
ABSPATH 'wp-admin/upgrade-functions.php');
    
dbDelta($qry);
   
        
    if (
$first_install == true) {
        
        
// Add In Poll Question/Answers
        
$sql[] = "INSERT INTO ".$table_prefix."democracyQ VALUES (1, 'Rate my site', '".time()."', '', '0', '0');";
        
$sql[] = "INSERT INTO ".$table_prefix."democracyA VALUES (1, 1, 'Best. Blog. Ever.', 0, 0);";
        
$sql[] = "INSERT INTO ".$table_prefix."democracyA VALUES (2, 1, 'Could be better...', 0, 0);";
        
$sql[] = "INSERT INTO ".$table_prefix."democracyA VALUES (3, 1, 'My grandma could make a better website!', 0, 0);";
        
$sql[] = "INSERT INTO ".$table_prefix."democracyA VALUES (4, 1, 'Ooo look, a butterfly!', 0, 0);";
        
$sql[] = "INSERT INTO ".$table_prefix."democracyA VALUES (5, 1, 'No Comment', 0, 0);";

        foreach(
$sql as $query) {
            
$wpdb->query($query);
        }

    }
}

// Prints the standings of a poll
function jal_SeeResults($poll_id 0$javascript FALSE) {
    global 
$wpdb$table_prefix$jal_order_answers$jal_before_question$jal_after_question$jal_graph_from_total;
    
    
$order_by = ($jal_order_answers) ? " ORDER BY votes DESC" " ORDER by aid ASC";
    
    
// What to say for total votes text
    
$total_votes_text "Total Votes";
    
    
$where = ($poll_id == 0) ? "active = '1'" "id = '".$poll_id."'";
    
$poll_question $wpdb->get_row("SELECT id, question, voters FROM ".$table_prefix."democracyQ WHERE ".$where);
    
$total_votes $wpdb->get_var("SELECT SUM(votes) FROM ".$table_prefix."democracyA WHERE qid = ".$poll_question->id);
    
$poll_answers $wpdb->get_results("SELECT aid, answers, votes, added_by FROM ".$table_prefix."democracyA WHERE qid = ".$poll_question->id $order_by);
?>
    
                <?php if (!$javascript) { echo '<div id="democracy">'; } ?>
    
    
                    <?php echo $jal_before_question jal_htmlentities_ap(stripslashes($poll_question->question)) . $jal_after_question?>
    
                     <ul>
    <?php 
        
    $output 
"";
    
$cookie $_COOKIE['demVoted_'.$poll_question->id];
    
$values = array();
    
    
// Search for the winner of the poll
    
foreach ($poll_answers as $row) {
        
$values[] = $row->votes;
    }
    
    
// Winner is the one with the max votes
    
$winner max($values);
    
    
// Loop for the number of answers
    
foreach ($poll_answers as $r) {
    
        
// Percent of total votes
        
$percent round($r->votes / ($total_votes 0.0001) * 100);
        
        
// Percent to display in the graph, as set at the top of the file
        
$graph_percent = ($jal_graph_from_total) ? $percent round($r->votes / ($winner 0.0001) * 100);
        
        
// See which choice they voted for
        
$voted_for_this = ($cookie == $r->aid) ? TRUE FALSE;
        
$user_added = ($r->added_by == "1") ? '<sup title="Added by users">1</sup>' '';
        if (
$r->added_by == "1") {
            
$user_added '<sup title="Added by a guest">1</sup>';
            
$add_sup    TRUE;
        } else 
$user_added "";
            
        
        
// In the graphs, define which class/id to use.
        
$graph_hooks = ($voted_for_this) ? 'id="voted-for-this" class="dem-choice-border"' 'class="dem-choice-border"';

        
$output .="\n\t\t\t\t\t";

        
$output .= "<li>";
        
        
$output .= jal_htmlentities_ap(stripslashes($r->answers)) . $user_added ": ";
        
$output .= "<strong>".$percent."%</strong>";
        
$output .= " (".$r->votes.")";
        
        
// Graph it
        
$output .= '<span '.$graph_hooks.'><span class="democracy-choice" style="width: '.$graph_percent.'px"></span></span>';
                
        
$output .= "</li>";

        echo 
$output;
        
        
// reset $output for the next loop
        
$output "";
        
    } 
?>


                 </ul>
                 <p>
                     <em id="dem-total-votes"><?php echo $total_votes_text?> : <?php echo $total_votes?></em>
     <?php /* if they are just looking at the results and haven't voted */
      
if (!$_COOKIE['demVoted_'.$poll_question->id]) { ?>
                       <br />
                       <a href="<?php echo $_SERVER['HTTP_REFERER']; ?>">Vote</a>
     <?php ?>
     <?php if ($add_sup) echo "<br /><small><sup>1</sup> = Added by a guest</small>"?>

                 </p>
         
             <?php if (!$javascript) echo "</div>\n\n";
 }


/*
===========================
Now, the functions are done
Let's run them....
===========================
*/


// for users with js turned off
if (isset($_GET['jal_nojs'])) {
    include (
"../../../wp-config.php");
    
    
// Set the cookies, it doesn't matter that they might already have voted.
    
if($_POST['poll_aid'] == "newAnswer") {
       
$aid $wpdb->get_var("SELECT aid FROM ".$table_prefix."democracyA ORDER BY aid DESC LIMIT 1");
       
// Give the user a cookie
       
setcookie("demVoted_".$_POST['poll_id'],$aid 1,time()+$jal_cookietime,'/');
    } else {
        
setcookie("demVoted_".$_POST['poll_id'],$_POST['poll_aid'],time()+$jal_cookietime,'/');
    }
    
    
// Check their IP against past votes
    
jal_checkIP($wpdb->escape($_POST['poll_id']));
    
    
// Add a new answer to the choice list
    
if ($_POST['poll_aid'] == "newAnswer") {
        if (
$wpdb->get_var("SELECT allowusers FROM ".$table_prefix."democracyQ WHERE id = '".$_POST['poll_id']."'") == 1) {
            
// Add the new choice
            
$wpdb->query("INSERT INTO ".$table_prefix."democracyA (qid, answers, votes, added_by) VALUES (".$wpdb->escape($_POST['poll_id']).", '".$wpdb->escape($_POST['poll_vote'])."', 1, 1)");
        }
    } else {
        
// or just add the new vote
        
$wpdb->query("UPDATE ".$table_prefix."democracyA SET votes = (votes+1) WHERE qid = ".$wpdb->escape($_POST['poll_id'])." AND aid = ".$wpdb->escape($_POST['poll_aid']));
    }
    
    
$x = (strstr($_SERVER['HTTP_REFERER'], '?')) ? "&" "?";
    
    
header("location: ".$_SERVER['HTTP_REFERER'].$x."jal_no_js=true");
}

// When the poll sends the vote
if (isset($_GET['demSend'])) {
    include (
"../../../wp-config.php");    
    
jal_checkIP($wpdb->escape($_POST['poll_id']));
    
    if (isset(
$_POST['new_vote'])) {
        
// Make sure users are allowed to add comments
        
if ($wpdb->get_var("SELECT allowusers FROM ".$table_prefix."democracyQ WHERE id = '".$_POST['poll_id']."'") == 1) {
            
// Add the new question and give it one vote
            
$wpdb->query("INSERT INTO ".$table_prefix."democracyA (qid, answers, votes, added_by) VALUES (".$wpdb->escape($_POST['poll_id']).", '".$wpdb->escape($_POST['vote'])."', 1, 1)");
            
// Get the new id of the new answer
        
}
    } else {
        
$wpdb->query("UPDATE ".$table_prefix."democracyA SET votes = (votes+1) WHERE qid = ".$wpdb->escape($_POST['poll_id'])." AND aid = ".$wpdb->escape($_POST['vote']));
    }
}

// When the poll wants results
if (isset($_GET['demGet'])) {
    include (
"../../../wp-config.php");
    
jal_SeeResults($_GET['poll_id'], TRUE);
}

// Make sure WP is running
if (function_exists('add_action')) {

    
// javascript for main blog
    
add_action('wp_head''jal_add_js');
    
// add the management page to the admin nav bar
    
add_action('admin_menu''jal_add_page');
    
// add javascript to admin area
    
add_action('admin_head''jal_dem_admin_head');

/* These actions are run through 'init' for security */
    
    // Run the install script if a plugin is activated
    
if (isset($_GET['activate']) && $_GET['activate'] == 'true') {
       
add_action('init''jal_dem_install');
    }
    
    
// Add a new question and its answers via admin panel
    
if (isset($_POST['jal_dem_question'])) {
        
add_action('init''jal_add_question');
    }
    
    
// When user deletes a poll
    
if (isset($_GET['jal_dem_delete'])) {
        
add_action('init''jal_delete_poll');
    }
    
    
// When user activates a poll
    
if (isset($_GET['jal_dem_activate'])) {
        
add_action('init''jal_activate_poll');
    }

    
// When user deactivates a poll
    
if (isset($_GET['jal_dem_deactivate'])) {
        
add_action('init''jal_deactivate_poll');
    }
    
    
// When a user edits a poll
    
if (isset($_POST['jal_dem_edit'])) {
        
add_action('init''jal_edit_poll');
    }
    
}
?>