Solved

polldaddy api method GetPollResults

Posted on 2011-09-23
6
1,142 Views
Last Modified: 2012-05-12
Hi there.  I'm using the following script to pull back poll daddy polls using the api calls.  However, I need to call the api method GetPollResults to get results from a specific poll.  How would I add that to the script below, then add the php code to a page or sidebar widget to display those results?
polldaddy.php:

<?php
    /**
     * Copyright (c) 2011 Khang Minh <betterwp.net>
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program. If not, see <http://www.gnu.org/licenses/>.
     */
     
    function bwp_get_poll($id = '')
    {
        global $bwp_polldaddy;
     
        $polls = $bwp_polldaddy->get_cached_polls();
     
        if (!empty($id) && isset($polls) && is_array($polls))
        {
            foreach ($polls as $poll)
            {
                if ($id == $poll->id)
                    return $poll;
            }
        }
     
        return '';
    }
     
    function bwp_get_polls($limit = 0, $orderby = '', $order = 'desc')
    {
        global $bwp_polldaddy;
     
        $polls = $bwp_polldaddy->get_cached_polls();
     
        if (!isset($polls) || !is_array($polls)) return array();
     
        // Sort by rand
        if ('rand' == $orderby)
        {
            shuffle($polls);
            return (!empty($limit)) ? array_slice($polls, 0, $limit) : $polls;
        }
     
        // Begin sorting
        $orderby = (empty($orderby) || !in_array($orderby, array('created', 'responses'))) ? 'id' : $orderby;
        $sorted_polls = array();
        foreach ($polls as $poll)
        {
            $sorted_polls[$poll->{$orderby}] = $poll;
        }
        if ('asc' == $order)
            ksort($sorted_polls);
        else
            krsort($sorted_polls);
     
        // Limit result
        return (!empty($limit)) ? array_slice($sorted_polls, 0, $limit) : $sorted_polls;
    }
     
    class BWP_PollDaddy {
     
        var $api_key;
        var $api_host = 'http://api.polldaddy.com/';
        var $user_code;
        var $is_ssl;
        var $polls;
        var $last_updated;
     
        function __construct($api_key, $cache_time = 43200, $is_ssl = false)
        {
            $this->api_key = (!empty($api_key)) ? $api_key : NULL;
            $this->is_ssl = (true == $is_ssl) ? true : false;
            $this->api_host = (true == $this->is_ssl) ? 'https://api.polldaddy.com/' : $this->api_host;
            // Get data
            $this->user_code = get_option('bwp_polldaddy_usercode');
            $this->polls = get_option('bwp_polldaddy_polls');
            $this->last_updated = get_option('bwp_polldaddy_updated');
            // Get all data again if the cache is expired or not found
            // Admin only
            if (is_user_logged_in() && current_user_can('manage_options'))
            {
                $time = time();
                if (empty($this->last_updated) || (!empty($cache_time) && $this->last_updated + $cache_time <= $time))
                {
                    // not really have to update this
                    $this->user_code = $this->get_usercode();
                    if (!empty($this->user_code))
                    {
                        $this->polls = $this->get_polls();
                        $this->last_updated = $time;
                    }
                }
                else
                {
                    $this->user_code = (!$this->user_code) ? $this->get_usercode() : $this->user_code;
                    $this->polls = (!$this->polls || !is_array($this->polls)) ? $this->get_polls() : $this->polls;
                }
                // Update all data
                update_option('bwp_polldaddy_usercode', $this->user_code);
                update_option('bwp_polldaddy_polls', $this->polls);
                update_option('bwp_polldaddy_updated', $this->last_updated);
            }
        }
     
        function do_request($request)
        {
            if (empty($request)) return '';
     
            $response = ''; $result = '';
     
            if (function_exists('wp_remote_post'))
            {
                $response = wp_remote_post(
                    $this->api_host,
                    array(
                        'headers' => array('Content-Type' => 'application/json; charset=utf-8', 'Content-Length' => strlen($request)),
                        'user-agent' => 'PollDaddy PHP Client/1.0',
                        'body' => $request
                    )
                );
     
                if (!$response || is_wp_error($response))
                    return '<strong>Polldaddy Error:</strong> Could not connect to API host or no data found';
     
                $result = wp_remote_retrieve_body($response);
            }
            else
            {
                /* Borrowed from the PollDaddy Polls & Rating Plugin */
                $parsed = parse_url($this->api_host);
                if (!isset($parsed['host']) && !isset($parsed['scheme']))
                    return 'Bad API host';
     
                $fp = fsockopen(
                    $parsed['host'],
                    true == $this->is_ssl ? 443 : 80,
                    $err_num,
                    $err_str,
                    3
                );                     
     
                if (!$fp)
                    return '<strong>Polldaddy Error:</strong> Could not connect to API host';
     
                if (function_exists('stream_set_timeout'))
                    stream_set_timeout($fp, 3);
     
                if (!isset($parsed['path']) || !$path = $parsed['path'] . (isset($parsed['query']) ? '?' . $parsed['query'] : ''))
                    $path = '/';
     
                $header  = "POST $path HTTP/1.0\r\n";
                $header .= "Host: {$parsed['host']}\r\n";
                $header .= "User-agent: PollDaddy PHP Client/1.0\r\n";
                $header .= "Content-Type: application/json; charset=utf-8\r\n";
                $header .= 'Content-Length: ' . strlen($request) . "\r\n";
     
                fwrite($fp, "$header\r\n$request");
     
                $response = '';
                while (!feof($fp))
                    $response .= fread($fp, 4096);
                fclose($fp);
     
                if (!$response)
                    return '<strong>Polldaddy Error:</strong> Could not connect to API host or no data found';
     
                list($headers, $result) = explode("\r\n\r\n", $response, 2);
            }
     
            return json_decode($result);
        }
     
        function get_cached_polls()
        {
            return $this->polls;
        }
     
        function get_polls()
        {
            if (empty($this->user_code))
                return '';
     
            $request = '
                {"pdRequest": {
                    "partnerGUID": "' . $this->api_key . '",
                    "userCode": "' . $this->user_code . '",
                    "demands": {
                        "demand": {
                                "id": "GetPolls"
                            }
                        }
                    }
                }
            ';
     
            $response = $this->do_request($request);
     
            if (!isset($response->pdResponse->demands->demand[0]->polls->poll))
                return '<strong>Polldaddy Error:</strong> There was a problem getting polls.';
     
            return $response->pdResponse->demands->demand[0]->polls->poll;
        }
     
        function get_usercode()
        {
            if (!isset($this->api_key))
                return '';
     
            $request  = '
                {"pdAccess": {
                        "partnerGUID": "' . $this->api_key . '",
                        "partnerUserID": "0",
                        "demands": {
                            "demand": {
                                "id": "GetUserCode"
                            }
                        }
                    }
                }
            ';
     
            $response = $this->do_request($request);
     
            if (!isset($response->pdResponse->userCode))
                return '<strong>Polldaddy Error:</strong> Account inaccessible, please recheck your API key.';
     
            return $response->pdResponse->userCode;
        }
    }
