-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathshare_count.php
351 lines (327 loc) · 13.1 KB
/
share_count.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
<?php
require_once("config.php");
class shareCount {
private $config;
private $data;
private $url;
private $format;
private $callback;
private $cache;
private $cache_directory;
private $cache_time;
function __construct() {
$this->config = new Config;
$this->cache = $this->config->cache;
$this->cache_directory = $this->config->cache_directory;
$this->cache_time = $this->config->cache_time;
$this->data = new stdClass;
}
private function getVar($var, $strict = false) {
if(array_key_exists($var, $_REQUEST) && $_REQUEST[$var] !== "") return $_REQUEST[$var];
elseif($strict) return false;
else return $this->config->$var;
}
public function get($url, $services = '') {
$this->url = $url;
$this->services = $services;
$this->data->url = $this->url;
$this->data->shares = new stdClass;
$this->data->shares->total = 0;
return $this->getShares($url)->shares;
}
public function serve() {
$this->url = $this->url ?: filter_input(INPUT_GET, 'url', FILTER_SANITIZE_URL);
$this->services = $this->services ?: filter_input(INPUT_GET, 'services', FILTER_SANITIZE_URL);
// kill the script if no URL provided
if(!$this->url) die("Error: No URL specified.");
$this->setFormat($this->format ?: $this->getVar('format'));
$this->callback = $this->callback ?: $this->getCallback();
$this->data = new stdClass;
$this->data->url = $this->url;
$this->data->shares = new stdClass;
$this->data->shares->total = 0;
$data = $this->getData();
return $data;
}
// validate and return the callback
private function getCallback(){
return filter_var($this->getVar('callback'), FILTER_VALIDATE_REGEXP,
array(
"options" => array(
"regexp"=>"/^\w+$/"
)
)
);
}
// set format of the output
private function setFormat ($format) {
switch($format) {
case "xml":
$this->format = 'xml';
header ("Content-Type:text/xml");
break;
case "jsonp":
$this->format = 'jsonp';
header ("Content-Type: application/javascript");
break;
case "json": // only here for reference
default:
if($this->getCallback()) {
$this->format = 'jsonp';
header ("Content-Type: application/javascript");
}
else {
$this->format = 'json';
header ("Content-Type:application/json");
}
}
return $format;
}
// query API to get share counts
public function getShares($url = '', $services = '') {
$url = $url ?: $this->url;
$services = $services ?: $this->services;
$shareLinks = array(
"facebook" => array("http://graph.facebook.com/?ids=",'GET'),
"google" => array("https://apis.google.com/u/0/se/0/_/+1/sharebutton?plusShare=true&url=",'GET'),
"linkedin" => array("https://www.linkedin.com/countserv/count/share?format=json&url=",'GET'),
"pinterest" => array("http://api.pinterest.com/v1/urls/count.json?url=",'GET'),
"stumbleupon" => array("http://www.stumbleupon.com/services/1.01/badge.getinfo?url=",'GET'),
"reddit" => array("http://www.reddit.com/api/info.json?&url=",'GET'),
"buffer" => array("https://api.bufferapp.com/1/links/shares.json?url=",'GET'),
"vk" => array("http://vk.com/share.php?act=count&index=1&url=",'GET'),
"addthis" => array("http://api-public.addthis.com/url/shares.json?url=",'GET'),
"flattr" => array("https://api.flattr.com/rest/v2/things/lookup/?url=",'GET'),
"xing" => array("https://www.xing-share.com/spi/shares/statistics?url=",'POST')
);
if ($services) {
if (!is_array($services)) {
$services = explode(',', $services);
}
foreach($services as $service) {
$provider = $shareLinks[$service];
@$this->getCount($service, $provider[0] . $this->url, $provider[1]);
}
} else {
foreach($shareLinks as $service=>$provider) {
@$this->getCount($service, $provider[0] . $this->url, $provider[1]);
}
}
switch($this->format) {
case 'xml':
return $this->generateValidXmlFromObj($this->data, "data");
case 'json':
case 'jsonp':
return json_encode($this->data);
default:
return $this->data;
}
}
// query API to get share counts
private function getCount($service, $url, $method = 'GET'){
if(function_exists('curl_version')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'shareCount/1.2 by abemedia');
if($method=='POST'){
$url = explode('?',$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$url[1]);
$url = $url[0];
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
@$data = curl_exec($ch);
curl_close($ch);
}
else {
if($method=='POST'){
$url = explode('?',$url);
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $url[1]
));
$url = $url[0];
$data = @file_get_contents($url, false, stream_context_create($params));
}
else {
$data = @file_get_contents($url);
}
}
if ($data) {
switch($service) {
case "facebook":
$data = json_decode($data, true);
$count = $data[$this->url]["share"]["share_count"];
break;
case "google":
preg_match( '/window\.__SSR = {c: ([\d]+)/', $data, $matches);
$count = isset($matches[1])?$matches[1]:0;
break;
case "pinterest":
$data = substr( $data, 13, -1);
case "linkedin":
$data = json_decode($data);
$count = $data->count;
break;
case "stumbleupon":
$data = json_decode($data);
$count = $data->result->in_index?$data->result->views:0;
break;
case "reddit":
$data = json_decode($data);
$count = 0;
foreach($data->data->children as $child) {
$count+= $child->data->score;
}
break;
case "addthis":
case "buffer":
$data = json_decode($data);
$count = $data->shares;
break;
case "vk":
$data = preg_match('/^VK.Share.count\(\d+,\s+(\d+)\);$/i', $data, $matches);
$count = $matches[1];
break;
case "flattr":
$data = json_decode($data);
$count = @$data->flattrs;// maybe not : {"message":"not_found","description":"No thing was found"}
break;
case "xing":
$data = json_decode($data);
$count = @$data->share_counter;
break;
default:
// kill the script if trying to fetch from a provider that doesn't exist
die("Error: Service (".$service.") not found");
}
$count = (int) $count;
$this->data->shares->total += $count;
$this->data->shares->$service = $count;
} else {
$this->data->shares->$service = '';
}
return;
}
// Get data and return it. If cache is active check for cached data and create it if unsuccessful.
private function getData() {
if($this->cache) $key = md5($this->url) . '.' . ($this->format == 'jsonp' ? 'json' : $this->format);
switch($this->cache) {
case 'memcache':
if(!function_exists('memcache_connect')) {
die('Memcache isn\'t installed');
}
else {
$memcache = new Memcache;
$memcache->addServer($this->config->cache_server, $this->config->cache_port, $this->config->cache_persistent);
if(!$memcache->connect($this->config->cache_server, $this->config->cache_port)) {
die('Couldn\'t connect to Memcache host');
}
$data = $memcache->get($key);
if ($data === false) {
$data = $this->getShares();
$memcache->set($key, $data, $this->cache_time);
}
}
break;
case 'apc':
if(!function_exists('apc_exists')) {
die('APC isn\'t installed');
}
if (apc_exists($key)) {
$data = apc_fetch($key);
}
else {
$data = $this->getShares();
apc_store($key, $data, $this->cache_time);
}
break;
case 'file':
$data = $this->getCacheFile($key);
break;
default:
$data = $this->getShares();
}
// if the format is JSONP wrap in callback function
if($this->format == 'jsonp') $data = $this->callback . '(' . $data . ')';
return $data;
}
// get cache file - create if doesn't exist
private function getCacheFile($key) {
if (!file_exists($this->cache_directory)) {
mkdir($this->cache_directory, 0755, true);
}
$file = $this->cache_directory . $key;
$file_created = ((@file_exists($file))) ? @filemtime($file) : 0;
@clearstatcache();
if (time() - $this->cache_time < $file_created) {
return file_get_contents($file);
}
$data = $this->getShares();
$fp = @fopen($file, 'w');
@fwrite($fp, $data);
@fclose($fp);
return $data;
}
// Delete expired file cache. Use "kill" parameter to also flush the memory and delete all cache files.
public function cleanCache($kill = null) {
// flush memcache
if($kill) {
switch($this->cache) {
case 'memcache':
$memcache = new Memcache;
$memcache->flush();
break;
case 'apc':
apc_clear_cache();
apc_clear_cache('user');
apc_clear_cache('opcode');
break;
}
}
// delete cache files
if ($handle = @opendir($this->cache_directory)) {
while (false !== ($file = @readdir($handle))) {
if ($file != '.' and $file != '..') {
$file_created = ((@file_exists($file))) ? @filemtime($file) : 0;
if (time() - $this->cache_time < $file_created or $kill) {
echo $file . ' deleted.<br>';
@unlink($this->cache_directory . '/' . $file);
}
}
}
@closedir($handle);
}
}
// output share counts as XML
// functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/
public static function generateValidXmlFromObj(stdClass $obj, $node_block='nodes', $node_name='node') {
$arr = get_object_vars($obj);
return self::generateValidXmlFromArray($arr, $node_block, $node_name);
}
public static function generateValidXmlFromArray($array, $node_block='nodes', $node_name='node') {
$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '<' . $node_block . '>';
$xml .= self::generateXmlFromArray($array, $node_name);
$xml .= '</' . $node_block . '>';
return $xml;
}
private static function generateXmlFromArray($array, $node_name) {
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES);
}
return $xml;
}
}