summaryrefslogtreecommitdiff
path: root/hauth/Hybrid/Providers/Facebook.php
blob: ab48370cf56b73aea7a53a95be21ae217b51fa30 (plain)
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
<?php

use Facebook\Exceptions\FacebookSDKException;
use Facebook\Facebook as FacebookSDK;

/* !
 * HybridAuth
 * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
 * (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
 */

/**
 * Hybrid_Providers_Facebook provider adapter based on OAuth2 protocol
 * Hybrid_Providers_Facebook use the Facebook PHP SDK created by Facebook
 * http://hybridauth.sourceforge.net/userguide/IDProvider_info_Facebook.html
 */
class Hybrid_Providers_Facebook extends Hybrid_Provider_Model {

    /**
     * Default permissions, and a lot of them. You can change them from the configuration by setting the scope to what you want/need.
     * For a complete list see: https://developers.facebook.com/docs/facebook-login/permissions
     *
     * @link https://developers.facebook.com/docs/facebook-login/permissions
     * @var array $scope
     */
    public $scope = array('email', 'public_profile');

    /**
     * Provider API client
     *
     * @var \Facebook\Facebook
     */
    public $api;

    public $useSafeUrls = true;

    /**
     * {@inheritdoc}
     */
    function initialize() {
        if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) {
            throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4);
        }

        if (isset($this->config['scope'])) {
            $scope = $this->config['scope'];
            if (is_string($scope)) {
                $scope = explode(",", $scope);
            }
            $scope = array_map('trim', $scope);
            $this->scope = $scope;
        }

        $trustForwarded = isset($this->config['trustForwarded']) ? (bool)$this->config['trustForwarded'] : false;

        // Include 3rd-party SDK.
        $this->autoLoaderInit();

        $this->api = new FacebookSDK([
            'app_id' => $this->config["keys"]["id"],
            'app_secret' => $this->config["keys"]["secret"],
            'default_graph_version' => !empty($this->config['default_graph_version']) ? $this->config['default_graph_version'] : 'v2.12',
            'trustForwarded' => $trustForwarded,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    function loginBegin() {

        $this->endpoint = $this->params['login_done'];
        $helper = $this->api->getRedirectLoginHelper();

        // Use re-request, because this will trigger permissions window if not all permissions are granted.
        $url = $helper->getReRequestUrl($this->endpoint, $this->scope);

        // Redirect to Facebook
        Hybrid_Auth::redirect($url);
    }

    /**
     * {@inheritdoc}
     */
    function loginFinish() {

        $helper = $this->api->getRedirectLoginHelper();
        if (isset($_GET['state'])) {
          $helper->getPersistentDataHandler()->set('state', $_GET['state']);
        }
        try {
            $accessToken = $helper->getAccessToken($this->params['login_done']);
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            throw new Hybrid_Exception('Facebook Graph returned an error: ' . $e->getMessage());
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            throw new Hybrid_Exception('Facebook SDK returned an error: ' . $e->getMessage());
        }

        if (!isset($accessToken)) {
            if ($helper->getError()) {
                throw new Hybrid_Exception(sprintf("Could not authorize user, reason: %s (%d)", $helper->getErrorDescription(), $helper->getErrorCode()));
            } else {
                throw new Hybrid_Exception("Could not authorize user. Bad request");
            }
        }

        try {
            // Validate token
            $oAuth2Client = $this->api->getOAuth2Client();
            $tokenMetadata = $oAuth2Client->debugToken($accessToken);
            $tokenMetadata->validateAppId($this->config["keys"]["id"]);
            $tokenMetadata->validateExpiration();

            // Exchanges a short-lived access token for a long-lived one
            if (!$accessToken->isLongLived()) {
                $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
            }
        } catch (FacebookSDKException $e) {
            throw new Hybrid_Exception($e->getMessage(), 0, $e);
        }

        $this->setUserConnected();
        $this->token("access_token", $accessToken->getValue());
    }

    /**
     * {@inheritdoc}
     */
    function logout() {
        parent::logout();
    }

    /**
    * Update user status
    *
    * @param mixed  $status An array describing the status, or string
    * @param string $pageid (optional) User page id
    * @return array
    * @throw Exception
    */
    function setUserStatus($status, $pageid = null) {

      if (!is_array($status)) {
          $status = array('message' => $status);
      }

      $access_token = null;

      if (is_null($pageid)) {
          $pageid = 'me';
          $access_token = $this->token('access_token');

          // if post on page, get access_token page
      } else {

          foreach ($this->getUserPages(true) as $p) {
              if (isset($p['id']) && intval($p['id']) == intval($pageid)) {
                  $access_token = $p['access_token'];
                  break;
              }
          }

          if (is_null($access_token)) {
              throw new Exception("Update user page failed, page not found or not writable!");
          }
      }

      try {
          $response = $this->api->post('/' . $pageid . '/feed', $status, $access_token);
      } catch (FacebookSDKException $e) {
          throw new Exception("Update user status failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
      }

      return $response;
    }

    /**
    * {@inheridoc}
    */
   function getUserPages($writableonly = false) {
       if (!in_array('manage_pages', $this->scope)) {
           throw new Exception("Get user pages requires manage_page permission!");
       }

       try {
           $pages = $this->api->get("/me/accounts", $this->token('access_token'));
           $pages = $pages->getDecodedBody();
       } catch (FacebookApiException $e) {
           throw new Exception("Cannot retrieve user pages! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
       }

       if (!isset($pages['data'])) {
           return array();
       }

       if (!$writableonly) {
           return $pages['data'];
       }

       $wrpages = array();
       foreach ($pages['data'] as $p) {
           if (isset($p['perms']) && in_array('CREATE_CONTENT', $p['perms'])) {
               $wrpages[] = $p;
           }
       }

       return $wrpages;
    }

    /**
     * {@inheritdoc}
     */
    function getUserProfile() {
        try {
            $fields = array(
                'id',
                'name',
                'first_name',
                'last_name',
                'link',
                'website',
                'gender',
                'locale',
                'about',
                'email',
                'hometown',
                'location',
                'birthday'
            );
            $response = $this->api->get('/me?fields=' . implode(',', $fields), $this->token('access_token'));
            $data = $response->getDecodedBody();
        } catch (FacebookSDKException $e) {
            throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e);
        }

        // Store the user profile.
        $this->user->profile->identifier = (array_key_exists('id', $data)) ? $data['id'] : "";
        $this->user->profile->displayName = (array_key_exists('name', $data)) ? $data['name'] : "";
        $this->user->profile->firstName = (array_key_exists('first_name', $data)) ? $data['first_name'] : "";
        $this->user->profile->lastName = (array_key_exists('last_name', $data)) ? $data['last_name'] : "";
        $this->user->profile->photoURL = $this->getUserPhoto($this->user->profile->identifier);
        $this->user->profile->profileURL = (array_key_exists('link', $data)) ? $data['link'] : "";
        $this->user->profile->webSiteURL = (array_key_exists('website', $data)) ? $data['website'] : "";
        $this->user->profile->gender = (array_key_exists('gender', $data)) ? $data['gender'] : "";
        $this->user->profile->language = (array_key_exists('locale', $data)) ? $data['locale'] : "";
        $this->user->profile->description = (array_key_exists('about', $data)) ? $data['about'] : "";
        $this->user->profile->email = (array_key_exists('email', $data)) ? $data['email'] : "";
        $this->user->profile->emailVerified = (array_key_exists('email', $data)) ? $data['email'] : "";
        $this->user->profile->region = (array_key_exists("location", $data) && array_key_exists("name", $data['location'])) ? $data['location']["name"] : "";

        if (!empty($this->user->profile->region)) {
            $regionArr = explode(',', $this->user->profile->region);
            if (count($regionArr) > 1) {
                $this->user->profile->city = trim($regionArr[0]);
                $this->user->profile->country = trim(end($regionArr));
            }
        }

        if (array_key_exists('birthday', $data)) {
            $birtydayPieces = explode('/', $data['birthday']);

            if (count($birtydayPieces) == 1) {
                $this->user->profile->birthYear = (int)$birtydayPieces[0];
            } elseif (count($birtydayPieces) == 2) {
                $this->user->profile->birthMonth = (int)$birtydayPieces[0];
                $this->user->profile->birthDay = (int)$birtydayPieces[1];
            } elseif (count($birtydayPieces) == 3) {
                $this->user->profile->birthMonth = (int)$birtydayPieces[0];
                $this->user->profile->birthDay = (int)$birtydayPieces[1];
                $this->user->profile->birthYear = (int)$birtydayPieces[2];
            }
        }

        return $this->user->profile;
    }

    /**
     * Since the Graph API 2.0, the /friends endpoint only returns friend that also use your Facebook app.
     * {@inheritdoc}
     */
    function getUserContacts() {
        if (!in_array('user_friends', $this->scope)) {
           throw new Exception("Get user contacts requires user_friends permission!");
        }

        $apiCall = '?fields=link,name';
        $returnedContacts = array();
        $pagedList = true;

        while ($pagedList) {
            try {
                $response = $this->api->get('/me/friends' . $apiCall, $this->token('access_token'));
                $response = $response->getDecodedBody();
            } catch (FacebookSDKException $e) {
                throw new Hybrid_Exception("User contacts request failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
            }

            // Prepare the next call if paging links have been returned
            if (array_key_exists('paging', $response) && array_key_exists('next', $response['paging'])) {
                $pagedList = true;
                $next_page = explode('friends', $response['paging']['next']);
                $apiCall = $next_page[1];
            } else {
                $pagedList = false;
            }

            // Add the new page contacts
            $returnedContacts = array_merge($returnedContacts, $response['data']);
        }

        $contacts = array();
        foreach ($returnedContacts as $item) {

            $uc = new Hybrid_User_Contact();
            $uc->identifier = (array_key_exists("id", $item)) ? $item["id"] : "";
            $uc->displayName = (array_key_exists("name", $item)) ? $item["name"] : "";
            $uc->profileURL = (array_key_exists("link", $item)) ? $item["link"] : "https://www.facebook.com/profile.php?id=" . $uc->identifier;
            $uc->photoURL = $this->getUserPhoto($uc->identifier);

            $contacts[] = $uc;
        }

        return $contacts;
    }

    /**
     * Load the user latest activity, needs 'read_stream' permission
     *
     * @param string $stream Which activity to fetch:
     *      - timeline : all the stream
     *      - me       : the user activity only
     * {@inheritdoc}
     */
    function getUserActivity($stream = 'timeline') {
        try {
            if ($stream == "me") {
                $response = $this->api->get('/me/feed', $this->token('access_token'));
            } else {
                $response = $this->api->get('/me/home', $this->token('access_token'));
            }
            $response = $response->getDecodedBody();
        } catch (FacebookSDKException $e) {
            throw new Hybrid_Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
        }

        if (!$response || !count($response['data'])) {
            return array();
        }

        $activities = array();
        foreach ($response['data'] as $item) {

            $ua = new Hybrid_User_Activity();

            $ua->id = (array_key_exists("id", $item)) ? $item["id"] : "";
            $ua->date = (array_key_exists("created_time", $item)) ? strtotime($item["created_time"]) : "";

            if ($item["type"] == "video") {
                $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
            }

            if ($item["type"] == "link") {
                $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
            }

            if (empty($ua->text) && isset($item["story"])) {
                $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
            }

            if (empty($ua->text) && isset($item["message"])) {
                $ua->text = (array_key_exists("message", $item)) ? $item["message"] : "";
            }

            if (!empty($ua->text)) {
                $ua->user->identifier = (array_key_exists("id", $item["from"])) ? $item["from"]["id"] : "";
                $ua->user->displayName = (array_key_exists("name", $item["from"])) ? $item["from"]["name"] : "";
                $ua->user->profileURL = "https://www.facebook.com/profile.php?id=" . $ua->user->identifier;
                $ua->user->photoURL = $this->getUserPhoto($ua->user->identifier);

                $activities[] = $ua;
            }
        }

        return $activities;
    }

    /**
     * Returns a photo URL for give user.
     *
     * @param string $id
     *   The User ID.
     *
     * @return string
     *   A photo URL.
     */
    function getUserPhoto($id) {
        $photo_size = isset($this->config['photo_size']) ? $this->config['photo_size'] : 150;

        return "https://graph.facebook.com/{$id}/picture?width={$photo_size}&height={$photo_size}";
    }

}