-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathgoogle-cse.php
More file actions
290 lines (268 loc) · 9.13 KB
/
google-cse.php
File metadata and controls
290 lines (268 loc) · 9.13 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<?php
/*
Plugin Name: Google CSE
Plugin URI: http://wordpress.org/extend/plugins/google-cse/
Description: Google powered search for your WordPress site or blog.
Version: 1.0.8
Author: Erik Eng
Author URI: http://erikeng.se/
License: GPLv2 or later
*/
/**
* Define constants
*
* @constant string GCSE_VERSION Plugin version
*/
define('GCSE_VERSION', '1.0.6');
/**
* Security
*
*/
if(!function_exists('add_action')) {
echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
exit;
}
/**
* Admin
*
*/
if(is_admin()) {
require_once dirname( __FILE__ ) . '/admin.php';
}
/**
* TODO: Localization
*
*/
/**
* Google API Request
*
* @see wp_remote_get
*
* @param boolean $test
*
* @since 1.0
*
* @return array
*/
function gcse_request($test = false)
{
global $wp_query;
$options = get_option('gcse_options');
$q = html_entity_decode(get_search_query());
if(isset($options['key']) && $options['key'] &&
isset($options['id']) && $options['id']) {
// Build URL
$num = isset($wp_query->query_vars['posts_per_page']) &&
$wp_query->query_vars['posts_per_page'] < 11 ?
$wp_query->query_vars['posts_per_page'] : 10;
$start = isset($wp_query->query_vars['paged']) &&
$wp_query->query_vars['paged'] ?
($wp_query->query_vars['paged']-1)*$num+1 : 1;
$params = http_build_query(array(
'key' => trim($options['key']),
'cx' => trim($options['id']),
'alt' => 'json',
'num' => $num,
'start' => $start,
'prettyPrint' => 'false',
'q' => $q));
$url = 'https://www.googleapis.com/customsearch/v1?'.$params;
// Check for and return cached response
if($response = get_transient('gcse_'.md5($url))) {
return json_decode($response, true);
}
// Request response
if(is_wp_error($response = wp_remote_get($url, array('sslverify' => false)))) {
return array('error' => array('errors' =>
array(array('reason' => $response->get_error_message()))));
}
}
// Save and return new response
if(isset($response['body'])) {
set_transient('gcse_'.md5($url), $response['body'], 3600);
return json_decode($response['body'], true);
}
else {
return array();
}
}
/**
* Search Results
*
* @since 1.0
*
*/
function gcse_results($posts, $q) {
if($q->is_single !== true && $q->is_search === true) {
global $wp_query;
$response = gcse_request();
if(isset($response['items']) && $response['items']) {
$results = array();
$options = get_option('gcse_options');
foreach($response['items'] as $result) {
if(!isset($options['match']) && $id = gcse_url_to_postid($result['link'])) {
$post = get_post($id);
}
else {
$mime = false;
if(!empty($result['mime'])) {
switch($result['mime']) {
case "application/pdf":
$mime = "PDF";
break;
case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
case "application/vnd.openxmlformats-officedocument.presentationml.template":
case "application/vnd.openxmlformats-officedocument.presentationml.slideshow":
case "application/vnd.ms-powerpoint.addin.macroEnabled.12":
case "application/vnd.ms-powerpoint.presentation.macroEnabled.12":
case "application/vnd.ms-powerpoint.template.macroEnabled.12":
case "application/vnd.ms-powerpoint.slideshow.macroEnabled.12":
case "application/vnd.ms-powerpoint":
$mime = "PPT";
break;
case "application/msword":
case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
case "application/vnd.openxmlformats-officedocument.wordprocessingml.template":
case "application/vnd.ms-word.document.macroEnabled.12":
case "application/vnd.ms-word.template.macroEnabled.12":
$mime = "DOC";
break;
case "application/vnd.ms-excel":
case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
case "application/vnd.openxmlformats-officedocument.spreadsheetml.template":
case "application/vnd.ms-excel.sheet.macroEnabled.12":
case "application/vnd.ms-excel.template.macroEnabled.12":
case "application/vnd.ms-excel.addin.macroEnabled.12":
case "application/vnd.ms-excel.sheet.binary.macroEnabled.12":
$mime = "XLS";
break;
}
}
$post = (object)array(
'post_type' => 'page',
'post_title' => $result['title'],
'post_author' => '',
'post_date' => '',
'post_status' => 'published',
'post_excerpt' => $result['snippet'],
'post_content' => $result['htmlSnippet'],
'guid' => $result['link'],
'post_type' => 'search',
'ID' => 0,
'comment_status' => 'closed',
'mime' => $mime,
);
// Adding in the featured image. You can use it if you'd like.
if(isset($result['pagemap']) && isset($result['pagemap']['cse_image']['0'])) {
$post->cse_img = $result['pagemap']['cse_image'][0]['src'];
}
}
$results[] = $post;
}
$post = '';
// Set results as posts
$posts = $results;
$results = '';
// Update post count
$wp_query->post_count = count($posts);
$wp_query->found_posts = $response['searchInformation']['totalResults'];
// Pagination
$posts_per_page = $wp_query->query_vars['posts_per_page'] < 11 ?
$wp_query->query_vars['posts_per_page'] : 10;
$wp_query->max_num_pages = ceil(
$response['searchInformation']['totalResults'] /
$posts_per_page);
// Apply filters
add_filter('the_permalink', 'gcse_permalink');
}
}
return $posts;
}
if(!is_admin()) {
// Modifies results directly after query is made
add_filter('posts_request', 'gcse_set_dummy_sql', 10, 2);
add_filter('posts_results', 'gcse_results', 99, 2);
add_filter('posts_results', 'gcse_fallback', 100, 2);
}
/**
* URL to Post ID
*
* @param string $url
*
* @since 1.0
*
* @see url_to_postid
* @see http://betterwp.net/wordpress-tips/url_to_postid-for-custom-post-types/
*
* @return int
*/
function gcse_url_to_postid($url)
{
// TODO: Check url to post id map cache
return url_to_postid($url);
}
/**
* Permalink Filter
*
* @since 1.0
*
* @param string $the_permalink
*
* @return string
*
*/
function gcse_permalink($the_permalink)
{
if(function_exists('is_main_query') && is_main_query() && $the_permalink == '') {
global $post;
return $post->guid;
}
else {
return $the_permalink;
}
}
/**
* Set Dummy SQL
*
* Set the sql to SELECT TRUE to avoid a heavy sql query from the database that we won't use (we will get the results from Google Search)
*
* @since 1.0.8
*
* @param string $sql, $q
*
* @return string
*
*/
function gcse_set_dummy_sql($sql, $q)
{
if($q->is_single !== true && $q->is_search === true) {
return "SELECT TRUE";
}
remove_filter('posts_request','gcse_set_dummy_sql',10);
return $sql;
}
/**
* Fallback
*
* After the Google Custom Search returns the results, we check if they are from a SELECT TRUE query.
* If that is the case, it means the request to GCSE failed, so we have to get the results from our own database.
*
* @since 1.0.8
*
* @param array $posts, object $q
*
* @return array
*
*/
function gcse_fallback($posts, $q)
{
if($q->is_single != true && $q->is_search == true) {
if (($posts[0]->filter == 'raw' && $posts[0]->TRUE == '1')) {
remove_filter('posts_request','gcse_set_dummy_sql',10);
remove_filter('posts_results','gcse_results',99);
remove_filter('posts_results','fallback_google_cse',100);
$posts = $q->get_posts();
}
}
return $posts;
}