Repustate Clients / php / Repustate.php

<?php
//
//  Repustate PHP API client.
//
//  Requirements:
//  - PHP >= 5.3, with cURL and JSON
//
//  Want to change it / improve it / share it? Go for it.
//
//  Feedback is appreciated at info@repustate.com
//
//  More documentation available at http://www.repustate.com/docs
//

function subst($str, $dict){
    return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str);
}

class Repustate
{
    const urlTemplate = 'http://api.repustate.com/%(version)s/%(key)s/%(function)s.json';

    const pptUrl = 'http://api.repustate.com/%(version)s/%(key)s/powerpoint/';

    public $apiKey;
    public $version;

    public function __construct($apiKey, $version='v2')
    {
        $this->apiKey = $apiKey;
        $this->version = $version;
    }

    //
    // Construct a query string from an array of arguments.
    //
    protected function getQueryString($args)
    {
        $data = array();
        foreach ($args as $k => $v)
        {
            // Skip empty values
            if ($v == '')
            {
                continue;
            }
            $data[] = $k . '=' . rawurlencode($v);
        }
        return join('&', $data);
    }

    //
    // Retrieve the url for the given api function.
    //
    protected function getUrlForCall($apiFunction)
    {
        if ($apiFunction == 'powerpoint')
        {
            $urlTemplate = self::pptUrl;
        }
        else
        {
            $urlTemplate = self::urlTemplate;
        }

        $urlArgs = array(
            'function' => $apiFunction,
            'key' => $this->apiKey,
            'version' => $this->version,
        );

        return subst($urlTemplate, $urlArgs);
    }

    /**
     * Make an HTTP request via cURL for the given url and data.
     */
    protected function getHttpResult($url, $data, $useHttpGet)
    {
        $ch = curl_init();

        if ($useHttpGet)
        {
            $url .= '?' . $data;
        }
        else
        {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, ! $useHttpGet);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        $result = curl_exec($ch);

        if (curl_errno($ch))
        {
            throw new Exception('Curl Error: ' . curl_error($ch));
        }

        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpStatus != 200)
        {
            throw new Exception('HTTP Error: ' . $httpStatus . ' ' . $result);
        }

        curl_close($ch);

        return $result;
    }

    protected function parseResult($result, $apiFunction)
    {
        if ($apiFunction == 'powerpoint')
        {
            return $result;
        }
        else
        {
            // Default is JSON
            return json_decode($result);
        }
    }

    protected function callApi($apiFunction, $args=null, $useHttpGet=FALSE)
    {
        $data = $this->getQueryString($args);
        $url = $this->getUrlForCall($apiFunction);
        $result = $this->getHttpResult($url, $data, $useHttpGet);
        return $this->parseResult($result, $apiFunction);
    }

    //
    // Helper function for the NLP calls.
    //
    protected function callNaturalLanguage($apiFunction, $cloud=null,
                                           $text=null, $url=null)
    {
        $args = array(
            'cloud' => $cloud,
            'text' => $text,
            'url' => $url,
        );
        return $this->callApi($apiFunction, $args);
    }

    //
    // Retreive the sentiment for a single URL or block of text.
    //
    public function sentiment($text=null, $url=null)
    {
        if (is_array($text))
        {
            extract($text, EXTR_IF_EXISTS);
            if (is_array($text))
            {
                $text = null;
            }
        }
        return $this->callApi('score', array('text' => $text, 'url' => $url));
    }

    //
    // Bulk score multiple pieces of text (not urls!).
    //
    public function bulkSentiment($items)
    {
        $itemsToScore = array();
        foreach (array_values($items) as $k => $v)
        {
            $itemsToScore['text' . $k] = $v;
        }
        return $this->callApi('bulk-score', $itemsToScore);
    }

    //
    // Clean up a web page. It doesn't work well on home pages - it's
    // designed for content pages.
    //
    public function clean_html($url=null)
    {
        if (is_array($url)) extract($url, EXTR_IF_EXISTS);
        return $this->callApi('clean-html', array('url' => $url),
                              $useHttpGet=TRUE);
    }

    public function adjectives($cloud=null, $text=null, $url=null)
    {
        if (is_array($cloud))
        {
            extract($cloud, EXTR_IF_EXISTS);
            if (is_array($cloud))
            {
                $cloud = null;
            }
        }
        return $this->callNaturalLanguage('adj', $cloud, $text, $url);
    }

    public function verbs($cloud=null, $text=null, $url=null)
    {
        if (is_array($cloud))
        {
            extract($cloud, EXTR_IF_EXISTS);
            if (is_array($cloud))
            {
                $cloud = null;
            }
        }
        return $this->callNaturalLanguage('verb', $cloud, $text, $url);
    }

    public function ngrams($url=null, $text=null, $max=null, $min=null,
                           $freq=null, $stopwords=null)
    {
        if (is_array($url))
        {
            extract($url, EXTR_IF_EXISTS);
            if (is_array($url))
            {
                $url = null;
            }
        }
        $args = array(
            'url' => $url,
            'text' => $text,
            'max' => $max,
            'min' => $min,
            'freq' => $freq,
            'stopwords' => $stopwords,
        );
        $useHttpGet = ($url != null);
        return $this->callApi('ngrams', $args, $useHttpGet);
    }

    //
    // Convert english date indicators like "today", "tomorrow", "next week"
    // into date strings like 2011-01-12.
    //
    public function dateExtraction($text=null, $relativeDate=null)
    {
        if (is_array($text))
        {
            extract($text, EXTR_IF_EXISTS);
            if (is_array($text))
            {
                $text = null;
            }
        }
        $args = array(
            'text' => $text,
            'relative_date' => $relativeDate,
        );
        return $this->callApi('extract-dates', $args);
    }

    //
    // Given a list of images and titles, generate a simple powerpoint
    // presentation.
    //
    public function powerpoint($reportTitle=null, $author=null, $images=null,
                               $titles=null)
    {
        if (is_array($reportTitle))
        {
            extract($reportTitle, EXTR_IF_EXISTS);
            if (is_array($reportTitle))
            {
                $reportTitle = null;
            }
        }
        $args = array(
            'title' => $reportTitle,
            'author' => $author,
        );
        $zippedArrays = array_map(null, $images, $titles);
        foreach (array_values($zippedArrays) as $k => $v)
        {
            $filename = $v[0];
            $title = $v[1];
            $fileHandle = fopen($filename, 'rb');
            $fileData = fread($fileHandle, filesize($filename));
            fclose($fileHandle);
            $args['slide_' . $k . '_image'] = base64_encode($fileData);
            $args['slide_' . $k . '_title'] = $title;
        }
        return $this->callApi('powerpoint', $args);
    }
}

?>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.