]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Google.php
Added PhpWiki RssFeed to Sidebar
[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
23  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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             return HTML::div(array('class' => 'errors'),
161                              fmt("You must first obtain a license key at %s to be able to use the Google API.",
162                                  WikiLink("http://www.google.com/apis/")),
163                              fmt("It's free however."));
164         else
165             $this->license_key = GOOGLE_LICENSE_KEY;
166         require_once("lib/nusoap/nusoap.php");
167
168         $this->soapclient = new soapclient(SERVER_URL . DATA_PATH."/"."GoogleSearch.wsdl", "wsdl");
169         $this->proxy = $this->soapclient->getProxy();
170         if ($maxResults > 10) $maxResults = 10;
171         if ($maxResults < 1) $maxResults = 1;
172         $this->maxResults = $maxResults;
173         return $this;
174     }
175
176     /** 
177      * doGoogleSearch
178      *
179      * See http://www.google.com/help/features.html for examples of
180      * advanced features.  Anything that works at the Google web site
181      * will work as a query string in this method.
182      * 
183      * You can use the start and maxResults parameters to page through
184      * multiple pages of results. Note that 'maxResults' is currently
185      * limited by Google to 10.  See the API reference for more
186      * advanced examples and a full list of country codes and topics
187      * for use in the restrict parameter, along with legal values for
188      * the language, inputencoding, and outputencoding parameters.
189      *
190      * <license key> Provided by Google, this is required for you to access the
191      * Google service. Google uses the key for authentication and
192      * logging.
193      * <q> (See the API docs for details on query syntax.)
194      * <start> Zero-based index of the first desired result.
195      * <maxResults> Number of results desired per query. The maximum
196      * value per query is 10.  Note: If you do a query that doesn't
197      * have many matches, the actual number of results you get may be
198      * smaller than what you request.
199      * <filter> Activates or deactivates automatic results filtering,
200      * which hides very similar results and results that all come from
201      * the same Web host. Filtering tends to improve the end user
202      * experience on Google, but for your application you may prefer
203      * to turn it off. (See the API docs for more
204      * details.)
205      * <restrict> Restricts the search to a subset of the Google Web
206      * index, such as a country like "Ukraine" or a topic like
207      * "Linux." (See the API docs for more details.)
208      * <safeSearch> A Boolean value which enables filtering of adult
209      * content in the search results. See SafeSearch for more details.
210      * <lr> Language Restrict - Restricts the search to documents
211      * within one or more languages.
212      * <ie> Input Encoding - this parameter has been deprecated and is
213      * ignored. All requests to the APIs should be made with UTF-8
214      * encoding. (See the API docs for details.)
215      * <oe> Output Encoding - this parameter has been deprecated and is
216      * ignored. All requests to the APIs should be made with UTF-8
217      * encoding.
218      */
219     function doGoogleSearch($query, $startIndex=1, $maxResults=10, $filter = "false",
220                             $restrict='', $safeSearch='false', $lr='',
221                             $inputencoding='UTF-8', $outputencoding='UTF-8') {
222         // doGoogleSearch() gets created automatically!! (some eval'ed code from the soap request)
223         $result = $this->doGoogleSearch(GOOGLE_LICENSE_KEY, // "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
224                                         $query,
225                                         $startIndex,
226                                         $maxResults,
227                                         $filter,
228                                         $restrict,
229                                         $safeSearch,
230                                         $lr,
231                                         $inputencoding, // ignored by server, everything is UTF-8 now
232                                         $outputencoding);
233         return new GoogleSearchResults($result);
234     }
235
236     /**
237      * Retrieve a page from the Google cache.
238      *
239      * Cache requests submit a URL to the Google Web APIs service and
240      * receive in return the contents of the URL when Google's
241      * crawlers last visited the page (if available).
242      *
243      * Please note that Google is not affiliated with the authors of
244      * cached pages nor responsible for their content.
245      *
246      * The return type for cached pages is base64 encoded text.
247      *
248      *  @params string url - full URL to the page to retrieve
249      *  @return string full text of the cached page
250      */
251     function doGetCachedPage($url) {
252         // This method gets created automatically!! (some eval'ed code from the soap request)
253         $result = $this->proxy->doGetCachedPage(GOOGLE_LICENSE_KEY,
254                                                 $url);
255         if (!empty($result)) return base64_decode($result);
256     }
257
258     /**
259      * Get spelling suggestions from Google
260      *
261      * @param  string phrase   word or phrase to spell-check 
262      * @return string          text of any suggested replacement, or None
263      */
264     function doSpellingSuggestion($phrase) {
265         // This method gets created automatically!! (some eval'ed code from the soap request)
266         return $this->proxy->doSpellingSuggestion(GOOGLE_LICENSE_KEY,
267                                                   $phrase);
268     }
269 }
270
271 // Local Variables:
272 // mode: php
273 // tab-width: 8
274 // c-basic-offset: 4
275 // c-hanging-comment-ender-p: nil
276 // indent-tabs-mode: nil
277 // End:
278 ?>