forked from rakeshtembhurne/Facebook-Groups-Analytics
/
FbStats.php
539 lines (481 loc) · 16.2 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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
<?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;
/**
* 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 static function getFbInstance($params)
{
$fb = new Facebook(
array(
'appId' => $params['appId'],
'secret' => $params['secret'],
'cookie' => true,
)
);
return $fb;
}//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(
'req_perms' => implode(',', $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()
/**
* Wall Post - calls Facebook api and post on groups wall.
* @throws Exception
* @return boolean
*/
public function wallPost($sourceId, $message)
{
$posted = 0;
$wall_post = array(
'access_token' => $this->accessToken,
'message' => $message,
);
try {
$data = $this->facebook->api(
"/{$sourceId}/feed",
'POST',
$wall_post
);
$posted = 1;
} catch (FacebookApiException $e) {
$result = $e->getResult();
throw new Exception($result['error']['message']);
}
return $posted;
}//end wallPost()
/**
* 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, $extra_params=null)
{
$userData = array(
'id' => null,
'name' => null,
'totalStatus' => 0,
'totalStatusChars' => 0,
'totalLinks' => 0,
'totalPictures' => 0,
'didLike' => 0,
'didComment' => 0,
'didCommentChars' => 0,
'gotLikesOnComments' => 0,
'gotTags' => 0,
);
$postData = array(
'from_id' => null,
'name' => null,
'message' => null,
'gotLikes' => 0,
'gotComments' => 0,
);
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'];
}
$posts[$entry['id']] = $postData;
$posts[$entry['id']]['id'] = $entry['id'];
$posts[$entry['id']]['name'] = $entry['from']['name'];
$posts[$entry['id']]['from_id'] = $entry['from']['id'];
}
// Status messages.
if ($entry['type'] === 'status') {
// Add Status count.
if ( strtotime($entry['created_time']) >= strtotime($extra_params['since']) && strtotime($entry['created_time']) <= strtotime($extra_params['until']) ) {
if( $extra_params['minLines'] || $extra_params['minWords'] ){
$message_lines = $message_words = array();
if( $extra_params['minLines'] ){
$message_lines = explode("\n", $entry['message']);
foreach( $message_lines as $key=>$val){
$val = preg_replace('/\s+/', ' ', $val);
if( empty($val) || $val==" " ){
unset($message_lines[$key]);
}
}
}
if( $extra_params['minWords'] ){
$message_words = explode(" ", $entry['message']);
foreach( $message_words as $key=>$val){
$val = str_replace("\n"," ",$val);
$val = preg_replace('/\s+/', ' ', $val);
if( empty($val) || $val==" " ){
unset($message_words[$key]);
}
}
}
if( (count($message_lines) > $extra_params['minLines'] ) || (count($message_words) > $extra_params['minWords'] ) ){
$users[$entry['from']['id']]['totalStatus']++;
}
}else{
$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']);
}
}
}
// Links.
if ($entry['type'] === 'link') {
if ( strtotime($entry['created_time']) >= strtotime($extra_params['since']) && strtotime($entry['created_time']) <= strtotime($extra_params['until']) ) {
if( !$extra_params['ignoreLinks'] ){
// Add Status count.
$users[$entry['from']['id']]['totalStatus']++;
}
// Add Link count.
$users[$entry['from']['id']]['totalLinks']++;
}
}
if ($entry['type'] === 'photo') {
if ( strtotime($entry['created_time']) >= strtotime($extra_params['since']) && strtotime($entry['created_time']) <= strtotime($extra_params['until']) ) {
if( !$extra_params['ignorePhotos'] ){
// Add Status count.
$users[$entry['from']['id']]['totalStatus']++;
}
// Add Picture count.
$users[$entry['from']['id']]['totalPictures']++;
}
}
//Add messages
if (isset($entry['message']) === true) {
$message = explode(" ", $entry['message']);
$message_part = implode(" ", array_splice($message, 0, 5));
$posts[$entry['id']]['message'] = preg_replace('/\s+/', ' ', str_replace("\n"," ",$message_part))."..";
}
// 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
}
if (isset($entry['likes']['count']) === true) {
if ( strtotime($entry['created_time']) >= strtotime($extra_params['since']) && strtotime($entry['created_time']) <= strtotime($extra_params['until']) ) {
$posts[$entry['id']]['gotLikes']
= (int) $entry['likes']['count'];
}
}//end if
}//end if
if (isset($entry['comments']) === true) {
if (isset($entry['comments']['data']) === true) {
// 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 comment counter.
if ( strtotime($entry['created_time']) >= strtotime($extra_params['since']) && strtotime($entry['created_time']) <= strtotime($extra_params['until']) ) {
if( $extra_params['selfComments'] ){
if( $entry['from']['id'] != $comment['from']['id'] ){
$posts[$entry['id']]['gotComments']++;
}
}else{
$posts[$entry['id']]['gotComments']++;
}
}
// Increase didComment for this user.
if ( strtotime($comment['created_time']) >= strtotime($extra_params['since']) && strtotime($comment['created_time']) <= strtotime($extra_params['until']) ) {
$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
}elseif (isset($entry['comments']['count']) === true) {
$posts[$entry['id']]['gotComments'] =
(int) $entry['comments']['count'];
}//end if
}//end if
}//end foreach
return array ($users, $posts);
}//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, $params=null)
{
${$statName} = array();
$name = array();
$sort_array = array();
list ($users, $posts) = $this->getFeedUsers($feed, $params);
if( in_array($statName , array('totalStatus','totalPictures','didComment','totalLinks')) ){
$sort_array = $users;
}else{
$sort_array = $posts;
}
foreach ($sort_array as $key => $value) {
${$statName}[$key] = $value[$statName];
$name[$key] = $value['name'];
}
array_multisort(${$statName}, SORT_DESC, SORT_NUMERIC, $name, $sort_array);
if ($count !== null && count($sort_array) > $count) {
$sort_array = array_slice($sort_array, 0, $count);
}
return $sort_array;
}//end getTopUsers()
}//end class
?>