-
Notifications
You must be signed in to change notification settings - Fork 2
/
lib.php
371 lines (309 loc) · 8.36 KB
/
lib.php
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php
/**
*@file lib.php
*
* Utility functions
*
*/
require_once(dirname(__FILE__) . '/config.inc.php');
//--------------------------------------------------------------------------------------------------
// safe file name, based on http://snipplr.com/view/5256/filename-safe/
function filename_safe($filename)
{
$temp = $filename;
// Lower case
$temp = strtolower($temp);
// Replace spaces with a '_'
$temp = str_replace(" ", "_", $temp);
// Loop through string
$result = '';
for ($i=0; $i<strlen($temp); $i++)
{
if (preg_match('([0-9]|[a-z]|_)', $temp[$i]))
{
$result = $result . $temp[$i];
}
}
// Return filename
return $result;
}
//--------------------------------------------------------------------------------------------------
/**
* @brief Format JSON nicely
*
* From umbrae at gmail dot com posted 10-Jan-2008 06:21 to http://uk3.php.net/json_encode
*
* @param json Original JSON
*
* @result Formatted JSON
*/
function json_format($json)
{
$tab = " ";
$new_json = "";
$indent_level = 0;
$in_string = false;
/* $json_obj = json_decode($json);
if($json_obj === false)
return false;
$json = json_encode($json_obj); */
$len = strlen($json);
for($c = 0; $c < $len; $c++)
{
$char = $json[$c];
switch($char)
{
case '{':
case '[':
if(!$in_string)
{
$new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
$indent_level++;
}
else
{
$new_json .= $char;
}
break;
case '}':
case ']':
if(!$in_string)
{
$indent_level--;
$new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
}
else
{
$new_json .= $char;
}
break;
case ',':
if(!$in_string)
{
$new_json .= ",\n" . str_repeat($tab, $indent_level);
}
else
{
$new_json .= $char;
}
break;
case ':':
if(!$in_string)
{
$new_json .= ": ";
}
else
{
$new_json .= $char;
}
break;
case '"':
if($c > 0 && $json[$c-1] != '\\')
{
$in_string = !$in_string;
}
default:
$new_json .= $char;
break;
}
}
return $new_json;
}
//--------------------------------------------------------------------------
/**
* @brief Test whether HTTP code is valid
*
* HTTP codes 200 and 302 are OK.
*
* For JSTOR we also accept 403
*
* @param HTTP code
*
* @result True if HTTP code is valid
*/
function HttpCodeValid($http_code)
{
if ( ($http_code == '200') || ($http_code == '302') || ($http_code == '403'))
{
return true;
}
else{
return false;
}
}
//--------------------------------------------------------------------------
/**
* @brief GET a resource
*
* Make the HTTP GET call to retrieve the record pointed to by the URL.
*
* @param url URL of resource
*
* @result Contents of resource
*/
function get($url, $userAgent = '')
{
global $config;
$data = '';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt ($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
if ($userAgent != '')
{
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
}
if ($config['proxy_name'] != '')
{
curl_setopt ($ch, CURLOPT_PROXY, $config['proxy_name'] . ':' . $config['proxy_port']);
}
$curl_result = curl_exec ($ch);
//echo $curl_result;
if (curl_errno ($ch) != 0 )
{
echo "CURL error: ", curl_errno ($ch), " ", curl_error($ch);
}
else
{
$info = curl_getinfo($ch);
//$header = substr($curl_result, 0, $info['header_size']);
//echo $header;
$http_code = $info['http_code'];
//echo "<p><b>HTTP code=$http_code</b></p>";
if (HttpCodeValid ($http_code))
{
$data = $curl_result;
}
}
return $data;
}
//--------------------------------------------------------------------------------------------------
/**
*
* @brief Checking whether a HTTP source has been modified.
*
* We use HTTP conditional GET to check whether source has been updated, see
* http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers .
* ETag and Last Modified header values are stored in a MySQL database table 'feed'.
* ETag is a double-quoted string sent by the HTTP server, e.g. "2f4511-8b92-44717fa6"
* (note the string includes the enclosing double quotes). Last Modified is date,
* written in the form Mon, 22 May 2006 09:08:54 GMT.
*
* @param url Feed URL
*
* @return 0 if source exists and is modified, otherwise an HTTP code or an error
* code.
*
*/
function has_source_changed($url)
{
global $config;
global $ADODB_FETCH_MODE;
$debug_headers = 0;
$result = 0;
// 1. Get details of ETag and LastModified from database
$db = NewADOConnection('mysql');
$db->Connect("localhost",
$config['db_user'] , $config['db_passwd'] , $config['db_name']);
// Ensure fields are (only) indexed by column name
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$sql = 'SELECT last_modified, etag FROM feed WHERE (url = "' . $url . '")';
$sql_result = $db->Execute($sql);
if ($sql_result == false) die("failed [" . __LINE__ . "]: " . $sql);
$ETag = '';
$LastModified = '';
if ($sql_result->RecordCount() == 0)
{
// We don't have this source
$sql = 'INSERT feed (url) VALUES(' . $db->qstr($url) . ')';
$sql_result = $db->Execute($sql);
if ($sql_result == false) die("failed [" . __LINE__ . "]: " . $sql);
}
else
{
$ETag = trim($sql_result->fields['etag']);
$LastModified = trim($sql_result->fields['last_modified']);
}
// Construct conditional GET header
$if_header = array();
if ($LastModified != "''")
{
array_push ($if_header, 'If-Modified-Since: ' . $LastModified);
}
// Only add this header if server returned an ETag value, otherwise
// Connotea doesn't play nice.
if ($ETag != "''")
{
array_push ($if_header,'If-None-Match: ' . $ETag);
}
if ($debug_headers)
{
print_r($if_header);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_HEADER, 1);
// curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
if ($check)
{
curl_setopt ($ch, CURLOPT_HTTPHEADER, $if_header);
}
if ($config['proxy_name'] != '')
{
curl_setopt ($ch, CURLOPT_PROXY, $config['proxy_name'] . ":" . $config['proxy_port']);
}
$curl_result = curl_exec ($ch);
if(curl_errno ($ch) != 0 )
{
// Problems with CURL
$result = curl_errno ($ch);
}
else
{
$info = curl_getinfo($ch);
$header = substr($curl_result, 0, $info['header_size']);
$result = $info['http_code'];
if ($debug_headers)
{
echo $header;
}
if ($result == 200)
{
// HTTP 200 means the feed exists and has been modified since we
// last visited (or this is the first time we've looked at it)
// so we grab it, remembering to trim off the header. We store
// details of the feed in our database.
$result = 0;
$rss = substr ($curl_result, $info['header_size']);
// Retrieve ETag and LastModified
$rows = split ("\n", $header);
foreach ($rows as $row)
{
$parts = split (":", $row, 2);
if (count($parts) == 2)
{
if (preg_match("/ETag/", $parts[0]))
{
$ETag = trim($parts[1]);
}
if (preg_match("/Last-Modified/", $parts[0]))
{
$LastModified = trim($parts[1]);
}
}
}
// Store in database conditional headers in database
$sql = 'UPDATE feed SET last_modified=' . $db->qstr($LastModified)
. ', etag=' . $db->qstr($ETag)
. ', last_accessed = NOW()'
. ' WHERE (url = "' . $url . '")';
$sql_result = $db->Execute($sql);
if ($sql_result == false) die("failed [" . __LINE__ . "]: " . $sql);
}
}
return $result;
}
?>