forked from rakeshtembhurne/Facebook-Groups-Analytics
/
FbStats.php
467 lines (402 loc) · 14.5 KB
/
FbStats.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
<?php
/**
* Facebook Statistics
*
* PHP version 5.3
*
* @category Class
* @package Facebook-Groups-Analytics
* @author Rakesh Tembhurne <rakesh@tembhurne.com>
* @license http://www.gnu.org/licenses/gpl-3.0.html GPLv3
* @link https://github.com/rakeshtembhurne/Facebook-Groups-Analytics
*/
require 'facebook/facebook.php';
/**
* Facebook Statistics class
*
* @category Class
* @package Facebook-Groups-Analytics
* @author Rakesh Tembhurne <rakesh@tembhurne.com>
* @license http://www.gnu.org/licenses/gpl-3.0.html GPLv3
* @link https://github.com/rakeshtembhurne/Facebook-Groups-Analytics
*/
class FbStats
{
/**
* Variable used for instance of Facebook class
*
* @var object
*/
public $facebook;
/**
* Variable used for facebook user's data
*
* @var array
*/
public $user;
/**
* Variable used for storing access token required for api calls.
*
* @var string
*/
public $accessToken;
/**
* Variable used for permissions required.
*
* @var type
*/
public $permissions;
/**
* Variable used for url to which script will redirect after user is logged in.
*
* @var type
*/
public $afterLoginUrl;
public static $instance;
/**
* Constructor method
*
* This method is used to create the facebook instance, set other important
* variables, log in and get needed Facebook permissions from user.
*
* @param array $params parameters
*
* @return void
*/
public function __construct($params)
{
// Creating facebook instance.
$this->facebook = $this->getFbInstance($params);
// Set class variables.
$this->permissions = $params['permissionsArray'];
$this->afterLoginUrl = $params['afterLoginUrl'];
// Login and check for permissions.
$this->logIn();
$this->accessToken = $this->facebook->getAccessToken();
$this->askPermissions();
}//end __construct()
/**
* This static function gets Facebook class instance.
*
* @param array $params parameters containing facebook application details.
*
* @return object
*/
public function getFbInstance($params)
{
self::$instance = new Facebook(
array(
'appId' => $params['appId'],
'secret' => $params['secret'],
'cookie' => true,
)
);
return self::$instance;
}//end getFbInstance()
/**
* Ask Permissions
*
* This method is used for getting user permissions from facebook and checking
* if user has given necessary permissions to the application.
*
* @throws Exception
* @return void
*/
public function askPermissions()
{
// Gets user permissions.
try {
$permissionsList = $this->facebook->api(
'/me/permissions',
'GET',
array('access_token' => $this->accessToken)
);
} catch (FacebookApiException $e) {
$result = $e->getResult();
throw new Exception($result['error']['message']);
}
// If any permission is not granted, redirects for getting permissions.
$permissionsNeeded = $this->permissions;
foreach ($permissionsNeeded as $perm) {
if (isset($permissionsList['data'][0][$perm]) === false
|| $permissionsList['data'][0][$perm] !== 1
) {
$loginUrlParams = array(
'scope' => implode(',', $this->permissions),
'fbconnect' => 1,
'display' => 'page',
'next' => $this->afterLoginUrl,
);
$loginUrl = $this->facebook->getLoginUrl($loginUrlParams);
header("Location: {$loginUrl}");
exit();
}
}//end foreach
}//end askPermissions()
/**
* Logs user in to facebook.
*
* @return void
*/
public function logIn()
{
$this->user = $this->facebook->getUser();
if ($this->user === 0) {
$loginUrlParams = array(
'scope' => explode(',', $this->permissions),
'fbconnect' => 1,
'display' => 'page',
'next' => $this->afterLoginUrl,
);
$loginUrl = $this->facebook->getLoginUrl($loginUrlParams);
// Redirect to the login URL on facebook.
header("Location: {$loginUrl}");
exit();
}
}//end logIn()
/**
* Get Feed - calls Facebook api and get feed.
*
* @param array $params array of source_id, limit, offset, until, since
*
* @throws Exception
* @return array
*/
public function getFeed($params)
{
if (empty($params) === false) {
// Source id.
if (isset($params['sourceId']) === true) {
$sourceId = $params['sourceId'];
unset($params['sourceId']);
} else {
$sourceId = 'me';
}
// Limits number of feed.
if (isset($params['limit']) === false) {
$params['limit'] = 50;
}
// Offet.
if (isset($params['offset']) === false) {
$params['offset'] = 0;
}
// Time since feed needed.
if (isset($params['since']) === false) {
$params['since'] = 'yesterday';
}
// Time until feed needed.
if (isset($params['until']) === false) {
$params['until'] = 'now';
}
// Create url from paramenters.
$urlParams = '?';
foreach ($params as $key => $value) {
$urlParams .= "{$key}={$value}&";
}
}//end if
$data = array();
try {
$data = $this->facebook->api(
"/{$sourceId}/feed{$urlParams}",
'GET',
array('access_token' => $this->accessToken)
);
} catch (FacebookApiException $e) {
$result = $e->getResult();
throw new Exception($result['error']['message']);
}
return $data;
}//end getFeed()
/**
* Get Info
*
* Gets information by facebook api call. It should work with user, group, or
* page if valid id is passed.
*
* @param type $id id
*
* @throws Exception
* @return array
*/
public function getInfo($id)
{
$data = array();
try {
$data = $this->facebook->api("/{$id}");
} catch (FacebookApiException $e) {
$result = $e->getResult();
throw new Exception($result['error']['message']);
}
return $data;
}//end getInfo()
/**
* Get feed users - extracts array of users with statistics from facebook feed.
*
* @param type $feed facebook feed
*
* @return array
*/
public function getFeedUsers($feed)
{
$userData = array(
'id' => null,
'name' => null,
'totalStatus' => 0,
'totalLinks' => 0,
'totalStatusChars' => 0,
'didLike' => 0,
'didComment' => 0,
'didCommentChars' => 0,
'gotLikes' => 0,
'gotComments' => 0,
'gotLikesOnComments' => 0,
'gotTags' => 0,
);
$users = array();
foreach ($feed['data'] as $entry) {
if (isset($entry['from']) === true) {
if (isset($users[$entry['from']['id']]) === false) {
$users[$entry['from']['id']] = $userData;
// Set user's name.
$users[$entry['from']['id']]['name'] = $entry['from']['name'];
// Set user's id.
$users[$entry['from']['id']]['id'] = $entry['from']['id'];
}
}
// Status messages.
if ($entry['type'] === 'status') {
// Add Status count.
$users[$entry['from']['id']]['totalStatus']++;
// Add total characters of status update.
if (isset($entry['message']) === true) {
// FIXME: non-english characters make above condition false.
$users[$entry['from']['id']]['totalStatusChars']
+= strlen($entry['message']);
}
}//end if
// Links.
if ($entry['type'] === 'link') {
// Add Status count.
$users[$entry['from']['id']]['totalLinks']++;
}
// Likes.
if (isset($entry['likes']) === true) {
if (isset($entry['likes']['data']) === true) {
$users[$entry['from']['id']]['gotLikes']
+= count($entry['likes']['data']);
// Loop through likers.
foreach ($entry['likes']['data'] as $like) {
// If user is not in the list, add.
if (isset($users[$like['id']]) === false) {
$users[$like['id']] = $userData;
// Set user's name.
$users[$like['id']]['name'] = $like['name'];
// Set user's id.
$users[$like['id']]['id'] = $like['id'];
}//end if
// Increase didComment.
$users[$like['id']]['didLike']++;
}//end foreach
} else if (isset($entry['likes']['count']) === true) {
$users[$entry['from']['id']]['gotLikes']
+= (int) $entry['likes']['count'];
}//end if
}//end if
if (isset($entry['comments']) === true) {
if (isset($entry['comments']['data']) === true) {
// Increase comment counter.
$users[$entry['from']['id']]['gotComments']
+= count($entry['comments']['data']);
// Loop through each comment.
foreach ($entry['comments']['data'] as $comment) {
// If commentator is not in the list, add.
if (isset($users[$comment['from']['id']]) === false) {
$users[$comment['from']['id']] = $userData;
// Set user's name.
$users[$comment['from']['id']]['name']
= $comment['from']['name'];
// Set user's id.
$users[$comment['from']['id']]['id']
= $comment['from']['id'];
}
// Increase didComment for this user.
$users[$comment['from']['id']]['didComment']++;
// Increase didCommentChars.
$users[$comment['from']['id']]['didCommentChars'] +=
strlen($comment['message']);
// Got likes on comments?
if (isset($comment['likes']) === true) {
$users[$comment['from']['id']]['gotLikesOnComments'] +=
(int) $comment['likes'];
}
// Are people tagged in this message?
if (isset($comment['message_tags']) === true) {
foreach ($comment['message_tags'] as $tag) {
// Check if user exists, otherwise add.
if (isset($users[$tag['id']]) === false) {
$users[$tag['id']] = $userData;
// Set user's name.
$users[$tag['id']]['name'] = $tag['name'];
// Set user's id.
$users[$tag['id']]['id'] = $tag['id'];
}
}//end foreach
$users[$tag['id']]['gotTags']++;
}
}//end foreach
} else if (isset($entry['comments']['count']) === true) {
$users[$entry['from']['id']]['gotComments'] +=
(int) $entry['comments']['count'];
}//end if
}//end if
}//end foreach
return $users;
}//end getFeedUsers()
/**
* Get Top Users functions extracts userf from given feed
*
* @param array $feed facebook feed
* @param string $statName statistic name to sort with
* @param int $count number of users to return
*
* @return type
*/
public function getTopUsers($feed, $statName, $count=null)
{
${$statName} = array();
$name = array();
$users = $this->getFeedUsers($feed);
foreach ($users as $key => $value) {
${$statName}[$key] = $value[$statName];
$name[$key] = $value['name'];
}
array_multisort(${$statName}, SORT_DESC, SORT_NUMERIC, $name, $users);
if ($count !== null && count($users) > $count) {
$users = array_slice($users, 0, $count);
}
return $users;
}//end getTopUsers()
/**
* This method sends data to facebook.
*
* @param string $sourceId facebook source to which data is to be sent
* @param string $message message that need to be posted on the facebook
*
* @return void
*/
public function sendInfo($sourceId, $message)
{
try {
$data = $this->facebook->api(
"/{$sourceId}/feed",
'POST',
array('message' => $message)
);
$posted = 1;
} catch (FacebookApiException $e) {
$result = $e->getResult();
throw new Exception($result['error']['message']);
}
}//end sendInfo()
}//end class
?>