Advertisement
Guest User

ngg-voting.pgp (by Wookiee)

a guest
Jun 13th, 2012
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 72.62 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: NextGEN Gallery Voting
  4. Plugin URI: http://shauno.co.za/wordpress-nextgen-gallery-voting/
  5. Description: This plugin allows users to add user voting to NextGEN Gallery Images
  6. Version: 1.10.1
  7. Author: Shaun Alberts
  8. Author URI: http://shauno.co.za
  9. */
  10. /*
  11. Copyright 2012  Shaun Alberts  (email : shaunalberts@gmail.com)
  12.  
  13. This program is free software; you can redistribute it and/or modify
  14. it under the terms of the GNU General Public License as published by
  15. the Free Software Foundation; either version 2 of the License, or
  16. (at your option) any later version.
  17.  
  18. This program is distributed in the hope that it will be useful,
  19. but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  21. GNU General Public License for more details.
  22.  
  23. You should have received a copy of the GNU General Public License
  24. along with this program; if not, write to the Free Software
  25. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  26. */
  27.  
  28. // stop direct call
  29. if(preg_match("#".basename(__FILE__)."#", $_SERVER["PHP_SELF"])) {die("You are not allowed to call this page directly.");}
  30.  
  31. //{
  32.     // api funcs {
  33.         /**
  34.          * Gets the voting options for a specific gallery
  35.          * @param int $gid The NextGEN Gallery ID
  36.          * @author Shaun <shaunalberts@gmail.com>
  37.          * @return object of options on success, empty array on failure
  38.          */
  39.         function nggv_getVotingOptions($gid) {
  40.             global $wpdb;
  41.             $opts = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."nggv_settings WHERE gid = '".$wpdb->escape($gid)."'");
  42.             return $opts ? $opts : array();
  43.         }
  44.  
  45.         /**
  46.          * Gets the voting options for a specific image
  47.          * @param int $pid The image ID
  48.          * @author Shaun <shaunalberts@gmail.com>
  49.          * @return object of options on success, empty array on failure
  50.          */    
  51.         function nggv_getImageVotingOptions($pid) {
  52.             global $wpdb;
  53.             $opts = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."nggv_settings WHERE pid = '".$wpdb->escape($pid)."'");
  54.             return is_numeric($pid) && $opts->pid == $pid ? $opts : array();           
  55.         }
  56.        
  57.         /**
  58.          Checks if the current user can vote on a gallery
  59.          * @param int $gid The NextGEN Gallery ID
  60.          * @author Shaun <shaunalberts@gmail.com>
  61.          * @return true if the user can vote, string of reason if the user can not vote
  62.          */
  63.         function nggv_canVote($gid) {
  64.             $options = nggv_getVotingOptions($gid);
  65.            
  66.             if(!$options) {
  67.                 return false;
  68.             }
  69.            
  70.             if(!$options->enable) {
  71.                 return "VOTING NOT ENABLED";
  72.             }
  73.            
  74.             if($options->force_login) {
  75.                 global $current_user;
  76.                 get_currentuserinfo();
  77.  
  78.                 if(!$current_user->ID) {
  79.                     return "NOT LOGGED IN";
  80.                 }
  81.             }
  82.            
  83.             if($options->force_once) {
  84.                 if($options->force_login) { //force login, so check userid has voted already
  85.                     if(nggv_userHasVoted($gid, $current_user->ID)) {
  86.                         return "USER HAS VOTED";
  87.                     }
  88.                 }else{ //no forced login, so just check the IP for a vote
  89.                     if(nggv_ipHasVoted($gid)) {
  90.                         return "IP HAS VOTED";
  91.                     }
  92.                 }
  93.             }
  94.            
  95.             return true;
  96.         }
  97.  
  98.         /**
  99.          Checks if the current user can vote on an image (current almost identical to nggv_canVote(), but is seperate function for scalability)
  100.          * @param int $pid The image ID
  101.          * @author Shaun <shaunalberts@gmail.com>
  102.          * @return true if the user can vote, string of reason if the user can not vote
  103.          */
  104.         function nggv_canVoteImage($pid) {
  105.             $options = nggv_getImageVotingOptions($pid);
  106.            
  107.             if(!$options) {
  108.                 return false;
  109.             }
  110.            
  111.             if(!$options->enable) {
  112.                 return "VOTING NOT ENABLED";
  113.             }
  114.            
  115.             if($options->force_login) {
  116.                 global $current_user;
  117.                 get_currentuserinfo();
  118.  
  119.                 if(!$current_user->ID) {
  120.                     return "NOT LOGGED IN";
  121.                 }
  122.             }
  123.            
  124.             if($options->force_once == 1) {
  125.                 if($options->force_login) { //force login, so check userid has voted already
  126.                     if(nggv_userHasVotedImage($pid, $current_user->ID)) {
  127.                         return "USER HAS VOTED";
  128.                     }
  129.                 }else{ //no forced login, so just check the IP for a vote
  130.                     if(nggv_ipHasVotedImage($pid)) {
  131.                         return "IP HAS VOTED";
  132.                     }
  133.                 }
  134.             }else if($options->force_once == 2) {
  135.                 if($options->force_login) { //force login, so check userid has voted already
  136.                     if(nggv_userHasVotedOnGalleryImage($pid, $current_user->ID)) {
  137.                         return "USER HAS VOTED";
  138.                     }
  139.                 }else{ //no forced login, so just check the IP for a vote
  140.                     if(nggv_ipHasVotedOnGalleryImage($pid)) {
  141.                         return "IP HAS VOTED";
  142.                     }
  143.                 }
  144.             }
  145.            
  146.             return true;
  147.         }
  148.        
  149.         /**
  150.          * Save the vote.  Checks nggv_canVote() to be sure you aren't being sneaky
  151.          * @param array $config The array that makes up a valid vote
  152.          *  int config[gid] : The NextGEN Gallery ID
  153.          *  int config[vote] : The cast vote, must be between 0 and 100 (inclusive)
  154.          * @author Shaun <shaunalberts@gmail.com>
  155.          * @return true on success, false on DB failure, string on nggv_canVote() not returning true
  156.          */
  157.         function nggv_saveVote($config) {
  158.             if(is_numeric($config["gid"]) && $config["vote"] >= 0 && $config["vote"] <= 100) {
  159.                 if(($msg = nggv_canVote($config["gid"])) === true) {
  160.                     global $wpdb, $current_user;
  161.                     get_currentuserinfo();
  162.                     $ip = getUserIp();
  163.                     if($wpdb->query("INSERT INTO ".$wpdb->prefix."nggv_votes (id, pid, gid, vote, user_id, ip, proxy, dateadded) VALUES (null, 0, '".$wpdb->escape($config["gid"])."', '".$wpdb->escape($config["vote"])."', '".$current_user->ID."', '".$ip["ip"]."', '".$ip["proxy"]."', '".date("Y-m-d H:i:s", time())."')")) {
  164.                         return true;
  165.                     }else{
  166.                         return false;
  167.                     }
  168.                 }else{
  169.                     return $msg;
  170.                 }
  171.             }
  172.         }
  173.        
  174.         /**
  175.             * Save the vote.  Checks nggv_canVoteImage() to be sure you aren't being sneaky
  176.             * @param array $config The array that makes up a valid vote
  177.             *  int config[pid] : The image id
  178.             *  int config[vote] : The cast vote, must be between 0 and 100 (inclusive)
  179.             * @author Shaun <shaunalberts@gmail.com>
  180.             * @return true on success, false on DB failure, string on nggv_canVoteImage() not returning true
  181.             */
  182.         function nggv_saveVoteImage($config) {
  183.             if(is_numeric($config["pid"]) && $config["vote"] >= 0 && $config["vote"] <= 100) {
  184.                 if(($msg = nggv_canVoteImage($config["pid"])) === true) {
  185.                     global $wpdb, $current_user;
  186.                     get_currentuserinfo();
  187.                     $ip = getUserIp();
  188.                     if($wpdb->query("INSERT INTO ".$wpdb->prefix."nggv_votes (id, gid, pid, vote, user_id, ip, proxy, dateadded) VALUES (null, 0, '".$wpdb->escape($config["pid"])."', '".$wpdb->escape($config["vote"])."', '".$current_user->ID."', '".$ip["ip"]."', '".$ip["proxy"]."', '".date("Y-m-d H:i:s", time())."')")) {
  189.                         return true;
  190.                     }else{
  191.                         return false;
  192.                     }
  193.                 }else{
  194.                     return $msg;
  195.                 }
  196.             }
  197.         }
  198.        
  199.         /**
  200.          * Delete all votes for a specific image
  201.          * @param int $pid The picture id from NGG
  202.          * @author Shaun <shaunalberts@gmail.com>
  203.          * @return true on success, false on failure
  204.          */
  205.         function nggv_deleteImageVotes($pid) {
  206.             global $wpdb;
  207.             if($wpdb->query("DELETE FROM ".$wpdb->prefix."nggv_votes WHERE gid = 0 AND pid = ".$wpdb->escape($pid)) !== false) { //check for FALSE vs 0 (0 rows isn't a db error!)
  208.                 return true;
  209.             }else{
  210.                 return false;
  211.             }
  212.            
  213.         }
  214.        
  215.         //gets the users actual IP even if they are behind a proxy (if the proxy is nice enough to let us know their actual IP of course)
  216.         /**
  217.          * Get a users IP.  If the users proxy allows, we get their actual IP, not just the proxies
  218.          * @author Shaun <shaunalberts@gmail.com>
  219.          * @return array("ip"=>string The IP found[might be proxy IP, sorry], "proxy"=>string The proxy IP if the proxy was nice enough to tell us it)
  220.          */
  221.         function getUserIp() {
  222.             if ($_SERVER["HTTP_X_FORWARDED_FOR"]) {
  223.                 if ($_SERVER["HTTP_CLIENT_IP"]) {
  224.                     $proxy = $_SERVER["HTTP_CLIENT_IP"];
  225.                 } else {
  226.                     $proxy = $_SERVER["REMOTE_ADDR"];
  227.                 }
  228.                 $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  229.             } else {
  230.                 if ($_SERVER["HTTP_CLIENT_IP"]) {
  231.                     $ip = $_SERVER["HTTP_CLIENT_IP"];
  232.                 } else {
  233.                     $ip = $_SERVER["REMOTE_ADDR"];
  234.                 }
  235.             }
  236.            
  237.             //if comma list of IPs, get the LAST one
  238.             if($proxy) {
  239.                 $proxy = explode(",", $proxy);
  240.                 $proxy = trim(array_pop($proxy));
  241.             }
  242.             if($ip) {
  243.                 $ip = explode(",", $ip);
  244.                 $ip = trim(array_pop($ip));
  245.             }
  246.            
  247.             return array("ip"=>$ip, "proxy"=>$proxy);
  248.         }
  249.  
  250.         /**
  251.          * Check if a user has voted on a gallery before
  252.          * @param int $gid The NextGEN Gallery ID
  253.          * @param int $userid The users id to check
  254.          * @author Shaun <shaunalberts@gmail.com>
  255.          * @return object of all the votes the user has cast for this gallery, or blank array
  256.          */
  257.         function nggv_userHasVoted($gid, $userid) {
  258.             global $wpdb;
  259.            
  260.             if($votes = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."nggv_votes WHERE gid = '".$wpdb->escape($gid)."' AND user_id = '".$wpdb->escape($userid)."'")) {
  261.                 return $votes;
  262.             }else{
  263.                 return array();
  264.             }
  265.         }
  266.        
  267.         /**
  268.          * Check if an IP has voted on a gallery before
  269.          * @param int $gid The NextGEN Gallery ID
  270.          * @param string The IP to check.  If not passed, the current users IP will be assumed
  271.          * @author Shaun <shaunalberts@gmail.com>
  272.          * @return object of all the votes this IP has cast for this gallery, or blank array
  273.          */
  274.         function nggv_ipHasVoted($gid, $ip=null) {
  275.             global $wpdb;
  276.             if(!$ip) {
  277.                 $tmp = getUserIp();
  278.                 $ip = $tmp["ip"];
  279.             }
  280.            
  281.             if($votes = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."nggv_votes WHERE gid = '".$wpdb->escape($gid)."' AND ip = '".$wpdb->escape($ip)."'")) {
  282.                 return $votes;
  283.             }else{
  284.                 return array();
  285.             }
  286.            
  287.         }
  288.        
  289.         /**
  290.             * Check if a user has voted on an image before
  291.             * @param int $pid The image ID to check
  292.             * @param int $userid The users id to check
  293.             * @author Shaun <shaunalberts@gmail.com>
  294.             * @return object of all the votes the user has cast for this image, or blank array
  295.             */
  296.         function nggv_userHasVotedImage($pid, $userid) {
  297.             global $wpdb;
  298.            
  299.             if($votes = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."nggv_votes WHERE pid = '".$wpdb->escape($pid)."' AND user_id = '".$wpdb->escape($userid)."'")) {
  300.                 return $votes;
  301.             }else{
  302.                 return array();
  303.             }
  304.         }
  305.  
  306.         /**
  307.             * Check if a user has voted on any image in this $pid gallery before
  308.             * @param int $pid The image ID to check
  309.             * @param int $userid The users id to check
  310.             * @author Shaun <shaunalberts@gmail.com>
  311.             * @return bool true if the user has voted on any image in the same gallery as this $pid, false of not
  312.             */
  313.         function nggv_userHasVotedOnGalleryImage($pid, $userid) {
  314.             global $wpdb;
  315.                        
  316.             if(!$image = nggdb::find_image($pid)) {
  317.                 return true; //huh, cant find image, so dont let the person vote to be safe (this should never happen)
  318.             }
  319.            
  320.             $picturelist = nggdb::get_gallery($image->gid);
  321.             foreach ((array)$picturelist as $key=>$val) {
  322.                 if($v = nggv_userHasVotedImage($val->pid, $userid)) {
  323.                     return true; //aha! there was a vote somewhere in this gallery.
  324.                 }
  325.             }
  326.            
  327.             return false; //cant find any votes, so seems safe
  328.            
  329.         }
  330.  
  331.         /**
  332.          * Check if an IP has voted on an image before
  333.          * @param int $pid The image ID
  334.          * @param string The IP to check.  If not passed, the current users IP will be assumed
  335.          * @author Shaun <shaunalberts@gmail.com>
  336.          * @return object of all the votes this IP has cast for this image, or blank array
  337.          */
  338.         function nggv_ipHasVotedImage($pid, $ip=null) {
  339.             global $wpdb;
  340.             if(!$ip) {
  341.                 $tmp = getUserIp();
  342.                 $ip = $tmp["ip"];
  343.             }
  344.            
  345.             if($votes = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."nggv_votes WHERE pid = '".$wpdb->escape($pid)."' AND ip = '".$wpdb->escape($ip)."'")) {
  346.                 return $votes;
  347.             }else{
  348.                 return array();
  349.             }
  350.            
  351.         }
  352.        
  353.         /**
  354.          * Check if an IP has voted on any images in the gallery of the $pid passed
  355.          * @param int $pid The image ID
  356.          * @param string The IP to check.  If not passed, the current users IP will be assumed
  357.          * @author Shaun <shaunalberts@gmail.com>
  358.          * @return bool true if the $ip has voted on any image in the same gallery as this $pid, false of not
  359.          */
  360.         function nggv_ipHasVotedOnGalleryImage($pid, $ip=null) {
  361.             global $wpdb;
  362.                        
  363.             if(!$image = nggdb::find_image($pid)) {
  364.                 return true; //huh, cant find image, so dont let the person vote to be safe (this should never happen)
  365.             }
  366.            
  367.             $picturelist = nggdb::get_gallery($image->gid);
  368.             foreach ((array)$picturelist as $key=>$val) {
  369.                 if($v = nggv_ipHasVotedImage($val->pid, $ip)) {
  370.                     return true; //aha! there was a vote somewhere in this gallery.
  371.                 }
  372.             }
  373.            
  374.             return false; //cant find any votes, so seems safe
  375.         }
  376.        
  377.         /**
  378.          * Get the voting results of a gallery
  379.          * @param int $gid The NextGEN Gallery ID
  380.          * @param array $type The type of results to return (can limti number of queries if you only need the avg for example)
  381.          *  bool type[avg] : Get average vote
  382.          *  bool type[list] : Get all the votes for the gallery
  383.          *  bool type[number] : Get the number of votes for the gallery
  384.          * @author Shaun <shaunalberts@gmail.com>
  385.          * @return array("avg"=>double average for gallery, "list"=>array of objects of all votes of the gallery, "number"=>integer the number of votes for the gallery)
  386.          */
  387.         //Changed by Wookiee
  388.         //function nggv_getVotingResults($gid, $type=array("avg"=>true, "list"=>true, "number"=>true, "likes"=>true, "dislikes"=>true)) {
  389.         function nggv_getVotingResults($gid, $type=array("avg"=>true, "list"=>true, "number"=>true, "likes"=>true)) {  
  390.            
  391.             if(is_numeric($gid)) {
  392.                 global $wpdb;
  393.                
  394.                 if($type["avg"]) {
  395.                     $avg = $wpdb->get_row("SELECT SUM(vote) / COUNT(vote) AS avg FROM ".$wpdb->prefix."nggv_votes WHERE gid = '".$wpdb->escape($gid)."' GROUP BY gid");
  396.                 }
  397.                 if($type["list"]) {
  398.                     $list = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."nggv_votes WHERE gid = '".$wpdb->escape($gid)."' ORDER BY dateadded DESC");
  399.                 }
  400.                 if($type["num"]) {
  401.                     $num = $wpdb->get_row("SELECT COUNT(vote) AS num FROM ".$wpdb->prefix."nggv_votes WHERE gid = '".$wpdb->escape($gid)."' GROUP BY gid");
  402.                 }
  403.                 if($type["likes"]) {
  404.                     $likes = $wpdb->get_row("SELECT COUNT(vote) AS num FROM ".$wpdb->prefix."nggv_votes WHERE gid = '".$wpdb->escape($gid)."' AND vote = 100 GROUP BY gid");
  405.                 }
  406.                 //Changed by Wookiee
  407.                 //if($type["dislikes"]) {
  408.                 //  $dislikes = $wpdb->get_row("SELECT COUNT(vote) AS num FROM ".$wpdb->prefix."nggv_votes WHERE gid = '".$wpdb->escape($gid)."' AND vote = 0 GROUP BY gid");
  409.                 //}
  410.                
  411.                 //return array("avg"=>$avg->avg, "list"=>$list, "number"=>$num->num, "likes"=>($likes->num ? $likes->num : 0), "dislikes"=>($dislikes->num ? $dislikes->num : 0));
  412.                 return array("avg"=>$avg->avg, "list"=>$list, "number"=>$num->num, "likes"=>($likes->num ? $likes->num : 0));
  413.                
  414.             }else{
  415.                 return array();
  416.             }
  417.         }
  418.  
  419.         /**
  420.          * Get the voting results of an image
  421.          * @param int $pid The image ID
  422.          * @param array $type The type of results to return (can limit number of queries if you only need the avg for example)
  423.          *  bool type[avg] : Get average vote
  424.          *  bool type[list] : Get all the votes for the gallery
  425.          *  bool type[number] : Get the number of votes for the gallery
  426.          * @author Shaun <shaunalberts@gmail.com>
  427.          * @return array("avg"=>double average for image, "list"=>array of objects of all votes of the image, "number"=>integer the number of votes for the image)
  428.          */
  429.             //Changed by Wookiee
  430.             //function nggv_getImageVotingResults($pid, $type=array("avg"=>true, "list"=>true, "number"=>true, "likes"=>true, "dislikes"=>true)) {
  431.             function nggv_getImageVotingResults($pid, $type=array("avg"=>true, "list"=>true, "number"=>true, "likes"=>true)) {
  432.            
  433.             if(is_numeric($pid)) {
  434.                 global $wpdb;
  435.                
  436.                 if($type["avg"]) {
  437.                     $avg = $wpdb->get_row("SELECT SUM(vote) / COUNT(vote) AS avg FROM ".$wpdb->prefix."nggv_votes WHERE pid = '".$wpdb->escape($pid)."' GROUP BY pid");
  438.                 }
  439.                 if($type["list"]) {
  440.                     $list = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."nggv_votes WHERE pid = '".$wpdb->escape($pid)."' ORDER BY dateadded DESC");
  441.                 }
  442.                 if($type["num"]) {
  443.                     $num = $wpdb->get_row("SELECT COUNT(vote) AS num FROM ".$wpdb->prefix."nggv_votes WHERE pid = '".$wpdb->escape($pid)."' GROUP BY pid");
  444.                 }
  445.                 if($type["likes"]) {
  446.                     $likes = $wpdb->get_row("SELECT COUNT(vote) AS num FROM ".$wpdb->prefix."nggv_votes WHERE pid = '".$wpdb->escape($pid)."' AND vote = 100 GROUP BY pid");
  447.                 }
  448.                 //Changed by Wookiee
  449.                 //if($type["dislikes"]) {
  450.                 //  $dislikes = $wpdb->get_row("SELECT COUNT(vote) AS num FROM ".$wpdb->prefix."nggv_votes WHERE pid = '".$wpdb->escape($pid)."' AND vote = 0 GROUP BY pid");
  451.                 //}
  452.  
  453.                 //return array("avg"=>$avg->avg, "list"=>$list, "number"=>$num->num, "likes"=>($likes->num ? $likes->num : 0), "dislikes"=>($dislikes->num ? $dislikes->num : 0));
  454.                 return array("avg"=>$avg->avg, "list"=>$list, "number"=>$num->num, "likes"=>($likes->num ? $likes->num : 0));
  455.                
  456.             }else{
  457.                 return array();
  458.             }
  459.         }
  460.     //}
  461.    
  462.     // admin functions {
  463.         //proper admin inits as of 1.10
  464.         add_action('admin_init', 'nggv_adminInit');
  465.         function nggv_adminInit() {
  466.             //at some point WP (or NGG?) stopped loading thickbox. It is being used for displaying vote details to admin, so this makes sure it's loaded again
  467.             wp_enqueue_script('thickbox');
  468.             wp_enqueue_style('thickbox');
  469.         }
  470.    
  471.         add_action('admin_menu', 'nggv_adminMenu');
  472.         function nggv_adminMenu() {
  473.             add_menu_page('NGG Voting Defaults', 'NGG Voting Defaults', 'manage_options', __FILE__, 'nggv_admin_options');
  474.             add_submenu_page(__FILE__, 'NGG Voting Top Rated Images', 'Top Rated Images', 'manage_options', 'nggv-top-rated-images', 'nggv_admin_top_rated_images');
  475.         }
  476.         //I didn't know about the whole slug/identifier thing to register url's with wp, so kinda hacked my own solution. meh
  477.         function nggv_admin_options() {
  478.             if($_GET["action"] == "get-votes-list") {
  479.                 echo '<!-- NGGV START AJAX RESPONSE -->'; //do not edit this line!!!
  480.                
  481.                 if($_GET["gid"]) {
  482.                     $options = nggv_getVotingOptions($_GET["gid"]);
  483.                     echo 'var nggv_voting_type = '.$options->voting_type.';';
  484.                    
  485.                     $results = nggv_getVotingResults($_GET["gid"]);
  486.                     echo "var nggv_votes_list = [];";
  487.                     foreach ((array)$results["list"] as $key=>$val) {
  488.                         $user_info = $val->user_id ? get_userdata($val->user_id) : array();
  489.                         echo "
  490.                             nggv_votes_list[nggv_votes_list.length] = [];
  491.                             nggv_votes_list[nggv_votes_list.length-1][0] = '".$val->vote."';
  492.                             nggv_votes_list[nggv_votes_list.length-1][1] = '".$val->dateadded."';
  493.                             nggv_votes_list[nggv_votes_list.length-1][2] = '".$val->ip."';
  494.                             nggv_votes_list[nggv_votes_list.length-1][3] = [];
  495.                             nggv_votes_list[nggv_votes_list.length-1][3][0] = '".$val->user_id."';
  496.                             nggv_votes_list[nggv_votes_list.length-1][3][1] = '".$user_info->user_login."';
  497.                         ";
  498.                     }
  499.                 }else if($_GET["pid"]){
  500.                     $options = nggv_getImageVotingOptions($_GET["pid"]);
  501.                     echo 'var nggv_voting_type = '.$options->voting_type.';';
  502.  
  503.                     $results = nggv_getImageVotingResults($_GET["pid"]);
  504.                    
  505.                     echo "var nggv_votes_list = [];";
  506.                     foreach ((array)$results["list"] as $key=>$val) {
  507.                         $user_info = $val->user_id ? get_userdata($val->user_id) : array();
  508.                         echo "
  509.                             nggv_votes_list[nggv_votes_list.length] = [];
  510.                             nggv_votes_list[nggv_votes_list.length-1][0] = '".$val->vote."';
  511.                             nggv_votes_list[nggv_votes_list.length-1][1] = '".$val->dateadded."';
  512.                             nggv_votes_list[nggv_votes_list.length-1][2] = '".$val->ip."';
  513.                             nggv_votes_list[nggv_votes_list.length-1][3] = [];
  514.                             nggv_votes_list[nggv_votes_list.length-1][3][0] = '".$val->user_id."';
  515.                             nggv_votes_list[nggv_votes_list.length-1][3][1] = '".$user_info->user_login."';
  516.                         ";
  517.                     }
  518.                 }else{
  519.                     //error num?
  520.                 }
  521.                
  522.                 exit;
  523.             }else if($_GET['action'] == 'clear-image-votes') {
  524.                 $deleted = nggv_deleteImageVotes($_GET['pid']);
  525.                 //force a crappy reload. yay...
  526.                 echo "<script>window.location = 'admin.php?page=nggallery-manage-gallery&mode=edit&gid=".$_GET['gid']."';</script>";
  527.                 exit;
  528.  
  529.             }else{
  530.                 if($_POST['nggv']) {
  531.                     //Gallery
  532.                     if(get_option('nggv_gallery_enable') === false) { //bool false means does not exists
  533.                         add_option('nggv_gallery_enable', ($_POST['nggv']['gallery']['enable'] ? '1' : '0'), null, 'no');
  534.                     }else{
  535.                         update_option('nggv_gallery_enable', ($_POST['nggv']['gallery']['enable'] ? '1' : '0'));
  536.                     }
  537.                     if(get_option('nggv_gallery_force_login') === false) { //bool false means does not exists
  538.                         add_option('nggv_gallery_force_login', ($_POST['nggv']['gallery']['force_login'] ? '1' : '0'), null, 'no');
  539.                     }else{
  540.                         update_option('nggv_gallery_force_login', ($_POST['nggv']['gallery']['force_login'] ? '1' : '0'));
  541.                     }
  542.                     if(get_option('nggv_gallery_force_once') === false) { //bool false means does not exists
  543.                         add_option('nggv_gallery_force_once', ($_POST['nggv']['gallery']['force_once'] ? '1' : '0'), null, 'no');
  544.                     }else{
  545.                         update_option('nggv_gallery_force_once', ($_POST['nggv']['gallery']['force_once'] ? '1' : '0'));
  546.                     }
  547.                     if(get_option('nggv_gallery_user_results') === false) { //bool false means does not exists
  548.                         add_option('nggv_gallery_user_results', ($_POST['nggv']['gallery']['user_results'] ? '1' : '0'), null, 'no');
  549.                     }else{
  550.                         update_option('nggv_gallery_user_results', ($_POST['nggv']['gallery']['user_results'] ? '1' : '0'));
  551.                     }
  552.                     if(get_option('nggv_gallery_voting_type') === false) { //bool false means does not exists
  553.                         add_option('nggv_gallery_voting_type', $_POST['nggv']['gallery']['voting_type'], null, 'no');
  554.                     }else{
  555.                         update_option('nggv_gallery_voting_type', $_POST['nggv']['gallery']['voting_type']);
  556.                     }
  557.                    
  558.                     //Images
  559.                     if(get_option('nggv_image_enable') === false) { //bool false means does not exists
  560.                         add_option('nggv_image_enable', ($_POST['nggv']['image']['enable'] ? '1' : '0'), null, 'no');
  561.                     }else{
  562.                         update_option('nggv_image_enable', ($_POST['nggv']['image']['enable'] ? '1' : '0'));
  563.                     }
  564.                     if(get_option('nggv_image_force_login') === false) { //bool false means does not exists
  565.                         add_option('nggv_image_force_login', ($_POST['nggv']['image']['force_login'] ? '1' : '0'), null, 'no');
  566.                     }else{
  567.                         update_option('nggv_image_force_login', ($_POST['nggv']['image']['force_login'] ? '1' : '0'));
  568.                     }
  569.                     if(get_option('nggv_image_force_once') === false) { //bool false means does not exists
  570.                         add_option('nggv_image_force_once', ($_POST['nggv']['image']['force_once'] <= 2 ? $_POST['nggv']['image']['force_once'] : '0'), null, 'no');
  571.                     }else{
  572.                         update_option('nggv_image_force_once', ($_POST['nggv']['image']['force_once'] <= 2 ? $_POST['nggv']['image']['force_once'] : '0'));
  573.                     }
  574.                     if(get_option('nggv_image_user_results') === false) { //bool false means does not exists
  575.                         add_option('nggv_image_user_results', ($_POST['nggv']['image']['user_results'] ? '1' : '0'), null, 'no');
  576.                     }else{
  577.                         update_option('nggv_image_user_results', ($_POST['nggv']['image']['user_results'] ? '1' : '0'));
  578.                     }
  579.                     if(get_option('nggv_image_voting_type') === false) { //bool false means does not exists
  580.                         add_option('nggv_image_voting_type', $_POST['nggv']['image']['voting_type'], null, 'no');
  581.                     }else{
  582.                         update_option('nggv_image_voting_type', $_POST['nggv']['image']['voting_type']);
  583.                     }
  584.                 }
  585.                
  586.                 $filepath = admin_url()."admin.php?page=".$_GET["page"];
  587.                 ?>
  588.                 <div class="wrap">
  589.                     <h2>Welcome to NextGEN Gallery Voting</h2>
  590.                     <p>This plugin adds the ability for users to vote on NextGEN Galleries and Images.  If you need any help or find any bugs, please create a post at the Wordpress plugin support forum, with the tag '<a href="http://wordpress.org/tags/nextgen-gallery-voting?forum_id=10" target="_blank">nextgen-gallery-voting</a>'</p>
  591.                
  592.                     <h2>Default Options</h2>
  593.                     <p>Here you can set the default voting options for <strong>new</strong> Galleries and Images.  Setting these options will not affect any existing Galleries or Images</p>
  594.                     <div id="poststuff">
  595.                         <form id="" method="POST" action="<?php echo $filepath; ?>" accept-charset="utf-8" >
  596.                             <input type="hidden" name="nggv[force]" value="1" /> <!-- this will just force _POST['nggv'] even if all checkboxes are unchecked -->
  597.                             <div class="postbox">
  598.                                 <table class="form-table" style="width:550px;">
  599.                                     <tr>
  600.                                         <td colspan="2" style="text-align:right;"><h3>Gallery</h3></th>
  601.                                         <td style="text-align:center;"><h3>Image</h3></th>
  602.                                     </tr>
  603.                                     <tr valign="top">
  604.                                         <th style="width:250px;">Enable:</th>
  605.                                         <td style="width:100px; text-align:center;"><input type="checkbox" name="nggv[gallery][enable]" <?php echo (get_option('nggv_gallery_enable') ? 'checked="checked"' : ''); ?> /></td>
  606.                                         <td style="width:200px; text-align:center;"><input type="checkbox" name="nggv[image][enable]" <?php echo (get_option('nggv_image_enable') ? 'checked="checked"' : ''); ?> /></td>
  607.                                     </tr>
  608.  
  609.                                     <tr valign="top">
  610.                                         <th>Only allow logged in users to vote:</th>
  611.                                         <td style="text-align:center;"><input type="checkbox" name="nggv[gallery][force_login]" <?php echo (get_option('nggv_gallery_force_login') ? 'checked="checked"' : ''); ?> /></td>
  612.                                         <td style="text-align:center;"><input type="checkbox" name="nggv[image][force_login]" <?php echo (get_option('nggv_image_force_login') ? 'checked="checked"' : ''); ?> /></td>
  613.                                     </tr>
  614.  
  615.                                     <tr valign="top">
  616.                                         <th>Number of votes allowed<br ><em>(IP or userid is used to stop multiple)</em></th>
  617.                                         <td style="text-align:center;"><input type="checkbox" name="nggv[gallery][force_once]" <?php echo (get_option('nggv_gallery_force_once') ? 'checked="checked"' : ''); ?> /></td>
  618.                                         <td style="text-align:center;">
  619.                                             <input type="radio" name="nggv[image][force_once]" <?php echo (get_option('nggv_image_force_once') == 0 ? 'checked="checked"' : ''); ?> value="0" />Unlimited votes<br />
  620.                                             <input type="radio" name="nggv[image][force_once]" <?php echo (get_option('nggv_image_force_once') == 1 ? 'checked="checked"' : ''); ?> value="1" />One per image<br />
  621.                                             <input type="radio" name="nggv[image][force_once]" <?php echo (get_option('nggv_image_force_once') == 2 ? 'checked="checked"' : ''); ?> value="2" />One per gallery image is in
  622.                                         </td>
  623.                                     </tr>
  624.  
  625.                                     <tr valign="top">
  626.                                         <th>Allow users to see results:</th>
  627.                                         <td style="text-align:center;"><input type="checkbox" name="nggv[gallery][user_results]" <?php echo (get_option('nggv_gallery_user_results') ? 'checked="checked"' : ''); ?> /></td>
  628.                                         <td style="text-align:center;"><input type="checkbox" name="nggv[image][user_results]" <?php echo (get_option('nggv_image_user_results') ? 'checked="checked"' : ''); ?> /></td>
  629.                                     </tr>
  630.  
  631.                                     <tr valign="top">
  632.                                         <th>Rating Type:</th>
  633.                                         <td style="text-align:center;">
  634.                                             <select name="nggv[gallery][voting_type]">
  635.                                                 <option value="1" <?php echo (get_option('nggv_gallery_voting_type') == 1 ? 'selected="selected"' : ''); ?>>Drop Down</option>
  636.                                                 <option value="2" <?php echo (get_option('nggv_gallery_voting_type') == 2 ? 'selected="selected"' : ''); ?>>Star Rating</option>
  637.                                                 <option value="3" <?php echo (get_option('nggv_gallery_voting_type') == 3 ? 'selected="selected"' : ''); ?>>Like</option>
  638.                                             </select>
  639.                                         </td>
  640.                                         <td style="text-align:center;">
  641.                                             <select name="nggv[image][voting_type]">
  642.                                                 <option value="1" <?php echo (get_option('nggv_image_voting_type') == 1 ? 'selected="selected"' : ''); ?>>Drop Down</option>
  643.                                                 <option value="2" <?php echo (get_option('nggv_image_voting_type') == 2 ? 'selected="selected"' : ''); ?>>Star Rating</option>
  644.                                                 <option value="3" <?php echo (get_option('nggv_image_voting_type') == 3 ? 'selected="selected"' : ''); ?>>Like</option>
  645.                                             </select>
  646.  
  647.                                         </td>
  648.                                     </tr>
  649.  
  650.                                     <tr>
  651.                                         <td colspan="2">
  652.                                             <div class="submit"><input class="button-primary" type="submit" value="Save Defaults"/>
  653.                                             </div>
  654.                                         </td>
  655.                                     </tr>
  656.                                 </table>
  657.                             </div>
  658.                         </form>
  659.                     </div>
  660.                 </div>
  661.                 <?php
  662.             }
  663.         }
  664.        
  665.         add_action('ngg_update_gallery', 'nggv_save_gallery_options', 10, 2);
  666.         /**
  667.          * Save the options for a gallery and/or images
  668.          * @param int $gid The NextGEN Gallery ID
  669.          * @param array $post the _POST array from the gallery save form. We have added the following fields for our options
  670.          *  bool (int 1/0) post["nggv"]["enable"] : Enable voting for the gallery
  671.          *  bool (int 1/0) post["nggv"]["force_login"] : Force the user to login to cast vote
  672.          *  bool (int 1/0) post["nggv"]["force_once"] : Only allow a user to vote once
  673.          *  bool (int 1/0) post["nggv"]["user_results"] : If users see results
  674.          *  bool (int 1/0) post["nggv_image"][image ID]["enable"] : Enable voting for the image
  675.          *  bool (int 1/0) post["nggv_image"][image ID]["force_login"] : Only allow a user to vote once
  676.          *  integer (0, 1, 2) post["nggv_image"][image ID]["force_once"] : Only allow a user to vote once(1), Only allow user to vote once per image in this gallery(2)
  677.          *  bool (int 1/0) post["nggv_image"][image ID]["user_results"] : If users see results
  678.          * @param bool $noReload If set to true, this function will act like an api and simply let the code execution continue after being called.
  679.          *  If false (default), this funtion uses a js hack to reload the page
  680.          * @author Shaun <shaunalberts@gmail.com>
  681.          * @return void
  682.          */
  683.         function nggv_save_gallery_options($gid, $post, $noReload=false) {
  684.             global $wpdb;
  685.  
  686.             if($post["nggv"]) { //gallery options
  687.                 $enable = $post["nggv"]["enable"] ? "1" : "0";
  688.                 $login = $post["nggv"]["force_login"] ? "1" : "0";
  689.                 $once = $post["nggv"]["force_once"] ? "1" : "0";
  690.                 $user_results = $post["nggv"]["user_results"] ? "1" : "0";
  691.                 $voting_type = is_numeric($post["nggv"]["voting_type"]) ? $post["nggv"]["voting_type"] : 1;
  692.                
  693.                 if(nggv_getVotingOptions($gid)) {
  694.                     $wpdb->query("UPDATE ".$wpdb->prefix."nggv_settings SET force_login = '".$login."', force_once = '".$once."', user_results = '".$user_results."', enable = '".$enable."', voting_type = '".$voting_type."' WHERE gid = '".$wpdb->escape($gid)."'");
  695.                 }else{
  696.                     $wpdb->query("INSERT INTO ".$wpdb->prefix."nggv_settings (id, gid, enable, force_login, force_once, user_results, voting_type) VALUES (null, '".$wpdb->escape($gid)."', '".$enable."', '".$login."', '".$once."', '".$user_results."', '".$voting_type."')");
  697.                 }
  698.             }
  699.            
  700.             if($post["nggv_image"]) { //image options
  701.                 foreach ((array)$post["nggv_image"] as $pid=>$val) {
  702.                     $enable = $wpdb->escape($val["enable"]) ? "1" : "0";
  703.                     $login = $wpdb->escape($val["force_login"]) ? "1" : "0";
  704.                     $once = $wpdb->escape($val["force_once"]) <= 2 ? $wpdb->escape($val["force_once"]) : "0";
  705.                     $user_results = $wpdb->escape($val["user_results"]) ? "1" : "0";
  706.                     $voting_type = is_numeric($val["voting_type"]) ? $val["voting_type"] : 1;
  707.  
  708.                     if(nggv_getImageVotingOptions($pid)) {
  709.                         $wpdb->query("UPDATE ".$wpdb->prefix."nggv_settings SET force_login = '".$login."', force_once = '".$once."', user_results = '".$user_results."', enable = '".$enable."', voting_type = '".$voting_type."' WHERE pid = '".$wpdb->escape($pid)."'");
  710.                     }else{
  711.                         $wpdb->query("INSERT INTO ".$wpdb->prefix."nggv_settings (id, pid, enable, force_login, force_once, user_results, voting_type) VALUES (null, '".$wpdb->escape($pid)."', '".$enable."', '".$login."', '".$once."', '".$user_results."', '".$voting_type."')");
  712.                     }
  713.                 }
  714.             }
  715.            
  716.             if(!$noReload) {
  717.                 //gotta force a reload or the js globals declared in nggv_add_vote_options() are set to the pre-saved values, and the checkboxes are ticked incorrectly (hack hackity hack hack hack)
  718.                 echo "<script>window.location = window.location;</script>";
  719.                 exit;
  720.             }
  721.         }
  722.        
  723.         // in version 1.7.0 ngg renamed the filter name
  724.         //if(version_compare(NGGVERSION, '1.6.99', '<')) {
  725.             //add_action("ngg_manage_gallery_columns", "nggv_add_image_vote_options_field");
  726.         //}else{
  727.             add_action("ngg_manage_images_columns", "nggv_add_image_vote_options_field");
  728.         //}
  729.         /**
  730.          * Add a custom field to the images field list.  This give us a place to add the voting options for each image with nggv_add_image_vote_options_field()
  731.          * Also enqueues a script that will add the gallery voting options with js (sneaky, but has to be done)
  732.          * @param array $gallery_columns The array of current fields
  733.          * @author Shaun <shaun@worldwidecreative.co.za>
  734.          * @return array $gallery_columns with an added field
  735.          */
  736.         function nggv_add_image_vote_options_field($gallery_columns) {
  737.             if(version_compare(NGGVERSION, '1.8.0', '>=')) {
  738.                 global $nggv_scripted_tag;
  739.                 if(!$nggv_scripted_tag) {
  740.                     $nggv_scripted_tag = true;
  741.                     echo '<script src="'.WP_PLUGIN_URL.'/nextgen-gallery-voting/js/gallery_options.js"></script>';
  742.                 }
  743.             }else{ //the old way of doing it (sheesh, i didnt read those docs)
  744.                 wp_enqueue_script('nggc_gallery_options', WP_PLUGIN_URL . '/nextgen-gallery-voting/js/gallery_options.js', array('jquery'), false, true);
  745.             }
  746.             $gallery_columns["nggv_image_vote_options"] = "Image Voting Options";
  747.             return $gallery_columns;
  748.         }
  749.  
  750.         // in version 1.7.0 ngg renamed the filter name
  751.         //if(version_compare(NGGVERSION, '1.6.99', '<')) {
  752.             //add_action("ngg_manage_gallery_custom_column", "nggv_add_image_voting_options", 10 ,2);
  753.         //}else{
  754.             add_action("ngg_manage_image_custom_column", "nggv_add_image_voting_options", 10 ,2);
  755.         //}
  756.         /**
  757.          * Add the voing options to the gallery (sneaky js) and each image
  758.          * @param string $gallery_column_key The key value of the 'custom' fields added by nggv_add_image_vote_options_field()
  759.          * @author Shaun <shaun@worldwidecreative.co.za>
  760.          * @return void
  761.          */
  762.         function nggv_add_image_voting_options($gallery_column_key, $pid) {
  763.             global $nggv_scripted;
  764.  
  765.             $uri = $_SERVER["REQUEST_URI"];
  766.             $info = parse_url($uri);
  767.             $dirName = plugin_basename(dirname(__FILE__));
  768.             $popup = $info["path"]."?page=".$dirName."/".basename(__FILE__)."&action=get-votes-list";
  769.            
  770.             if(!$nggv_scripted) { //its a hack, so just check that its only called once :)
  771.                 $nggv_scripted = true;
  772.                 $options = nggv_getVotingOptions($_GET["gid"]);
  773.                 //Changed by Wookiee
  774.                 //$results = nggv_getVotingResults($_GET["gid"], array("avg"=>true, "num"=>true, "likes"=>true, "dislikes"=>true));
  775.                 $results = nggv_getVotingResults($_GET["gid"], array("avg"=>true, "num"=>true, "likes"=>true));
  776.                
  777.                 /* Changed by Wookiee
  778.                 echo "<script>
  779.                 var nggv_gid = parseInt(".$_GET["gid"].");
  780.                 var nggv_enable = parseInt(".$options->enable.");
  781.                 var nggv_login = parseInt(".$options->force_login.");
  782.                 var nggv_once = parseInt(".$options->force_once.");
  783.                 var user_results = parseInt(".$options->user_results.");
  784.                 var voting_type = parseInt(".$options->voting_type.");
  785.                 var nggv_avg = Math.round(".($results["avg"] ? $results["avg"] : 0).") / 10;
  786.                 var nggv_num_votes = parseInt(".($results["number"] ? $results["number"] : 0).");
  787.                 var nggv_num_likes = parseInt(".($results["likes"] ? $results["likes"] : 0).");
  788.                 var nggv_num_dislikes = parseInt(".($results["dislikes"] ? $results["dislikes"] : 0).");
  789.                
  790.                 var nggv_more_url = '".$popup."';
  791.                 </script>";
  792.                 */
  793.                
  794.                 echo "<script>
  795.                 var nggv_gid = parseInt(".$_GET["gid"].");
  796.                 var nggv_enable = parseInt(".$options->enable.");
  797.                 var nggv_login = parseInt(".$options->force_login.");
  798.                 var nggv_once = parseInt(".$options->force_once.");
  799.                 var user_results = parseInt(".$options->user_results.");
  800.                 var voting_type = parseInt(".$options->voting_type.");
  801.                 var nggv_avg = Math.round(".($results["avg"] ? $results["avg"] : 0).") / 10;
  802.                 var nggv_num_votes = parseInt(".($results["number"] ? $results["number"] : 0).");
  803.                 var nggv_num_likes = parseInt(".($results["likes"] ? $results["likes"] : 0).");
  804.                                
  805.                 var nggv_more_url = '".$popup."';
  806.                 </script>";
  807.                
  808.                
  809.                
  810.                 //the popup window for results
  811.                 echo '<div id="nggvShowList" style="display:none;">';
  812.                 echo '<span style="float:right;" width: 100px; height: 40px; border:>';
  813.                 echo '<a href="#" id="nggv_more_results_close">Close Window</a>';
  814.                 echo '</span>';
  815.                 echo '<div style="clear:both;"></div>';
  816.                
  817.                 echo '<div id="nggvShowList_content">';
  818.                 echo '<img src="'.WP_PLUGIN_URL."/".$dirName."/images/loading.gif".'" />';
  819.                 echo '</div>';
  820.                 echo '</div>';
  821.             }
  822.  
  823.             if($gallery_column_key == "nggv_image_vote_options") {
  824.                 $opts = nggv_getImageVotingOptions($pid);
  825.                 echo "<table width='100%'";
  826.                 echo "<tr><td width='1px'><input type='checkbox' name='nggv_image[".$pid."][enable]' value=1 ".($opts->enable ? "checked" : "")." /></td><td>Enable for image</td></tr>";
  827.                 echo "<tr><td width='1px'><input type='checkbox' name='nggv_image[".$pid."][force_login]' value=1 ".($opts->force_login ? "checked" : "")." /></td><td>Only allow logged in users</td></tr>";
  828.                 //echo "<tr><td width='1px'><input type='checkbox' name='nggv_image[".$pid."][force_once]' value=1 ".($opts->force_once ? "checked" : "")." /></td><td>Only allow 1 vote per person</td></tr>";
  829.                 echo "<tr><td width='1px'><input type='radio' name='nggv_image[".$pid."][force_once]' value=3 ".(!$opts->force_once ? "checked" : "")." /></td><td>Unlimited votes for this image</td></tr>";
  830.                 echo "<tr><td width='1px'><input type='radio' name='nggv_image[".$pid."][force_once]' value=1 ".($opts->force_once == 1 ? "checked" : "")." /></td><td>Only allow 1 vote per person for this image</td></tr>";
  831.                 echo "<tr><td width='1px'><input type='radio' name='nggv_image[".$pid."][force_once]' value=2 ".($opts->force_once == 2 ? "checked" : "")." /></td><td>Only allow 1 vote per person for this gallery</td></tr>";
  832.                 echo "<tr><td width='1px'><input type='checkbox' name='nggv_image[".$pid."][user_results]' value=1 ".($opts->user_results ? "checked" : "")." /></td><td>Allow users to see results</td></tr>";
  833.                
  834.                 echo "<tr><td colspan=2>";
  835.                 echo "Rating Type: <select name='nggv_image[".$pid."][voting_type]'>";
  836.                 echo "<option value='1' ".($opts->voting_type == 1 || !$opts->voting_type ? "selected" : "").">Drop Down</option>";
  837.                 echo "<option value='2' ".($opts->voting_type == 2 ? "selected" : "").">Star Rating</option>";
  838.                 echo "<option value='3' ".($opts->voting_type == 3 ? "selected" : "").">Like</option>";
  839.                 echo "</select>";
  840.                 echo "</td></tr>";
  841.  
  842.                
  843.                 echo "</table>";
  844.                 if($opts->voting_type == 3) {
  845.                     //Changed by Wookiee
  846.                     //$results = nggv_getImageVotingResults($pid, array("likes"=>true, "dislikes"=>true));
  847.                     $results = nggv_getImageVotingResults($pid, array("likes"=>true));
  848.                     echo "Current Votes: ";
  849.                     echo "<a href='' class='nggv_mote_results_image' id='nggv_more_results_image_".$pid."'>";
  850.                     echo $results['likes'].' ';
  851.                     echo $results['likes'] == 1 ? 'Vote ' : 'Votes ';
  852.                     //echo $results['dislikes'].' ';
  853.                     //echo $results['dislikes'] == 1 ? 'Dislike' : 'Dislikes';
  854.                     echo "</a>";
  855.                 }else{
  856.                     $results = nggv_getImageVotingResults($pid, array("avg"=>true, "num"=>true));
  857.                     echo "Current Avg: ".round(($results["avg"] / 10), 1)." / 10 <a href='#' class='nggv_mote_results_image' id='nggv_more_results_image_".$pid."'>(".($results["number"] ? $results["number"] : "0")." votes cast)</a>";
  858.                 }
  859.                
  860.                 echo '<br />[&nbsp;<a class="nggv_clear_image_results" href="'.$info['path'].'?page='.$dirName.'/'.basename(__FILE__).'&action=clear-image-votes&pid='.$pid.'&gid='.$_GET["gid"].'">Clear Votes</a>&nbsp;]';
  861.             }
  862.         }
  863.        
  864.         add_action("ngg_add_new_gallery_form", "nggv_new_gallery_form"); //new in ngg 1.4.0a
  865.         /**
  866.          * Adds the default voting options for a new gallery.  Can be tweaked for the specif gallery without affecting the defaults
  867.          * @author Shaun <shaun@worldwidecreative.co.za>
  868.          * @return void
  869.          */
  870.         function nggv_new_gallery_form() {
  871.             ?>
  872.             <tr valign="top">
  873.             <th scope="row">Gallery Voting Options:<br /><em>(Pre-set from <a href="<?php echo admin_url(); ?>admin.php?page=nextgen-gallery-voting/ngg-voting.php">here</a>)</em></th>
  874.             <td>
  875.                 <input type="checkbox" name="nggv[gallery][enable]" <?php echo (get_option('nggv_gallery_enable') ? 'checked="checked"' : ''); ?> />
  876.                 Enable<br />
  877.                
  878.                 <input type="checkbox" name="nggv[gallery][force_login]" <?php echo (get_option('nggv_gallery_force_login') ? 'checked="checked"' : ''); ?> />
  879.                 Only allow logged in users to vote<br />
  880.                
  881.                 <input type="checkbox" name="nggv[gallery][force_once]" <?php echo (get_option('nggv_gallery_force_once') ? 'checked="checked"' : ''); ?> />
  882.                 Only allow 1 vote per person <em>(IP or userid is used to stop multiple)</em><br />
  883.                
  884.                 <input type="checkbox" name="nggv[gallery][user_results]" <?php echo (get_option('nggv_gallery_user_results') ? 'checked="checked"' : ''); ?> />
  885.                 Allow users to see results<br />
  886.                
  887.                 Rating Type:
  888.                 <select name="nggv[gallery][voting_type]">
  889.                     <option value="1" <?php echo (get_option('nggv_gallery_voting_type') == 1 ? 'selected="selected"' : ''); ?>>Drop Down</option>
  890.                     <option value="2" <?php echo (get_option('nggv_gallery_voting_type') == 2 ? 'selected="selected"' : ''); ?>>Star Rating</option>
  891.                     <option value="3" <?php echo (get_option('nggv_gallery_voting_type') == 3 ? 'selected="selected"' : ''); ?>>Like</option>
  892.                 </select>
  893.             </td>
  894.             </tr>
  895.             <?php
  896.         }
  897.        
  898.         add_action("ngg_created_new_gallery", "nggv_add_new_gallery"); //new in ngg 1.4.0a
  899.         /**
  900.          * Saves the voting options for the new gallery
  901.          * @param int $gid the gallery id
  902.          * @author Shaun <shaun@worldwidecreative.co.za>
  903.          * @return voide
  904.          */
  905.         function nggv_add_new_gallery($gid) {
  906.             if($gid) {
  907.                 $post = array();
  908.                 $post['nggv'] = $_POST['nggv']['gallery'];
  909.                 nggv_save_gallery_options($gid, $post, true);
  910.             }
  911.         }
  912.        
  913.         add_action("ngg_added_new_image", "nggv_add_new_image");
  914.         /**
  915.          * Add the image voting options for a new image (pulled from the defaaults
  916.          * @param array $image the new image details
  917.          * @author Shaun <shaun@worldwidecreative.co.za>
  918.          * @return void
  919.          */
  920.         function nggv_add_new_image($image) {
  921.             if($image['id']) {
  922.                 $post = array();
  923.                 $post['nggv_image'] = array();
  924.                 $post['nggv_image'][$image['id']] = array();
  925.                 $post['nggv_image'][$image['id']]['enable'] = get_option('nggv_image_enable');
  926.                 $post['nggv_image'][$image['id']]['force_login'] = get_option('nggv_image_force_login');
  927.                 $post['nggv_image'][$image['id']]['force_once'] = get_option('nggv_image_force_once');
  928.                 $post['nggv_image'][$image['id']]['user_results'] = get_option('nggv_image_user_results');
  929.                 $post['nggv_image'][$image['id']]['voting_type'] = get_option('nggv_image_voting_type');
  930.                
  931.                 nggv_save_gallery_options($image['galleryID'], $post, true);
  932.             }
  933.         }
  934.        
  935.         function nggv_admin_top_rated_images() {
  936.             global $nggdb, $wpdb;
  937.             $gallerylist = $nggdb->find_all_galleries('gid', 'asc', false, 0, 0, false);
  938.  
  939.             $_GET['nggv']['limit'] = is_numeric($_GET['nggv']['limit']) ? $_GET['nggv']['limit'] : 25;
  940.             $_GET['nggv']['order'] = $_GET['nggv']['order'] ? $_GET['nggv']['order'] : 'DESC';
  941.            
  942.             $qry = 'SELECT pid, SUM(vote) AS total, AVG(vote) AS avg, MIN(vote) AS min, MAX(vote) AS max, COUNT(vote) AS num'; //yes, no joins for now. performance isnt an issue (i hope...)
  943.             $qry .= ' FROM '.$wpdb->prefix.'nggv_votes';
  944.             $qry .= ' WHERE';
  945.             $qry .= ' pid > 0';
  946.             $qry .= ' GROUP BY pid';
  947.             $qry .= ' ORDER BY avg '.$_GET['nggv']['order'];
  948.             $qry .= ' LIMIT 0, '.$_GET['nggv']['limit'];
  949.            
  950.             $list = $wpdb->get_results($qry);
  951.             ?>
  952.             <div class="wrap">
  953.                 <h2>Top Rated Images</h2>
  954.            
  955.                 <div id="poststuff">
  956.                     <form id="" method="GET" action="" accept-charset="utf-8">
  957.                         <input type="hidden" name="page" value="<?php echo $_GET['page']; ?>" />
  958.                         <div class="postbox">
  959.                             <h3>Filter</h3>
  960.                             <table class="form-table">
  961.                                 <tr>
  962.                                     <th>Limit</th>
  963.                                     <td>
  964.                                         <input type="text" name="nggv[limit]" value="<?php echo $_GET['nggv']['limit'] ?>" />
  965.                                     </td>
  966.                                    
  967.                                     <th style="width:20%;">Order</th>
  968.                                     <td style="width:30%;">
  969.                                         <select name="nggv[order]">
  970.                                             <option value="desc" <?php echo ($_GET['nggv']['order'] == 'desc' ? 'selected' : ''); ?>>Highest to Lowest</option>
  971.                                             <option value="asc" <?php echo ($_GET['nggv']['order'] == 'asc' ? 'selected' : ''); ?>>Lowest to Highest</option>
  972.                                         </select>
  973.                                     </td>
  974.                                 </tr>
  975.                                
  976.                                 <tr>
  977.                                     <td colspan=4>
  978.                                         <input class="button-primary" type="submit" value="Filter Images" />
  979.                                     </td>
  980.                                 </tr>
  981.                             </table>
  982.                         </div>
  983.                     </form>
  984.                 </div>
  985.  
  986.                 <?php if($list) { ?>
  987.                     <div class="updated below-h2">
  988.                         Wow, check all those awesome people voing for your images! Have you returned the favour by <a target="_blank" href="http://wordpress.org/extend/plugins/nextgen-gallery-voting/">rating NGG Voting</a>?<br />
  989.                         Maybe you're even more awesomer and might consider <a target="_blank" href="http://shauno.co.za/donate/">donating</a>?
  990.                     </div>
  991.                 <?php } ?>
  992.                
  993.                 <table cellspacing="0" class="wp-list-table widefat fixed">
  994.                 <thead>
  995.                     <tr>
  996.                         <th style="width:30px;">pid</th>
  997.                         <th>Gallery Name</th>
  998.                         <th>Filename</th>
  999.                         <th>Avg / 10</th>
  1000.                         <th>Max / 10</th>
  1001.                         <th>Min / 10</th>
  1002.                         <th>Number Votes</th>
  1003.                         <th></th>
  1004.                     </tr>
  1005.                 </thead>
  1006.                 <?php if($list) { ?>
  1007.                     <tbody>
  1008.                         <?php if($list) { ?>
  1009.                             <?php $cnt = 0; ?>
  1010.                             <?php foreach ($list as $key=>$val) { ?>
  1011.                                 <?php $image = nggdb::find_image($val->pid); ?>
  1012.                                     <tr <?php echo $cnt % 2 == 0 ? 'class="alternate"' : '' ?>>
  1013.                                         <td><?php echo $val->pid ?></td>
  1014.                                         <td><?php echo $image->title; ?></td>
  1015.                                         <td><?php echo $image->filename; ?></td>
  1016.                                         <td><?php echo round($val->avg / 10, 2) ?></td>
  1017.                                         <td><?php echo round($val->max / 10, 2) ?></td>
  1018.                                         <td><?php echo round($val->min / 10, 2) ?></td>
  1019.                                         <td><?php echo $val->num ?> </td>
  1020.                                         <td><img src="<?php echo $image->thumbURL; ?>" /></td>
  1021.                                     </tr>
  1022.                                     <?php $cnt++; ?>
  1023.                                 <?php } ?>
  1024.                         <?php }else{ ?>
  1025.                             <tr>
  1026.                                 <td colspan="4">No records found. <a href="<?php echo $this->pluginUrl; ?>page=sf-gallery-add">Click here</a> to add your first gallery.</td>
  1027.                             </tr>
  1028.                         <?php } ?>
  1029.                     </tbody>
  1030.                 <?php }else{ ?>
  1031.                     <td colspan=6>No results found</td>
  1032.                 <?php } ?>
  1033.             </table>
  1034.  
  1035.             </div>
  1036.            
  1037.            
  1038.             <?php
  1039.         }
  1040.     //}
  1041.  
  1042.     // front end functions {
  1043.         /**
  1044.          * Stops the script including a JS file more than once.  wp_enqueue_script only works
  1045.          * before any buffers have been outputted, so this will have to do
  1046.          * @param string $filename The path/url to the js file to be included
  1047.          * @author Shaun <shaun@worldwidecreative.co.za>
  1048.          * @return string with the <script> tags if not included already, else nothing
  1049.          */
  1050.         function nggv_include_js($filename) {
  1051.             global $nggv_front_scripts;
  1052.            
  1053.             if(!$nggv_front_scripts) {
  1054.                 $nggv_front_scripts = array();
  1055.             }
  1056.            
  1057.             if(!$nggv_front_scripts[$filename]) {
  1058.                 $nggv_front_scripts[$filename] = array('filename'=>$nggv_front_scripts[$filename], 'added'=>true);
  1059.                 return '<script type="text/javascript" src="'.$filename.'"></script>';
  1060.             }
  1061.         }
  1062.    
  1063.         add_filter("ngg_show_gallery_content", "nggv_show_gallery", 10, 2);
  1064.         /**
  1065.          * The function that display to voting form, or results depending on if a user can vote or note
  1066.          * @param string $out The entire markup of the gallery passed from NextGEN
  1067.          * @param int $gid The NextGEN Gallery ID
  1068.          * @author Shaun <shaunalberts@gmail.com>
  1069.          * @return string The voting form (or results) appended to the original gallery markup given
  1070.          */
  1071.         function nggv_show_gallery($out, $gid) {
  1072.             return $out.nggc_voteForm($gid, $buffer);
  1073.         }
  1074.        
  1075.         /**
  1076.          * Using nggv_canVote() display the voting form, or results, or thank you message.  Also calls the nggv_saveVote() once a user casts their vote
  1077.          * @param int $gid The NextGEN Gallery ID
  1078.          * @author Shaun <shaunalberts@gmail.com>
  1079.          * @return string The voting form, or results, or thank you message markup
  1080.          */
  1081.         function nggc_voteForm($gid) {
  1082.             if(!is_numeric($gid)) {
  1083.                 //trigger_error("Invalid argument 1 for function ".__FUNCTION__."(\$galId).", E_USER_WARNING);
  1084.                 return;
  1085.             }
  1086.            
  1087.             $options = nggv_getVotingOptions($gid);
  1088.             $out = "";
  1089.             $errOut = "";
  1090.             if($_POST && !$_POST["nggv"]["vote_pid_id"] && $_POST['nggv']['vote_gid_id'] == $gid) { //select box voting
  1091.                 if($_POST["nggv"]["required_pot_field"]) { //seems spammy
  1092.                     $errOut .= "Vote not saved. Spam like activity detected.";
  1093.                 }else if(($msg = nggv_saveVote(array("gid"=>$gid, "vote"=>$_POST["nggv"]["vote"]))) === true) {
  1094.                     $saved = true;
  1095.                 }else{
  1096.                     //$errOut .= '<div class="nggv-error">';
  1097.                     if($msg == "VOTING NOT ENABLED") {
  1098.                         $errOut .= "This gallery has not turned on voting.";
  1099.                     }else if($msg == "NOT LOGGED IN") {
  1100.                         $errOut .= "You need to be logged in to vote on this gallery.";
  1101.                     }else if($msg == "USER HAS VOTED") {
  1102.                         $errOut .= "You have already voted on this gallery.";
  1103.                     }else if($msg == "IP HAS VOTED") {
  1104.                         $errOut .= "This IP has already voted on this gallery.";
  1105.                     }else{
  1106.                         $errOut .= "There was a problem saving your vote, please try again in a few moments.";
  1107.                     }
  1108.                     //$errOut .= '</div>';
  1109.                     //maybe return $errOut here?  user really should only get here if they are 'hacking' the dom anyway?
  1110.                 }
  1111.             }else if($_GET["gid"] && is_numeric($_GET["r"]) && $gid == $_GET['gid']) { //star or like/dislike, js disabled
  1112.                 if($options->voting_type == 3) { //like/dislike
  1113.                     if($_GET['r']) {$_GET['r'] = 100;} //like/dislike is all or nothing :)
  1114.                 }
  1115.                 if(($msg = nggv_saveVote(array("gid"=>$gid, "vote"=>$_GET["r"]))) === true) {
  1116.                     $saved = true;
  1117.                 }else{
  1118.                     //$errOut .= '<div class="nggv-error">';
  1119.                     if($msg == "VOTING NOT ENABLED") {
  1120.                         $errOut .= "This gallery has not turned on voting.";
  1121.                     }else if($msg == "NOT LOGGED IN") {
  1122.                         $errOut .= "You need to be logged in to vote on this gallery.";
  1123.                     }else if($msg == "USER HAS VOTED") {
  1124.                         $errOut .= "You have already voted on this gallery.";
  1125.                     }else if($msg == "IP HAS VOTED") {
  1126.                         $errOut .= "This IP has already voted on this gallery.";
  1127.                     }else{
  1128.                         $errOut .= "There was a problem saving your vote, please try again in a few moments.";
  1129.                     }
  1130.                     //$errOut .= '</div>';
  1131.                     //maybe return $errOut here?  user really should only get here if they are 'hacking' the dom anyway?
  1132.                 }
  1133.             }
  1134.  
  1135.             if($_GET['ajaxify'] && $_GET['gid'] == $gid) {
  1136.                 $out .= "<!-- NGGV START AJAX RESPONSE -->";
  1137.                 $out .= "var nggv_js = {};";
  1138.                 $out .= "nggv_js.options = {};";
  1139.                 foreach ($options as $key=>$val) {
  1140.                     $out .= 'nggv_js.options.'.$key.' = "'.$val.'";';
  1141.                 }
  1142.                
  1143.                 $out .= "nggv_js.saved = ".($saved ? "1" : "0").";";
  1144.                 $out .= "nggv_js.msg = '".addslashes($errOut)."';";
  1145.             }else if($_GET['gid'] || $_POST['nggv']){
  1146.                 $out .= '<div class="nggv-error">';
  1147.                 $out .= $errOut;
  1148.                 $out .= '</div>';
  1149.             }
  1150.            
  1151.             if((($canVote = nggv_canVote($gid)) === true) && !$saved) { //they can vote, show the form
  1152.                 $url = $_SERVER["REQUEST_URI"];
  1153.                 $url .= (strpos($url, "?") === false ? "?" : (substr($url, -1) == "&" ? "" : "&")); //make sure the url ends in "?" or "&" correctly
  1154.                 //todo, try not duplicate the GET[gid] and GET[r] if clicked 2x
  1155.                
  1156.                 if($options->voting_type == 3) { //like / dislike (new from 1.5)
  1157.                     $dirName = plugin_basename(dirname(__FILE__));
  1158.                     $out .= nggv_include_js(WP_PLUGIN_URL.'/'.$dirName.'/js/ajaxify-likes.js'); //ajaxify voting, from v1.7
  1159.                    
  1160.                     $out .= '<div class="nggv_container">';
  1161.                    
  1162.                     //Changed by Wookiee
  1163.                     /*$out .= '<a href="'.$url.'gid='.$gid.'&r=1" class="nggv-link-like"><img src="'.WP_PLUGIN_URL."/".$dirName."/images/thumbs_up.png".'" alt="Like" /></a>';
  1164.                    
  1165.                     $out .= '<a href="'.$url.'gid='.$gid.'&r=0" class="nggv-link-dislike"><img src="'.WP_PLUGIN_URL."/".$dirName."/images/thumbs_down.png".'" alt="Dislike" /></a>';
  1166.                     */
  1167.                     $out .= '<div class="like_button"><a href="'.$url.'gid='.$gid.'&r=1" class="nggv-link-like">&nbsp;</a></div>';
  1168.                    
  1169.                     $out .= '<img class="nggv-star-loader" src="'.WP_PLUGIN_URL.'/'.$dirName.'/images/loading.gif'.'" style="display:none;" />';
  1170.                     if($options->user_results) {
  1171.                         //Changed by Wookiee
  1172.                         //$results = nggv_getVotingResults($gid, array("likes"=>true, "dislikes"=>true));
  1173.                         $results = nggv_getVotingResults($gid, array("likes"=>true));
  1174.                         $out .= '<div class="like-results">';
  1175.                         $out .= $results['likes'].' ';
  1176.                         $out .= '<span class="like-results-text">';
  1177.                         $out .= $results['likes'] == 1 ? 'Vote ' : 'Votes ';
  1178.                         $out .= '</span>';
  1179.                         //$out .= $results['dislikes'].' ';
  1180.                         //$out .= $results['dislikes'] == 1 ? 'Dislike' : 'Dislikes';
  1181.                         $out .= '</div>';
  1182.                     }
  1183.                     $out .= '</div>';
  1184.                 }elseif($options->voting_type == 2) { //star
  1185.                     $out .= nggv_include_js(WP_PLUGIN_URL.'/nextgen-gallery-voting/js/ajaxify-stars.js');   //ajaxify voting, from v1.7
  1186.                    
  1187.                     $results = nggv_getVotingResults($gid, array("avg"=>true));
  1188.                     $out .= '<link rel="stylesheet" href="'.WP_PLUGIN_URL.'/nextgen-gallery-voting/css/star_rating.css" type="text/css" media="screen" />';
  1189.                     $out .= '<div class="nggv_container">';
  1190.                     $out .= '<span class="inline-rating">';
  1191.                     $out .= '<ul class="star-rating">';
  1192.                     if($options->user_results) { //user can see curent rating
  1193.                         $out .= '<li class="current-rating" style="width:'.round($results["avg"]).'%;">Currently '.round($results["avg"] / 20, 1).'/5 Stars.</li>';
  1194.                     }
  1195.                     $out .= '<li><a href="'.$url.'gid='.$gid.'&r=20" title="1 star out of 5" class="one-star">1</a></li>';
  1196.                     $out .= '<li><a href="'.$url.'gid='.$gid.'&r=40" title="2 stars out of 5" class="two-stars">2</a></li>';
  1197.                     $out .= '<li><a href="'.$url.'gid='.$gid.'&r=60" title="3 stars out of 5" class="three-stars">3</a></li>';
  1198.                     $out .= '<li><a href="'.$url.'gid='.$gid.'&r=80" title="4 stars out of 5" class="four-stars">4</a></li>';
  1199.                     $out .= '<li><a href="'.$url.'gid='.$gid.'&r=100" title="5 stars out of 5" class="five-stars">5</a></li>';
  1200.                     $out .= '</ul>';
  1201.                     $out .= '</span>';
  1202.                     $out .= '<img class="nggv-star-loader" src="'.WP_PLUGIN_URL."/nextgen-gallery-voting/images/loading.gif".'" style="display:none;" />';
  1203.                     $out .= '</div>';
  1204.                 }else{ //it will be 1, but why not use a catch all :) (drop down)
  1205.                     $out .= '<style>';
  1206.                     $out .= '.nggv-gallery-pot {display:none;}';
  1207.                     $out .= '</style>';
  1208.                     $out .= '<div class="nggv_container">';
  1209.                     $out .= '<form method="post" action="">';
  1210.                     $out .= '<input type="text" class="nggv-gallery-pot" name="nggv[required_pot_field]" value="" />'; //honey pot attempt, not sure how useful this will be. I will consider better options for cash :)
  1211.                     $out .= '<input type="hidden" name="nggv[vote_gid_id]" value="'.$gid.'" />';
  1212.                     $out .= '<label forid="nggv_rating">Rate this gallery:</label>';
  1213.                     $out .= '<select id="nggv_rating" name="nggv[vote]">';
  1214.                     $out .= '<option value="0">0</option>';
  1215.                     $out .= '<option value="10">1</option>';
  1216.                     $out .= '<option value="20">2</option>';
  1217.                     $out .= '<option value="30">3</option>';
  1218.                     $out .= '<option value="40">4</option>';
  1219.                     $out .= '<option value="50">5</option>';
  1220.                     $out .= '<option value="60">6</option>';
  1221.                     $out .= '<option value="70">7</option>';
  1222.                     $out .= '<option value="80">8</option>';
  1223.                     $out .= '<option value="90">9</option>';
  1224.                     $out .= '<option value="100">10</option>';
  1225.                     $out .= '</select>';
  1226.                     $out .= '<input type="submit" value="Rate" />';
  1227.                     $out .= '</form>';
  1228.                     $out .= '</div>';
  1229.                 }
  1230.             }else{ //ok, they cant vote.  what next?
  1231.                 if($options->enable) { //votings enabled for this gallery, lets find out more...
  1232.                     if($canVote === "NOT LOGGED IN") { //the api wants them to login to vote
  1233.                         $out .= '<div class="nggv_container">';
  1234.                         $out .= 'Only registered users can vote.  Please login to cast your vote';
  1235.                         $out .= '</div>';
  1236.                     }else if($canVote === "USER HAS VOTED" || $canVote === "IP HAS VOTED" || $canVote === true) { //api tells us they have voted, can they see results? (canVote will be true if they have just voted successfully)
  1237.                         if($options->user_results) { //yes! show it
  1238.                             if($options->voting_type == 3) {
  1239.                                 //Changed by Wookiee
  1240.                                 //$results = nggv_getVotingResults($gid, array("likes"=>true, "dislikes"=>true));
  1241.                                 $results = nggv_getVotingResults($gid, array("likes"=>true));
  1242.                                
  1243.                                 $buffer = '';
  1244.                                 $bufferInner = ''; //buffer the innser, so we can pass it back to the ajax request if enabled
  1245.                                
  1246.                                 $buffer .= '<div class="nggv_container">';
  1247.                                 $bufferInner .= $results['likes'].' ';
  1248.                                 $bufferInner .= $results['likes'] == 1 ? 'Vote ' : 'Votes ';
  1249.                                 //$bufferInner .= $results['dislikes'].' ';
  1250.                                 //$bufferInner .= $results['dislikes'] == 1 ? 'Dislike' : 'Dislikes';
  1251.                                 $buffer .= $bufferInner;
  1252.                                 $buffer .= '</div>';
  1253.                                
  1254.                                 if($_GET['ajaxify']) {
  1255.                                     $out .= "nggv_js.nggv_container = '".addslashes($bufferInner)."';";
  1256.                                 }else{
  1257.                                     $out .= $buffer;
  1258.                                 }
  1259.                             }elseif($options->voting_type == 2) {
  1260.                                 $results = nggv_getVotingResults($gid, array("avg"=>true));
  1261.                                
  1262.                                 $buffer = '';
  1263.                                 $bufferInner = ''; //buffer the innser, so we can pass it back to the ajax request if enabled
  1264.                                
  1265.                                 $buffer .= '<link rel="stylesheet" href="'.WP_PLUGIN_URL.'/nextgen-gallery-voting/css/star_rating.css" type="text/css" media="screen" />';
  1266.                                 $buffer .= '<div class="nggv_container">';
  1267.                                 $bufferInner .= '<span class="inline-rating">';
  1268.                                 $bufferInner .= '<ul class="star-rating">';
  1269.                                 $bufferInner .= '<li class="current-rating" style="width:'.round($results["avg"]).'%;">Currently '.round($results["avg"] / 20, 1).'/5 Stars.</li>';
  1270.                                 $bufferInner .= '<li>1</li>';
  1271.                                 $bufferInner .= '<li>2</li>';
  1272.                                 $bufferInner .= '<li>3</li>';
  1273.                                 $bufferInner .= '<li>4</li>';
  1274.                                 $bufferInner .= '<li>5</li>';
  1275.                                 $bufferInner .= '</ul>';
  1276.                                 $bufferInner .= '</span>';
  1277.                                 $bufferInner .= '<img class="nggv-star-loader" src="'.WP_PLUGIN_URL."/nextgen-gallery-voting/images/loading.gif".'" style="display:none;" />';
  1278.                                 $buffer .= $bufferInner;
  1279.                                 $buffer .= '</div>';
  1280.  
  1281.                                 if($_GET['ajaxify']) {
  1282.                                     $out .= "nggv_js.nggv_container = '".addslashes($bufferInner)."';";
  1283.                                 }else{
  1284.                                     $out .= $buffer;
  1285.                                 }
  1286.                             }else{
  1287.                                 $results = nggv_getVotingResults($gid, array("avg"=>true));
  1288.                                 $out .= '<div class="nggv_container">';
  1289.                                 $out .= 'Current Average: '.round(($results["avg"] / 10), 1)." / 10";
  1290.                                 $out .= '</div>';
  1291.                             }
  1292.                         }else{ //nope, but thanks for trying
  1293.                             $buffer = '';
  1294.                             $bufferInner = ''; //buffer the innser, so we can pass it back to the ajax request if enabled
  1295.  
  1296.                             $buffer .= '<div class="nggv_container">';
  1297.                             $bufferInner .= 'Thank you for casting your vote!';
  1298.                             $buffer .= $bufferInner;
  1299.                             $buffer .= '</div>';
  1300.                            
  1301.                             if($_GET['ajaxify']) {
  1302.                                 $out .= "nggv_js.nggv_container = '".addslashes($bufferInner)."';";
  1303.                             }else{
  1304.                                 $out .= $buffer;
  1305.                             }
  1306.                         }
  1307.                     }
  1308.                 }
  1309.             }
  1310.            
  1311.             if($_GET['ajaxify'] && $_GET['gid'] == $gid) {
  1312.                 $out .= "<!-- NGGV END AJAX RESPONSE -->";
  1313.             }
  1314.            
  1315.             return $out;
  1316.         }
  1317.  
  1318.         function nggv_imageVoteForm($pid) {
  1319.             if(!is_numeric($pid)) {
  1320.                 //trigger_error("Invalid argument 1 for function ".__FUNCTION__."(\$galId).", E_USER_WARNING);
  1321.                 return;
  1322.             }
  1323.            
  1324.             $options = nggv_getImageVotingOptions($pid);
  1325.             $out = "";
  1326.             $errOut = "";
  1327.            
  1328.             if($_POST && $_POST["nggv"]["vote_pid_id"] && $pid == $_POST["nggv"]["vote_pid_id"]) { //dont try save a vote for a gallery silly (and make sure this is the right pid cause we are in a loop)
  1329.                 if($_POST["nggv"]["required_pot_field"]) { //seems spammy
  1330.                     $errOut .= "Vote not saved. Spam like activity detected.";
  1331.                 }else if(($msg = nggv_saveVoteImage(array("pid"=>$pid, "vote"=>$_POST["nggv"]["vote_image"]))) === true) {
  1332.                     $saved = true;
  1333.                 }else{
  1334.                     //$out .= '<div class="nggv-error">';
  1335.                     if($msg == "VOTING NOT ENABLED") {
  1336.                         $errOut .= "Voting is not enabled for this image";
  1337.                     }else if($msg == "NOT LOGGED IN") {
  1338.                         $errOut .= "You need to be logged in to vote on this image.";
  1339.                     }else if($msg == "USER HAS VOTED") {
  1340.                         $errOut .= "You have already voted.";
  1341.                     }else if($msg == "IP HAS VOTED") {
  1342.                         $errOut .= "This IP has already voted.";
  1343.                     }else{
  1344.                         $errOut .= "There was a problem saving your vote, please try again in a few moments.";
  1345.                     }
  1346.                     //$out .= '</div>';
  1347.                     //maybe return $out here?  user really should only get here if they are 'hacking' the dom anyway?
  1348.                 }
  1349.             }else if($_GET["ngg-pid"] && is_numeric($_GET["r"]) && $pid == $_GET["ngg-pid"]) { //star and like/dislike rating, js disabled
  1350.                 if($options->voting_type == 3) { //like/dislike
  1351.                     if($_GET['r']) {$_GET['r'] = 100;} //like/dislike is all or nothing :)
  1352.                 }
  1353.                 if(($msg = nggv_saveVoteImage(array("pid"=>$pid, "vote"=>$_GET["r"]))) === true) {
  1354.                     $saved = true;
  1355.                 }else{
  1356.                     //$out .= '<div class="nggv-error">';
  1357.                     if($msg == "VOTING NOT ENABLED") {
  1358.                         $errOut .= "Voting is not enabled for this image";
  1359.                     }else if($msg == "NOT LOGGED IN") {
  1360.                         $errOut .= "You need to be logged in to vote on this image.";
  1361.                     }else if($msg == "USER HAS VOTED") {
  1362.                         $errOut .= "You have already voted.";
  1363.                     }else if($msg == "IP HAS VOTED") {
  1364.                         $errOut .= "This IP has already voted.";
  1365.                     }else{
  1366.                         $errOut .= "There was a problem saving your vote, please try again in a few moments.";
  1367.                     }
  1368.                     //$out .= '</div>';
  1369.                     //maybe return $out here?  user really should only get here if they are 'hacking' the dom anyway?
  1370.                 }
  1371.             }
  1372.            
  1373.             if($_GET['ajaxify'] && $_GET['ngg-pid'] == $pid) {
  1374.                 $out .= "<!-- NGGV START AJAX RESPONSE -->";
  1375.                 $out .= "var nggv_js = {};";
  1376.                 $out .= "nggv_js.options = {};";
  1377.                 foreach ($options as $key=>$val) {
  1378.                     $out .= 'nggv_js.options.'.$key.' = "'.$val.'";';
  1379.                 }
  1380.                
  1381.                 $out .= "nggv_js.saved = ".($saved ? "1" : "0").";";
  1382.                 $out .= "nggv_js.msg = '".addslashes($errOut)."';";
  1383.             }else{
  1384.                 //TODO XMAS remove color styling
  1385.                 $out .= '<div class="nggv-error" style="display:'.($errOut ? 'block' : 'none').'; border:1px solid red; background:#fcc; padding:10px;">';
  1386.                 $out .= $errOut;
  1387.                 $out .= '</div>';
  1388.             }
  1389.            
  1390.             if((($canVote = nggv_canVoteImage($pid)) === true) && !$saved) { //they can vote, show the form
  1391.                 $url = $_SERVER["REQUEST_URI"];
  1392.                
  1393.                 $url .= (strpos($url, "?") === false ? "?" : (substr($url, -1) == "&" ? "" : "&")); //make sure the url ends in "?" or "&" correctly
  1394.                 //todo, try not duplicate the GET[gid] and GET[r] if clicked 2x
  1395.                 if($options->voting_type == 3) { //like / dislike (new in 1.5)
  1396.                     $dirName = plugin_basename(dirname(__FILE__));
  1397.                     $out .= nggv_include_js(WP_PLUGIN_URL.'/'.$dirName.'/js/ajaxify-likes.js'); //ajaxify voting, from v1.7
  1398.                    
  1399.                     $out .= '<div class="nggv_container">';
  1400.                     //Changed by Wookiee
  1401.                     /*$out .= '<a href="'.$url.'ngg-pid='.$pid.'&r=1" class="nggv-link-like"><img src="'.WP_PLUGIN_URL."/".$dirName."/images/thumbs_up.png".'" alt="Like" /></a>';
  1402.                     $out .= '<a href="'.$url.'ngg-pid='.$pid.'&r=0" class="nggv-link-dislike"><img src="'.WP_PLUGIN_URL."/".$dirName."/images/thumbs_down.png".'" alt="Dislike" /></a>';
  1403.                     */
  1404.                     $out .= '<div class="like_button"><a href="'.$url.'ngg-pid='.$pid.'&r=1" class="nggv-link-like">&nbsp;</a></div>';
  1405.                    
  1406.                     $out .= '<img class="nggv-star-loader" src="'.WP_PLUGIN_URL.'/'.$dirName.'/images/loading.gif'.'" style="display:none;" />';
  1407.                     if($options->user_results) {
  1408.                         //Changed by Wookiee
  1409.                         //$results = nggv_getImageVotingResults($pid, array("likes"=>true, "dislikes"=>true));
  1410.                         $results = nggv_getImageVotingResults($pid, array("likes"=>true));
  1411.                         $out .= '<div class="like-results">';
  1412.                         $out .= $results['likes'].' ';
  1413.                         $out .= '<span class="like-results-text">';
  1414.                         $out .= $results['likes'] == 1 ? 'Vote ' : 'Votes ';
  1415.                         $out .= '</span>';
  1416.                         //$out .= $results['dislikes'].' ';
  1417.                         //$out .= $results['dislikes'] == 1 ? 'Dislike' : 'Dislikes';
  1418.                         $out .= '</div>';
  1419.                     }
  1420.                     $out .= '</div>';
  1421.                 }elseif($options->voting_type == 2) { //star
  1422.                     $out .= nggv_include_js(WP_PLUGIN_URL.'/nextgen-gallery-voting/js/ajaxify-stars.js');   //ajaxify voting, from v1.7
  1423.                     $results = nggv_getImageVotingResults($pid, array("avg"=>true));
  1424.                     $out .= '<link rel="stylesheet" href="'.WP_PLUGIN_URL.'/nextgen-gallery-voting/css/star_rating.css" type="text/css" media="screen" />';
  1425.                     $out .= '<div class="nggv_container">';
  1426.                     $out .= '<span class="inline-rating">';
  1427.                     $out .= '<ul class="star-rating">';
  1428.                     if($options->user_results) { //user can see curent rating
  1429.                         $out .= '<li class="current-rating" style="width:'.round($results["avg"]).'%;">Currently '.round($results["avg"] / 20, 1).'/5 Stars.</li>';
  1430.                     }
  1431.                     $out .= '<li><a href="'.$url.'ngg-pid='.$pid.'&r=20" title="1 star out of 5" class="one-star">1</a></li>';
  1432.                     $out .= '<li><a href="'.$url.'ngg-pid='.$pid.'&r=40" title="2 stars out of 5" class="two-stars">2</a></li>';
  1433.                     $out .= '<li><a href="'.$url.'ngg-pid='.$pid.'&r=60" title="3 stars out of 5" class="three-stars">3</a></li>';
  1434.                     $out .= '<li><a href="'.$url.'ngg-pid='.$pid.'&r=80" title="4 stars out of 5" class="four-stars">4</a></li>';
  1435.                     $out .= '<li><a href="'.$url.'ngg-pid='.$pid.'&r=100" title="5 stars out of 5" class="five-stars">5</a></li>';
  1436.                     $out .= '</ul>';
  1437.                     $out .= '</span>';
  1438.                     $out .= '<img class="nggv-star-loader" src="'.WP_PLUGIN_URL."/nextgen-gallery-voting/images/loading.gif".'" style="display:none;" />';
  1439.                     $out .= '</div>';
  1440.                 }else{
  1441.                     global $_nggv_image_once; //sorry, hacky shit to not output css more than once (meh, it's free, quit bitching)
  1442.                     if(!$_nggv_image_once) {
  1443.                         $out .= '<style>';
  1444.                         $out .= '.nggv-image-pot {display:none;}';
  1445.                         $out .= '</style>';
  1446.                         $_nggv_image_once = 1;
  1447.                     }
  1448.                    
  1449.                     /* dev note.  you can set any values from 0-100 (the api will only allow this range) */
  1450.                     $out .= '<div class="nggv-image-vote-container">';
  1451.                     $out .= '<form method="post" action="#ngg-image-'.$pid.'">';
  1452.                     $out .= '<input type="text" class="nggv-image-pot" name="nggv[required_pot_field]" value="" />'; //honey pot attempt, not sure how useful this will be. I will consider better options for cash :)
  1453.                     $out .= '<label forid="nggv_rating_image_'.$pid.'">Rate this image:</label>';
  1454.                     $out .= '<input type="hidden" name="nggv[vote_pid_id]" value="'.$pid.'" />';
  1455.                     $out .= '<select id="nggv_rating_image_'.$pid.'" name="nggv[vote_image]">';
  1456.                     $out .= '<option value="0">0</option>';
  1457.                     $out .= '<option value="10">1</option>';
  1458.                     $out .= '<option value="20">2</option>';
  1459.                     $out .= '<option value="30">3</option>';
  1460.                     $out .= '<option value="40">4</option>';
  1461.                     $out .= '<option value="50">5</option>';
  1462.                     $out .= '<option value="60">6</option>';
  1463.                     $out .= '<option value="70">7</option>';
  1464.                     $out .= '<option value="80">8</option>';
  1465.                     $out .= '<option value="90">9</option>';
  1466.                     $out .= '<option value="100">10</option>';
  1467.                     $out .= '</select>';
  1468.                     $out .= '<input type="submit" value="Rate" />';
  1469.                     $out .= '</form>';
  1470.                     $out .= '</div>';
  1471.                 }
  1472.             }else{ //ok, they cant vote.  what next?
  1473.                 if($options->enable) { //votings enabled for this gallery, lets find out more...
  1474.                     if($canVote === "NOT LOGGED IN") { //the api wants them to login to vote
  1475.                         $out .= '<div class="nggv-image-vote-container">';
  1476.                         $out .= 'Only registered users can vote on this image.  Please login to cast your vote';
  1477.                         $out .= '</div>';
  1478.                     }else if($canVote === "USER HAS VOTED" || $canVote === "IP HAS VOTED" || $canVote === true) { //api tells us they have voted, can they see results? (canVote will be true if they have just voted successfully)
  1479.                         if($options->user_results) { //yes! show it
  1480.                             if($options->voting_type == 3) {
  1481.                                 //Changed by Wookiee
  1482.                                 //$results = nggv_getImageVotingResults($pid, array("likes"=>true, "dislikes"=>true));
  1483.                                 $results = nggv_getImageVotingResults($pid, array("likes"=>true));
  1484.                                
  1485.                                 $buffer = '';
  1486.                                 $bufferInner = ''; //buffer the innser, so we can pass it back to the ajax request if enabled
  1487.                                
  1488.                                 $buffer .= '<div class="nggv_container">';
  1489.                                 $bufferInner .= $results['likes'].' ';
  1490.                                 $bufferInner .= $results['likes'] == 1 ? 'Vote ' : 'Votes ';
  1491.                                 //$bufferInner .= $results['dislikes'].' ';
  1492.                                 //$bufferInner .= $results['dislikes'] == 1 ? 'Dislike' : 'Dislikes';
  1493.                                 $buffer .= $bufferInner;
  1494.                                 $buffer .= '</div>';
  1495.                                
  1496.                                 if($_GET['ajaxify']) {
  1497.                                     $out .= "nggv_js.nggv_container = '".addslashes($bufferInner)."';";
  1498.                                 }else{
  1499.                                     $out .= $buffer;
  1500.                                 }
  1501.                             }elseif($options->voting_type == 2) {
  1502.                                 $results = nggv_getImageVotingResults($pid, array("avg"=>true));
  1503.                                
  1504.                                 $buffer = '';
  1505.                                 $bufferInner = '';
  1506.                                
  1507.                                 $buffer .= '<link rel="stylesheet" href="'.WP_PLUGIN_URL.'/nextgen-gallery-voting/css/star_rating.css" type="text/css" media="screen" />';
  1508.                                 $buffer .= '<div class="nggv_container">';
  1509.                                 $bufferInner .= '<span class="inline-rating">';
  1510.                                 $bufferInner .= '<ul class="star-rating">';
  1511.                                 $bufferInner .= '<li class="current-rating" style="width:'.round($results["avg"]).'%;">Currently '.round($results["avg"] / 20, 1).'/5 Stars.</li>';
  1512.                                 $bufferInner .= '<li>1</li>';
  1513.                                 $bufferInner .= '<li>2</li>';
  1514.                                 $bufferInner .= '<li>3</li>';
  1515.                                 $bufferInner .= '<li>4</li>';
  1516.                                 $bufferInner .= '<li>5</li>';
  1517.                                 $bufferInner .= '</ul>';
  1518.                                 $bufferInner .= '</span>';
  1519.                                 $bufferInner .= '<img class="nggv-star-loader" src="'.WP_PLUGIN_URL."/nextgen-gallery-voting/images/loading.gif".'" style="display:none;" />';
  1520.                                 $buffer .= $bufferInner;
  1521.                                 $buffer .= '</div>';
  1522.                                
  1523.                                 if($_GET['ajaxify']) {
  1524.                                     $out .= "nggv_js.nggv_container = '".addslashes($bufferInner)."';";
  1525.                                 }else{
  1526.                                     $out .= $buffer;
  1527.                                 }
  1528.                             }else{
  1529.                                 $results = nggv_getImageVotingResults($pid, array("avg"=>true));
  1530.                                 $out .= '<div class="nggv-image-vote-container">';
  1531.                                 $out .= 'Current Average: '.round(($results["avg"] / 10), 1)." / 10";
  1532.                                 $out .= '</div>';
  1533.                             }
  1534.                         }else{ //nope, but thanks for trying
  1535.                             $buffer = '';
  1536.                             $bufferInner = ''; //buffer the innser, so we can pass it back to the ajax request if enabled
  1537.                            
  1538.                             $buffer .= '<div class="nggv_container">';
  1539.                             $bufferInner .= 'Thank you for casting your vote!';
  1540.                             $buffer .= $bufferInner;
  1541.                             $buffer .= '</div>';
  1542.                            
  1543.                             if($_GET['ajaxify']) {
  1544.                                 $out .= "nggv_js.nggv_container = '".addslashes($bufferInner)."';";
  1545.                             }else{
  1546.                                 $out .= $buffer;
  1547.                             }
  1548.                         }
  1549.                     }
  1550.                 }
  1551.             }
  1552.            
  1553.             if($_GET['ajaxify'] && $_GET['ngg-pid'] == $pid) {
  1554.                 $out .= "<!-- NGGV END AJAX RESPONSE -->";
  1555.             }
  1556.            
  1557.             return $out;
  1558.         }
  1559.     //}
  1560.  
  1561.     //install func {
  1562.         register_activation_hook(__FILE__, "nggv_install");
  1563.         /**
  1564.          * Create the database tables needed on activation
  1565.          * @author Shaun <shaunalberts@gmail.com>
  1566.          * @return void
  1567.          */
  1568.         function nggv_install() {
  1569.             global $wpdb;
  1570.            
  1571.             $table_name = $wpdb->prefix."nggv_settings";
  1572.             $sql = "CREATE TABLE ".$table_name." (
  1573.                 id BIGINT(19) NOT NULL AUTO_INCREMENT,
  1574.                 gid BIGINT NOT NULL DEFAULT 0,
  1575.                 pid BIGINT NOT NULL DEFAULT 0,
  1576.                 enable TINYINT NOT NULL DEFAULT 0,
  1577.                 force_login TINYINT NOT NULL DEFAULT 0,
  1578.                 force_once TINYINT NOT NULL DEFAULT 0,
  1579.                 user_results TINYINT NOT NULL DEFAULT 0,
  1580.                 voting_type INT NOT NULL DEFAULT 1,
  1581.                 UNIQUE KEY id (id)
  1582.             );";
  1583.             require_once(ABSPATH."wp-admin/includes/upgrade.php");
  1584.             dbDelta($sql);
  1585.            
  1586.             $table_name = $wpdb->prefix."nggv_votes";
  1587.             $sql = "CREATE TABLE ".$table_name." (
  1588.             id BIGINT(19) NOT NULL AUTO_INCREMENT,
  1589.             gid BIGINT NOT NULL,
  1590.             pid BIGINT NOT NULL,
  1591.             vote INT NOT NULL DEFAULT 0,
  1592.             user_id BIGINT NOT NULL DEFAULT 0,
  1593.             ip VARCHAR(32) NULL,
  1594.             proxy VARCHAR(32) NULL,
  1595.             dateadded DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
  1596.             UNIQUE KEY id (id)
  1597.             );";
  1598.             require_once(ABSPATH."wp-admin/includes/upgrade.php");
  1599.             dbDelta($sql);
  1600.         }
  1601.     //}
  1602. //}
  1603. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement