]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Google.php
var --> public
[SourceForge/phpwiki.git] / lib / Google.php
1 <?php
2 /**
3  * Google API
4  *
5  * @author: Chris Petersen, Reini Urban
6  */
7 /*
8  Copyright (c) 2002 Intercept Vector
9  Copyright (c) 2004 Reini Urban
10
11  This library is free software; you can redistribute it and/or
12  modify it under the terms of the GNU Lesser General Public
13  License as published by the Free Software Foundation; either
14  version 2.1 of the License, or (at your option) any later version.
15
16  This library is distributed in the hope that it will be useful,
17  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  Lesser General Public License for more details.
20
21  You should have received a copy of the GNU Lesser General Public
22  License along with this library; if not, write to the Free Software Foundation, Inc.,
23  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
25  If you have any questions or comments, please email:
26
27  Chris Petersen
28  admin@interceptvector.com
29  Intercept Vector
30  http://www.interceptvector.com
31 */
32
33 /*
34  * @seealso: http://scripts.incutio.com/google/
35  */
36
37 /*
38  * Objectified, simplified, documented and added the two other queries
39  * by Reini Urban
40  */
41
42 /**
43  * GoogleSearchResults, list of GoogleSearch Result Elements
44  *
45  * Each time you issue a search request to the Google service, a
46  * response is returned back to you. This section describes the
47  * meanings of the values returned to you.
48  *
49  * <documentFiltering> - A Boolean value indicating whether filtering
50  * was performed on the search results. This will be "true" only if
51  * (a) you requested filtering and (b) filtering actually occurred.
52  *
53  * <searchComments> - A text string intended for display to an end
54  * user. One of the most common messages found here is a note that
55  * "stop words" were removed from the search automatically. (This
56  * happens for very common words such as "and" and "as.")
57  *
58  * <estimatedTotalResultsCount> - The estimated total number of
59  * results that exist for the query.  Note: The estimated number may
60  * be either higher or lower than the actual number of results that
61  * exist.
62  *
63  * <estimateIsExact> - A Boolean value indicating that the estimate is
64  * actually the exact value.
65  *
66  * <resultElements> - An array of <resultElement> items. This
67  * corresponds to the actual list of search results.
68  *
69  * <searchQuery> - This is the value of <q> for the search request.
70  *
71  * <startIndex> - Indicates the index (1-based) of the first search
72  * result in <resultElements>.
73  *
74  * <endIndex> - Indicates the index (1-based) of the last search
75  * result in <resultElements>.
76  *
77  * <searchTips> - A text string intended for display to the end
78  * user. It provides instructive suggestions on how to use Google.
79  *
80  * <directoryCategories> - An array of <directoryCategory> items. This
81  * corresponds to the ODP directory matches for this search.
82  *
83  * <searchTime> - Text, floating-point number indicating the total
84  * server time to return the search results, measured in seconds.
85  */
86
87 class GoogleSearchResults
88 {
89     public $_fields = "documentFiltering,searchComments,estimatedTotalResultsCount,estimateIsExact,searchQuery,startIndex,endIndex,searchTips,directoryCategories,searchTime,resultElements";
90     public $resultElements, $results;
91
92     function GoogleSearchResults($result)
93     {
94         $this->fields = explode(',', $this->_fields);
95         foreach ($this->fields as $f) {
96             $this->{$f} = $result[$f];
97         }
98         $i = 0;
99         $this->results = array();
100         //$this->resultElements = $result['resultElements'];
101         foreach ($this->resultElements as $r) {
102             $this->results[] = new GoogleSearchResult($r);
103         }
104         return $this;
105     }
106 }
107
108 /**
109  *   Google Search Result Element:
110  *
111  *   <summary> - If the search result has a listing in the ODP
112  *   directory, the ODP summary appears here as a text string.
113  *
114  *   <URL> - The URL of the search result, returned as text, with an
115  *   absolute URL path.
116  *
117  *   <snippet> - A snippet which shows the query in context on the URL
118  *   where it appears. This is formatted HTML and usually includes <B>
119  *   tags within it. Note that the query term does not always appear
120  *   in the snippet. Note: Query terms will be in highlighted in bold
121  *   in the results, and line breaks will be included for proper text
122  *   wrapping.
123  *
124  *   <title> - The title of the search result, returned as HTML.
125  *
126  *   <cachedSize> - Text (Integer + "k"). Indicates that a cached
127  *   version of the <URL> is available; size is indicated in
128  *   kilobytes.
129  *
130  *   <relatedInformationPresent> - Boolean indicating that the
131  *   "related:" query term is supported for this URL.
132  *
133  *   <hostName> - When filtering occurs, a maximum of two results from
134  *   any given host is returned. When this occurs, the second
135  *   resultElement that comes from that host contains the host name in
136  *   this parameter.
137  *
138  *   <directoryCategory> - array with "fullViewableName" and
139  *   "specialEncoding" keys.
140  *
141  *   <directoryTitle> - If the URL for this resultElement is contained
142  *   in the ODP directory, the title that appears in the directory
143  *   appears here as a text string. Note that the directoryTitle may
144  *   be different from the URL's <title>.
145  */
146 class GoogleSearchResult
147 {
148     public $_fields = "summary,URL,snippet,title,cachedSize,relatedInformationPresent,hostName,directoryCategory,directoryTitle";
149
150     function GoogleSearchResult($result)
151     {
152         $this->fields = explode(',', $this->_fields);
153         foreach ($this->fields as $f) {
154             $this->{$f} = $result[$f];
155         }
156         return $this;
157     }
158 }
159
160 class Google
161 {
162
163     function Google($maxResults = 10, $license_key = false, $proxy = false)
164     {
165         if ($license_key)
166             $this->license_key = $license_key;
167         elseif (!defined('GOOGLE_LICENSE_KEY')) {
168             trigger_error("\nYou must first obtain a license key at http://www.google.com/apis/"
169                 . "\nto be able to use the Google API." .
170                 "\nIt's free however.", E_USER_WARNING);
171             return false;
172         } else
173             $this->license_key = GOOGLE_LICENSE_KEY;
174         require_once 'lib/nusoap/nusoap.php';
175
176         $this->soapclient = new soapclient(SERVER_URL . NormalizeWebFileName("GoogleSearch.wsdl"), "wsdl");
177         $this->proxy = $this->soapclient->getProxy();
178         if ($maxResults > 10) $maxResults = 10;
179         if ($maxResults < 1) $maxResults = 1;
180         $this->maxResults = $maxResults;
181         return $this;
182     }
183
184     /**
185      * doGoogleSearch
186      *
187      * See http://www.google.com/help/features.html for examples of
188      * advanced features.  Anything that works at the Google web site
189      * will work as a query string in this method.
190      *
191      * You can use the start and maxResults parameters to page through
192      * multiple pages of results. Note that 'maxResults' is currently
193      * limited by Google to 10.  See the API reference for more
194      * advanced examples and a full list of country codes and topics
195      * for use in the restrict parameter, along with legal values for
196      * the language, inputencoding, and outputencoding parameters.
197      *
198      * <license key> Provided by Google, this is required for you to access the
199      * Google service. Google uses the key for authentication and
200      * logging.
201      * <q> (See the API docs for details on query syntax.)
202      * <start> Zero-based index of the first desired result.
203      * <maxResults> Number of results desired per query. The maximum
204      * value per query is 10.  Note: If you do a query that doesn't
205      * have many matches, the actual number of results you get may be
206      * smaller than what you request.
207      * <filter> Activates or deactivates automatic results filtering,
208      * which hides very similar results and results that all come from
209      * the same Web host. Filtering tends to improve the end user
210      * experience on Google, but for your application you may prefer
211      * to turn it off. (See the API docs for more
212      * details.)
213      * <restrict> Restricts the search to a subset of the Google Web
214      * index, such as a country like "Ukraine" or a topic like
215      * "Linux." (See the API docs for more details.)
216      * <safeSearch> A Boolean value which enables filtering of adult
217      * content in the search results. See SafeSearch for more details.
218      * <lr> Language Restrict - Restricts the search to documents
219      * within one or more languages.
220      * <ie> Input Encoding - this parameter has been deprecated and is
221      * ignored. All requests to the APIs should be made with UTF-8
222      * encoding. (See the API docs for details.)
223      * <oe> Output Encoding - this parameter has been deprecated and is
224      * ignored. All requests to the APIs should be made with UTF-8
225      * encoding.
226      */
227     function doGoogleSearch($query, $startIndex = 1, $maxResults = 10, $filter = "false",
228                             $restrict = '', $safeSearch = 'false', $lr = '',
229                             $inputencoding = 'UTF-8', $outputencoding = 'UTF-8')
230     {
231         if (!$this->license_key)
232             return false;
233         // doGoogleSearch() gets created automatically!! (some eval'ed code from the soap request)
234         $result = $this->proxy->doGoogleSearch($this->license_key, // "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
235             $query,
236             $startIndex,
237             $maxResults,
238             $filter,
239             $restrict,
240             $safeSearch,
241             $lr,
242             $inputencoding, // ignored by server, everything is UTF-8 now
243             $outputencoding);
244         return new GoogleSearchResults($result);
245     }
246
247     /**
248      * Retrieve a page from the Google cache.
249      *
250      * Cache requests submit a URL to the Google Web APIs service and
251      * receive in return the contents of the URL when Google's
252      * crawlers last visited the page (if available).
253      *
254      * Please note that Google is not affiliated with the authors of
255      * cached pages nor responsible for their content.
256      *
257      * The return type for cached pages is base64 encoded text.
258      *
259      * @params string url - full URL to the page to retrieve
260      * @return string full text of the cached page
261      */
262     function doGetCachedPage($url)
263     {
264         if (!$this->license_key)
265             return false;
266         // This method gets created automatically!! (some eval'ed code from the soap request)
267         $result = $this->proxy->doGetCachedPage($this->license_key,
268             $url);
269         if (!empty($result)) return base64_decode($result);
270     }
271
272     /**
273      * Get spelling suggestions from Google
274      *
275      * @param  string phrase   word or phrase to spell-check
276      * @return string text of any suggested replacement, or None
277      */
278     function doSpellingSuggestion($phrase)
279     {
280         if (!$this->license_key)
281             return false;
282         // This method gets created automatically!! (some eval'ed code from the soap request)
283         return $this->proxy->doSpellingSuggestion($this->license_key,
284             $phrase);
285     }
286 }
287
288 // Local Variables:
289 // mode: php
290 // tab-width: 8
291 // c-basic-offset: 4
292 // c-hanging-comment-ender-p: nil
293 // indent-tabs-mode: nil
294 // End: