]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Google.php
include [all] Include and file path should be devided with single space. File path...
[SourceForge/phpwiki.git] / lib / Google.php
1 <?php // -*- 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     var $_fields = "documentFiltering,searchComments,estimatedTotalResultsCount,estimateIsExact,searchQuery,startIndex,endIndex,searchTips,directoryCategories,searchTime,resultElements";
89     var $resultElements, $results;
90
91     function GoogleSearchResults ($result) {
92         $this->fields = explode(',',$this->_fields);
93         foreach ($this->fields as $f) {
94             $this->{$f} = $result[$f];
95         }
96         $i = 0; $this->results = array();
97         //$this->resultElements = $result['resultElements'];
98         foreach ($this->resultElements as $r) {
99             $this->results[] = new GoogleSearchResult($r);
100         }
101         return $this;
102     }
103 }
104
105 /**
106  *   Google Search Result Element:
107  *
108  *   <summary> - If the search result has a listing in the ODP
109  *   directory, the ODP summary appears here as a text string.
110  *
111  *   <URL> - The URL of the search result, returned as text, with an
112  *   absolute URL path.
113  *
114  *   <snippet> - A snippet which shows the query in context on the URL
115  *   where it appears. This is formatted HTML and usually includes <B>
116  *   tags within it. Note that the query term does not always appear
117  *   in the snippet. Note: Query terms will be in highlighted in bold
118  *   in the results, and line breaks will be included for proper text
119  *   wrapping.
120  *
121  *   <title> - The title of the search result, returned as HTML.
122  *
123  *   <cachedSize> - Text (Integer + "k"). Indicates that a cached
124  *   version of the <URL> is available; size is indicated in
125  *   kilobytes.
126  *
127  *   <relatedInformationPresent> - Boolean indicating that the
128  *   "related:" query term is supported for this URL.
129  *
130  *   <hostName> - When filtering occurs, a maximum of two results from
131  *   any given host is returned. When this occurs, the second
132  *   resultElement that comes from that host contains the host name in
133  *   this parameter.
134  *
135  *   <directoryCategory> - array with "fullViewableName" and
136  *   "specialEncoding" keys.
137  *
138  *   <directoryTitle> - If the URL for this resultElement is contained
139  *   in the ODP directory, the title that appears in the directory
140  *   appears here as a text string. Note that the directoryTitle may
141  *   be different from the URL's <title>.
142  */
143 class GoogleSearchResult {
144     var $_fields = "summary,URL,snippet,title,cachedSize,relatedInformationPresent,hostName,directoryCategory,directoryTitle";
145     function GoogleSearchResult ($result) {
146         $this->fields = explode(',',$this->_fields);
147         foreach ($this->fields as $f) {
148             $this->{$f} = $result[$f];
149         }
150         return $this;
151     }
152 }
153
154 class Google {
155
156     function Google($maxResults=10,$license_key=false,$proxy=false) {
157         if ($license_key)
158             $this->license_key = $license_key;
159         elseif (!defined('GOOGLE_LICENSE_KEY')) {
160             trigger_error("\nYou must first obtain a license key at http://www.google.com/apis/"
161                          ."\nto be able to use the Google API.".
162                           "\nIt's free however.", E_USER_WARNING);
163             return false;
164         }
165         else
166             $this->license_key = GOOGLE_LICENSE_KEY;
167         require_once 'lib/nusoap/nusoap.php';
168
169         $this->soapclient = new soapclient(SERVER_URL . NormalizeWebFileName("GoogleSearch.wsdl"), "wsdl");
170         $this->proxy = $this->soapclient->getProxy();
171         if ($maxResults > 10) $maxResults = 10;
172         if ($maxResults < 1) $maxResults = 1;
173         $this->maxResults = $maxResults;
174         return $this;
175     }
176
177     /**
178      * doGoogleSearch
179      *
180      * See http://www.google.com/help/features.html for examples of
181      * advanced features.  Anything that works at the Google web site
182      * will work as a query string in this method.
183      *
184      * You can use the start and maxResults parameters to page through
185      * multiple pages of results. Note that 'maxResults' is currently
186      * limited by Google to 10.  See the API reference for more
187      * advanced examples and a full list of country codes and topics
188      * for use in the restrict parameter, along with legal values for
189      * the language, inputencoding, and outputencoding parameters.
190      *
191      * <license key> Provided by Google, this is required for you to access the
192      * Google service. Google uses the key for authentication and
193      * logging.
194      * <q> (See the API docs for details on query syntax.)
195      * <start> Zero-based index of the first desired result.
196      * <maxResults> Number of results desired per query. The maximum
197      * value per query is 10.  Note: If you do a query that doesn't
198      * have many matches, the actual number of results you get may be
199      * smaller than what you request.
200      * <filter> Activates or deactivates automatic results filtering,
201      * which hides very similar results and results that all come from
202      * the same Web host. Filtering tends to improve the end user
203      * experience on Google, but for your application you may prefer
204      * to turn it off. (See the API docs for more
205      * details.)
206      * <restrict> Restricts the search to a subset of the Google Web
207      * index, such as a country like "Ukraine" or a topic like
208      * "Linux." (See the API docs for more details.)
209      * <safeSearch> A Boolean value which enables filtering of adult
210      * content in the search results. See SafeSearch for more details.
211      * <lr> Language Restrict - Restricts the search to documents
212      * within one or more languages.
213      * <ie> Input Encoding - this parameter has been deprecated and is
214      * ignored. All requests to the APIs should be made with UTF-8
215      * encoding. (See the API docs for details.)
216      * <oe> Output Encoding - this parameter has been deprecated and is
217      * ignored. All requests to the APIs should be made with UTF-8
218      * encoding.
219      */
220     function doGoogleSearch($query, $startIndex=1, $maxResults=10, $filter = "false",
221                             $restrict='', $safeSearch='false', $lr='',
222                             $inputencoding='UTF-8', $outputencoding='UTF-8') {
223         if (!$this->license_key)
224             return false;
225         // doGoogleSearch() gets created automatically!! (some eval'ed code from the soap request)
226         $result = $this->proxy->doGoogleSearch($this->license_key, // "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
227                                         $query,
228                                         $startIndex,
229                                         $maxResults,
230                                         $filter,
231                                         $restrict,
232                                         $safeSearch,
233                                         $lr,
234                                         $inputencoding, // ignored by server, everything is UTF-8 now
235                                         $outputencoding);
236         return new GoogleSearchResults($result);
237     }
238
239     /**
240      * Retrieve a page from the Google cache.
241      *
242      * Cache requests submit a URL to the Google Web APIs service and
243      * receive in return the contents of the URL when Google's
244      * crawlers last visited the page (if available).
245      *
246      * Please note that Google is not affiliated with the authors of
247      * cached pages nor responsible for their content.
248      *
249      * The return type for cached pages is base64 encoded text.
250      *
251      *  @params string url - full URL to the page to retrieve
252      *  @return string full text of the cached page
253      */
254     function doGetCachedPage($url) {
255         if (!$this->license_key)
256             return false;
257         // This method gets created automatically!! (some eval'ed code from the soap request)
258         $result = $this->proxy->doGetCachedPage($this->license_key,
259                                                 $url);
260         if (!empty($result)) return base64_decode($result);
261     }
262
263     /**
264      * Get spelling suggestions from Google
265      *
266      * @param  string phrase   word or phrase to spell-check
267      * @return string text of any suggested replacement, or None
268      */
269     function doSpellingSuggestion($phrase) {
270         if (!$this->license_key)
271             return false;
272         // This method gets created automatically!! (some eval'ed code from the soap request)
273         return $this->proxy->doSpellingSuggestion($this->license_key,
274                                                   $phrase);
275     }
276 }
277
278 // Local Variables:
279 // mode: php
280 // tab-width: 8
281 // c-basic-offset: 4
282 // c-hanging-comment-ender-p: nil
283 // indent-tabs-mode: nil
284 // End: