?
Solved

polldaddy api method GetPollResults

Posted on 2011-09-23
6
Medium Priority
?
1,197 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 111

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: 36591106
however, I still need to somehow just pull back results from polls, not so much for users to vote on.
0
How To Reduce Deployment Times With Pre-Baked AMIs

Even if we can't include all the files in the base image, we can sometimes include some of the larger files that we would otherwise have to download, and we can also sometimes remove the most time-consuming steps. This can help a lot with reducing deployment times.

 
LVL 23

Accepted Solution

by:
jeremyjared74 earned 2000 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

765 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