?>





functions.php:

//POLL DADDY
include_once('includes/polldaddy.php');
// cache data for 1 day (86400 seconds)
$bwp_polldaddy = new BWP_PollDaddy('a really long number', 0);

Open in new window

0
Comment
Question by:COwebmaster
  • 3
  • 2
6 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36590616
A Google search for polldaddy getPollResults turns up a lot of links to online resources.  What code have you tried so far?
0
 

Author Comment

by:COwebmaster
ID: 36591074
0
 

Author Comment

by:COwebmaster
ID: 36591106
however, I still need to somehow just pull back results from polls, not so much for users to vote on.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 23

Accepted Solution

by:
jeremyjared74 earned 500 total points
ID: 36595262
Hello COwebmaster, I've found a solution for you. It's not the most elegant way but may get you by until another way is found.

If you go to your Polldaddy account you can go to the results section for a given Poll. Once you are in the Results section you'll notice an RSS icon. Right click the RSS icon and choose save link as: now choose somewhere on your computer to save it. By default it will be called something.part. change the .part to .xml and save the file

Next you'll log-in to your WP-Admin section. Go to Tools>Import and choose RSS. Navigate to your file and select it (You might me prompted to install the Import plug-in if you've never used it before). You should see a message after importing that says HAVE FUN!. This part is a little quirky, but it works. You'll have to go to All Posts section and navigate to the very last post in your All Posts section. For some reason every time I tested it it said the Post was from 1970. I changed the date by clicking the Quick Edit button to bring it to the front. You won't see anything in the Post Edit screen, but if you go to your site, you'll see that it has added the poll results to your blog roll.

That's the best I could come up with. The links you provided to the API are for building a plug-in. If you follow the steps they offer you will see that it just builds an APP that will perform as the already existing WP Plug-in. I'm sure there is a way to get the results, but it appears to be a Paid Polldaddy option in the Results Page. Since I don't have a paid account I can't test this option. I hope that helps.
Good luck.
0
 

Author Closing Comment

by:COwebmaster
ID: 36926432
Thanks!
0
 
LVL 23

Expert Comment

by:jeremyjared74
ID: 36926947
Just curious...
                          did you get it to work or are you saying thanks for the effort?
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now