php5-duckduckgo /DuckDuckGo/API.php

Language PHP Lines 164
MD5 Hash b13b6f6e51df4c900e5d5134b89da281 Estimated Cost $1,905 (why?)
Repository git://github.com/duckduckgo/php5-duckduckgo.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<?php

/**
 * @file DuckDuckGo/API.php
 * This file provides the base class to interface with the DuckDuckGo API.
 * It will also include any necessary classes.
 * With this interface, you can currently only perform ZeroClickInfo queries.
 * Simple example:
 *     $api = new DuckDuckGo\API();
 *     $info = $api->zeroClickQuery('Internet Relay Chat');
 *     echo $info->definition;
 */

namespace DuckDuckGo;

/* Include the necessary classes. */
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'APIResult.php';
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ZeroClickInfo.php';

class API
{

    /* General API options and flags. */

    /**
     * The API base URL. This defaults to api.duckduckgo.com.
     */
    public $baseURL;
    /**
     * Whether to use HTTPS or not. This defaults to FALSE (no HTTPS).
     */
    public $secure;
    /**
     * Whether to disallow HTML in the result. This defaults to FALSE (don't disallow HTML).
     */
    public $noHTML;

    /**
     * Query-specific flags
     */

    /**
     * Whether or not to return Disambiguation (D) results (ZeroClickInfo).
     * Defaults to FALSE (allow disambiguation results).
     */
    public $noDisambiguations;


    /* Constructors and internal functions. */

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->secure = FALSE;
        $this->noHTML = FALSE;
        $this->noDisambiguations = FALSE;
        $this->baseURL = 'api.duckduckgo.com';
    }

    /**
     * Construct an API URL, given a section and an associative options array.
     * @param section   Which part of the API to call.
     * @param options   An associative array containing options to pass in key => value form.
     * @return          The API URL that corresponds with this query, which then can be retrieved in order to get the query results.
     */
    protected function constructURL($section, $options)
    {
        $url = '';
        if($this->secure) {
            $url .= 'https://' . $this->baseURL;
        } else {
            $url .= 'http://' . $this->baseURL;
        }
        $url .= $section;

        if(count($options) > 0) {
            $url .= '?' . \urlencode(\current(\array_keys($options))) . '=' . \urlencode(\array_shift($options));

            foreach($options as $name => $value) {
                $url .= '&' . \urlencode($name) . '=' . \urlencode($value);
            }
        }

        return $url;
    }

    /**
     * Given an API section and query options, queries the API and returns the raw results.
     * @param section   Which part of the API to call.
     * @param options   An associative array containing options to pass in key => value form.
     * @return          The raw results of the API call.
     */
    protected function getAPIResult($section, $options)
    {
        $url = $this->constructURL($section, $options);

        if(\extension_loaded('curl')) {
            $curl = \curl_init($url);
            \curl_setopt($curl, CURLOPT_HEADER, FALSE);
            \curl_setopt($curl, CURLOPT_FOLLOWLOCATION, FALSE);
            \curl_setopt($curl, CURLOPT_FRESH_CONNECT, TRUE);
            \curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

            $result = \curl_exec($curl);
            \curl_close($curl);

            return $result;
        }

        if(\function_exists('http_get') && \function_exists('http_parse_message')) {
            $options = array(
                'redirect' => 0,
            );

            return \http_parse_message(\http_get($url), $options)->body;
        }

        if(\ini_get('allow_url_fopen')) {
            $context = \stream_context_create(array(
                'http' => array(
                    'follow_location' => 0,
                )
            ));

            $handle = \fopen($url, 'r', FALSE, $context);
            $result = \stream_get_contents($handle);
            \fclose($handle);

            return $result;
        }

        throw new Exception('Could not find suitable method to retrieve API result. Either install the cURL or pear_http extension, or set allow_url_fopen to 1.');
    }


    /* API functions. */

    /**
     * Perform a ZeroClickInfo query against the DuckDuckGo API.
     * @param query     The term to query for.
     * @return          A ZeroClickInfo object containing the results of the query.
     * @see ZeroClickInfo
     */
    public function zeroClickQuery($query)
    {
        $result = $this->getAPIResult('/', array(
            'q' => $query,
            'format' => 'json',
            'no_html' => ($this->noHTML ? 1 : 0),
            'no_redirect' => 1,
            'skip_disambig' => ($this->noDisambiguations ? 1 : 0),
        ));

        if(!$result) {
            throw new Exception('Could not retrieve API result.');
        }

        return new ZeroClickInfo(\json_decode($result, TRUE));
    }

}
Back to Top