We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 10666
    • 68 Posts
    This is a modified version of Garry Nutting’s original poll snippets. ( http://modxcms.com/Polls-Module-526.html )
    In this version, the module part stays the same,only the snippet parts being updated.
    Features as opposed to the ’old’ one tongue .

    • The same snippet can be used for voting AND displaying results.(using &viewOnly parameter)
    • If a user votes , it is by default redirected to the current page,and showed the results in place of the poll.
    • Users that should not vote (restricted by &onevote and &useip) will not be showed the poll form. They will see the poll’s results instead.(this makes &ovmessage obsolete).
    • The options in the list are ’clickable’ . When clicking on the text next to a radio button,it will select that choice in the poll.
    Some core logic is modified here and there, but mainly the code was cut and pasted from one place to another,so there shouldn’t be any regressions. (I hope).
    This snippet also works well with SEO Strict URLs . (I had some issues with the old version because of the way $cur_url variable was generated.The $url aproach in the snippet seems to work better.)

    Also ,last,but not least, I would like to thank Garry for making this wonderful module/snippet.

    Feel free to test it and report anything you don’t like about it.
    (Also,Garry, if you don’t want this snippet to be named as your original one , I will change it immediately ).

    [Solved]*NOTE*:Some help needed. How could I add the .css file to a page only when this snippet is used(dynamically)? I’ve seen that done with Jot and CSSStarRating , but have no idea how to do it. Any help is appreciated.


    I would like to thank Mitch and Apoxx for helping me with the dynamic CSS insertion.

    EDIT:Uploaded new version 3.1.1. The snippet now assumes that you have the css file at the following location:
    assets/snippets/pollsmodule/poll.css . However, you can call the script with a different location for the css file,with the help of the &cssFile parameter.

    EDIT:Uploaded new version 3.1.2.
    Changelog: Fixed an issue with generating wrong URLs for redirecting when using SEO Strict URLs plugin.

    EDIT:Uploaded new version 3.1.3.
    Changelog:

    • now the choices in the poll are labels,so that when you click on them it selects the choice they represent.
    • a few optimizations in the code
    • a tiny bit of logic rewrites

    EDIT:Uploaded new version 3.1.5.
    Changelog:
    • You can now pass 0 , false , or ’ ’ to the &cssFile paramater ,so that the snippet does not introduce any CSS file.
    • Small changes in userIP() function.

    //<?php
    // +----------------------------------------------------------------------+
    // | Polls Vote Snippet                                                   |
    // +----------------------------------------------------------------------+
    // | Created: February 2006 Version: 3                                    |
    // | Modified:March    2007 Version: 3.1.5                                |
    // +----------------------------------------------------------------------+
    // | Author: Garry Nutting               Edited by:George Arion           |
    // +----------------------------------------------------------------------+
    //
    // &pollid	- Poll ID to be used
    // &redirect	- Document ID to redirect to after voting/pressing 'Results' button.Defaults to current page.If custom,make sure that the page exists and IS published,or else the page will NOT load!
    // &onevote	- Boolean value, if true, uses a cookie to allow only one vote per visitor.Defaults to false.
    // &viewOnly	- Boolean value, if true, the snippet will only show the poll's results.Defaults to false.
    // &useip	- Boolean value, if true, logs IP addresses and a user can only have a single vote.Defaults to false.
    // &ovtime	- Time limit to set the cookie time to.Defaults to a week.
    // &ovmessage	- Message to display if a user tries to vote more than once if $onevote/$useip is enabled
    // &ovmessage	- NOW Obsolete.If a user should not vote,it will be shown the results instead of the poll form.
    // &resultsbutton-Boolean value, if true, show a 'Results' button - Results button goes to the page id defined by &redirect.
    // &decimal	- Display decimal places(number is how many decimal points to display).Defaults to 1.
    // &cssFile	- Where to look for the .css file to style the snippet's output.Takes the css file's path as a  value.Defaults to assets/snippets/pollsmodule/poll.css .Set the paramater to 0 , false or '' if you don't want the snippet to automatically introduce a css file.
    //
    // +----------------------------------------------------------------------+
    
    //-- Try to get poll id, if no poll id then no point carrying on
    if (!isset ($pollid))
    	return false;
    
    //-- setup initial variables
    $output = '';
    $pollid = intval($pollid);
    $redirect = (isset ($redirect)) ? intval($redirect) : $modx->documentIdentifier;
    $onevote = (isset ($onevote)) ? (bool) $onevote : false;
    $viewOnly = (isset ($viewOnly)) ? (bool) $viewOnly : false;
    $ovtime = (isset ($ovtime)) ? $ovtime : 608400; // default: expires in one week
    $useip = (isset ($useip)) ? (bool) $useip : false;
    $ovmessage = (isset ($ovmessage)) ? $ovmessage : 'You are only allowed to vote once';
    $resultsbutton = (isset ($resultsbutton)) ? (bool) $resultsbutton : false;
    $decimal = (isset ($decimal)) ? intval($decimal) : 1;
    $cssFile = (isset ($cssFile) ) ? $cssFile : "assets/snippets/pollsmodule/poll.css";
    
    $fields = array ();
    
    //-- load CSS:
    if ( $cssFile ) {
    	$modx->regClientCSS($cssFile);
    }
    
    //-- make url for redirect if required
    $doc = $modx->getDocument($redirect);
    $r_id = $doc['id'];
    $r_alias = $doc['alias'];
    $url = $modx->makeURL($r_id);
    
    //-- set form action to redirect $url
    $modx->setPlaceholder('formaction', $url);
    
    //-- setup DB table names
    $polltable = $modx->getFullTableName("polls");
    $choicetable = $modx->getFullTableName("poll_choices");
    $iptable = $modx->getFullTableName("pollip");
    
    //-- if 'Results' button has been selected OR viewOnly is set to true , show the results page.
    if ( (isset ($_POST['results'])) || ($viewOnly == true)  ) {
    	return showResults($pollid,$decimal,$polltable,$choicetable);
    }
    
    //-- if already voted and repeated voting is disabled:
    
    	//-- cookie check - if $onevote, check if visitor is allowed to vote;if not allowed,show him the results.
    	if ($onevote == true) {
    		if (isset ($_COOKIE['poll' . $pollid])) {
    			return showResults($pollid,$decimal,$polltable,$choicetable);
    		}
    	}
    
    	//-- ip check, if $useip, check if visitor is allowed to vote;if not allowed,show him the results.
    	if ($useip == true) {
    		$useraddy = userIP();
    		$results = $modx->db->select('*', $iptable, 'ipaddress=\'' . $useraddy . '\' AND pollid=' . $_POST['poll_pollid'], '');
    		if ($modx->db->getRecordCount($results) > 0) {
    			return showResults($pollid,$decimal,$polltable,$choicetable);
    		}
    	}
    
    //-- if vote was submitted increment polls and poll_choices vote counts
    
    if (isset ($_POST['vote']) && isset ($_POST['poll_choice_id'])) {
    
    	//-- cookie check - if $onevote, check if visitor is allowed to vote
    	if ($onevote == true) {
    			//-- set cookie
    			setcookie('poll' . $_POST['poll_pollid'], 'novote', time() + $ovtime);
    	}
    
    	//-- log ip address into database if required
    	if ($useip == true ) {
    		$ipsql = 'INSERT INTO ' . $iptable . ' (pollid,ipaddress) VALUES (' . $pollid . ',\'' . $useraddy .'\')';
    		$modx->db->query($ipsql);
    	}
    
    	//-- insert voting data into database:
    	$sql = "UPDATE " . $polltable . " SET votes=votes+1 WHERE id=" . $_POST['poll_pollid'] . ";";
    	$modx->db->query($sql);
    
    	$sql = "UPDATE " . $choicetable . " SET votes=votes+1 WHERE id=" . $_POST['poll_choice_id'] . ";";
    	$modx->db->query($sql);
    
    	//-- send redirect
    	$modx->sendRedirect($url);
    }
    
    return showPoll($pollid,$polltable,$choicetable,$resultsbutton,$redirect,$novote);
    
    //-- gets the visitors ip address
    function userIP() {
    	// This returns the True IP of the client calling the requested page
    	// Checks to see if HTTP_X_FORWARDED_FOR 
    	// has a value then the client is operating via a proxy
    	// return the IP we'll figured out:
    	if ($_SERVER['HTTP_CLIENT_IP'] <> '') {
    		return $_SERVER['HTTP_CLIENT_IP'];
    	}
    	elseif ($_SERVER['HTTP_X_FORWARDED_FOR'] <> '') {
    		return $_SERVER['HTTP_X_FORWARDED_FOR'];
    	}
    	elseif ($_SERVER['HTTP_X_FORWARDED'] <> '') {
    		return $_SERVER['HTTP_X_FORWARDED'];
    	}
    	elseif ($_SERVER['HTTP_FORWARDED_FOR'] <> '') {
    		return $_SERVER['HTTP_FORWARDED_FOR'];
    	}
    	elseif ($_SERVER['HTTP_FORWARDED_FOR'] <> '') {
    		return $_SERVER['HTTP_FORWARDED_FOR'];
    	} 
    	else {
    		return $_SERVER['REMOTE_ADDR'];
    	}
    }
    function showPoll($pollid,$polltable,$choicetable,$resultsbutton,$redirect,$novote) {
    
    //-- to use $modx:
    global $modx;
    
    //-- query for the poll to be displayed and assign local variables
    $where = "id=" . $pollid;
    $rs = $modx->db->select("*", $polltable, $where, "id ASC", "");
    $limit = $modx->db->getRecordCount($rs);
    if ($limit > 0) {
    	$poll = $modx->db->getRow($rs);
    }
    
    //-- query for poll choice results
    $where = "pollid=" . $pollid;
    $choices_rs = $modx->db->select("*", $choicetable, $where, "id ASC", "");
    $limit2 = $modx->db->getRecordCount($choices_rs);
    
    if ($limit > 0) {
    
    	//-- start the CSS poll voting display
    	$output .= '
    				      <form name="pollvote" method="post" action="[+formaction+]">
    				        <input type="hidden" name="poll_pollid" value="' . $poll['id'] . '" />
    				        <div class="poll">
    				          <div class="poll_container">
    				            <div class="poll_row_container poll_question">' . stripslashes($poll['question']) 
    
    . '</div>
    				            <div><hr /></div>
    				
    				    ';
    
    	//-- loop through choice results
    	for ($i = 0; $i < $limit2; $i++) {
    		$row = $modx->db->getRow($choices_rs);
    
    		//-- display each poll choice
    		$output .= '
    								            <div class="poll_row_container">
    								              <div class="float_left_text_right"><label for="vote' . $pollid . '.' . $row['id'] . '">' .stripslashes($row['choice']) . ':</label></div>
    								              <div class="float_right_text_left">
    								                <input type="radio" class="radio"  name="poll_choice_id" id="vote' . $pollid . '.' . $row['id'] . '" value="' . $row['id'] . '" />
    								              </div>
    								            </div>
    								            <div style="clear:both;"></div>
    								        ';
    
    	}
    
    	//-- display buttons
    	$output .= '
    				            <div><hr /></div>
    				            <div class="poll_row_container poll_question">
    				              <input type="submit" name="vote" value="Vote" class="vote" />';
    	if ($resultsbutton == true && $redirect <> '') {
    		$output .= '<input type="submit" name="results" value="Results" class="vote" />';
    	}
    	if (isset ($novote)) {
    		$output .= '<div class="poll_reject">' . $ovmessage . '</div>';
    	}
    
    	$output .= '
    				            </div>
    				          </div>
    				        </div>
    				      </form>
    				    ';
    }
    return $output;
    }
    
    //Shows poll results:
    function showResults($pollid,$decimal,$polltable,$choicetable)
    {
    // +----------------------------------------------------------------------+
    // | Polls Results Snippet                                                |
    // +----------------------------------------------------------------------+
    // | Created: January 2006 Version: 1                                     |
    // +----------------------------------------------------------------------+
    global $modx;
    $output = '';
    //-- Query for the poll to be displayed and assign local variables
    $where = "id=" . $pollid;
    $rs = $modx->db->select("*", $polltable, $where, "id ASC", "");
    $limit = $modx->db->getRecordCount($rs);
    if ($limit > 0) {
    	$poll = $modx->db->getRow($rs);
    	$name = $poll['name'];
    	$question = $poll['question'];
    	$totalvotes = $poll['votes'];
    }
    
    //-- Query for poll choice results
    $where = "pollid=" . $pollid;
    $choices_rs = $modx->db->select("*", $choicetable, $where, "id ASC", "");
    $climit = $modx->db->getRecordCount($choices_rs);
    
    if ($limit > 0) {
    
    	//-- Start the CSS poll results display
    	$output .= '
    	  <div class="poll">
    	    <div class="poll_container">
    	      <div class="poll_row_container poll_question">' . stripslashes($question) . '</div>
    	      <hr />
    	';
    
    	//-- Loop through choice results
    	for ($i = 0; $i < $climit; $i++) {
    		$row = $modx->db->getRow($choices_rs);
    		$choice = $row['choice'];
    		$votes = $row['votes'];
    
    		if (($votes < 1) || ($totalvotes < 1)) {
    			$percent = 0;
    		} else {
    			$percent = ($votes / $totalvotes) * 100;
    		}
    
    		//-- Display the details of each poll choice
    		$output .= '
    		      <div class="poll_row_container">
    		        <div class="poll_choice">' . stripslashes($choice) . ':</div>
    		        <div class="poll_votes">[ ' . $votes . ' ]</div>
    		        <div class="poll_bar_container">
    		';
    
    		if ($percent > 0) {
    			$output .= '
    			          <div class="poll_bar" style="width:' . number_format($percent, $decimal, '.', '') . '%"> </div>
    			';
    		} else {
    			$output .= '<div class="poll_bar"></div>';
    		}
    
    		$output .= '
    		        </div>
    		        <div class="poll_percent">
    		          ' . number_format($percent, $decimal, '.', '') . '%
    		        </div>
    		        <div class="space-line"></div>
    		      </div>
    		';
    
    	}
    
    	//-- Display total votes for the poll so far and close the table
    	$output .= '
    	        <hr />
    	        <div class="space-line"></div>
    	      <div class="poll_row_container">
    	        <div class="poll_choice">Total Votes:</div>
    	        <div class="poll_votes"> [ ' . $totalvotes . ' ]</div>
    	        <div class="poll_percent"> </div>
    	        <div class="space-line"></div>
    	      </div>
    	    </div>
    	  </div>
    	';
    }
    return $output;
    }
    //?>


      • 19726
      • 239 Posts
      Those changes are exactly what I needed. I will try to see if I can use it somewhere this weekend.

      Checkout this function for adding CSS to a page from a snippet http://modxcms.com/regclientcss.html
        • 16886
        • 40 Posts
        Quote from: Mitch at Mar 23, 2007, 08:23 PM

        Checkout this function for adding CSS to a page from a snippet http://modxcms.com/regclientcss.html

        Yes, but you always can do something like this:

        Create a Chunk
        {{MyCSSDefinition}}

        and in this chunk {{MyCSSDefinition}} place two or more chunk-parts that contain your partial CSS
        <style type="text/css">
        for example:
        {{MyCSSFonts}}
        and
        {{MyCSSColors}}
        or/and
        {{MyDIVS}}
        ...
        </style>
        than you easily can change only the css-parts that you need
        only an idea...

        Greetings
        LeftHanded
          I love ModX!
          • 10666
          • 68 Posts
          That is a an idea, but I needed to have the snippet to automatically add the CSS file ( to "Just Work") only to the pages that needed that piece of CSS. (less wasted bandwidth).

          If you want to use the css like you showed us,I guess I could even use a &disableCss parameter (or to check if the &cssFile is not false or 0 or ’’ )in the snippet so you can manage the css as you wish.

          I’ll probably be looking to making some changes soon so that cssFile == ’’ or == 0 would not insert anything.
          Expect 3.1.4 grin
          • @Geo88: Nice work on the mods, keep it up smiley I’ll check out the updates a bit more in depth when I get a chance (read: time off from work) - let me know when you have the next update ready and I’ll most likely update the main repository version with it.

            Oh, fancy looking at making building in an Ajax voting option? tongue

            Thanks again,
            Garry
              Garry Nutting
              Senior Developer
              MODX, LLC

              Email: [email protected]
              Twitter: @garryn
              Web: modx.com
              • 10666
              • 68 Posts
              Updated snippet.Current version is now 3.1.5

              I’d build it so that it uses AJAX , but the thing is I really don’t know AJAX (and of course , I don’t really now js and xml sad ).

              If anyone is willing to change this to use AJAX ,please step up ! tongue
                • 40024
                • 72 Posts
                Hello, the line:
                $results = $modx->db->select('*', $iptable, 'ipaddress=\'' . $useraddy . '\' AND pollid=' . $_POST['poll_pollid'], '');
                needs to be changed to:
                $results = $modx->db->select('*', $iptable, 'ipaddress=\'' . $useraddy . '\' AND pollid=' . $pollid . '');